Sub topic 3
Giving the assistant the context it needs
This chapter assumes you can write and run pytest tests, read a diff in code review, and have used an AI chat or coding assistant before. It covers how to write the prompt that comes before test and documentation generation. Later chapters build on it.
Why context decides the quality of the output
An assistant can only work from what is in its input. That input is your prompt, any code you paste, and any files the tool reads for you. It has not seen your repository, your team's conventions, or the conversation in which you decided how errors should be handled. Where it lacks information, it fills the gap with the most statistically common choice.
For tests, the common choice is often wrong for your project:
- It may pick
unittestwhen you use pytest. - It may import from a module path that does not exist.
- It may put the file in the wrong directory.
- It may "fix" the function under test so that the tests pass.
- It may compute expected values by repeating the function's own formula.
None of these is a reasoning failure. Each one is missing information. A good prompt closes those gaps before the assistant has to guess.
The running example
This chapter uses the same function as the rest of the tutorial. It has a documented contract and two error paths.
def apply_discount(price: float, percent: float) -> float:
"""Return price reduced by percent, rounded to two decimals.
Raises ValueError if price is negative or percent is outside 0-100.
"""
if price < 0:
raise ValueError("price must be non-negative")
if not 0 <= percent <= 100:
raise ValueError("percent must be between 0 and 100")
return round(price * (1 - percent / 100), 2)Suppose you paste this and write only: "Write tests for this." You will probably get something that runs, but you cannot rely on it. Compare that with the prompt below.
Anatomy of a useful prompt
Write pytest tests for the function below.
Context:
- Project uses pytest; tests live in tests/test_pricing.py.
- Import the function with: from pricing import apply_discount
- Use pytest.mark.parametrize for input/output tables.
Requirements:
- Cover normal values, the boundaries 0 and 100 for percent, and every ValueError path.
- Assert on expected values you derive from the docstring, not by re-implementing the function.
- Do not change the function under test.
<code of apply_discount here>The prompt has three parts, and each does a different job.
The task
The first line says what to produce: pytest tests, for one function. State the artifact and the framework explicitly. "Tests" alone leaves the framework open.
The context
These lines describe facts about your project that the assistant cannot see:
- The test framework and where test files live.
- The exact import statement. Without it, the assistant may write
import pricingorfrom src.pricing import ..., and the file will fail at collection time. - The style you want, here parametrized tables rather than many near-identical test functions.
The requirements
These lines describe what a finished answer must contain and what it must avoid. They name the coverage you expect (normal values, both boundaries, every error path). They also carry two constraints that prevent specific failures:
- "Derive expected values from the docstring, not by re-implementing the function." Without this, an assistant may write
assert apply_discount(100, 10) == round(100 * (1 - 10 / 100), 2). That is a tautology: it passes whatever the function does, so it can never catch a bug. - "Do not change the function under test." Without this, a failing test may be "resolved" by editing the code, which hides the failure you wanted to find.
Kinds of context and what each prevents
| Kind of context | Example | Failure it prevents |
|---|---|---|
| Code under test | The full function, with its signature and docstring | Invented signatures, wrong argument order |
| Framework and version | pytest, Python 3.11 | Tests in the wrong framework or with unsupported syntax |
| File layout and imports | `tests/test_pricing.py`, `from pricing import apply_discount` | Import errors, files in the wrong place |
| Conventions | Parametrize tables, naming pattern `test_<function>_<behavior>` | Output that does not match the rest of the suite |
| Coverage expectations | Boundaries and every `ValueError` path | Happy-path-only tests |
| Prohibitions | No edits to source, no tautological assertions | Self-confirming tests, silently changed code |
| Source of truth | "Use the docstring as the specification" | Expected values copied from the implementation |
You do not need every row for every request. Use the table as a checklist when output disappoints you. Find the missing row, add it, and ask again.
Pick a source of truth
The last row of the table matters most. If the assistant reads only the implementation, it tends to treat the implementation as correct. Any bug in the code then reappears in the tests as an expected value.
Name an independent source for expected behavior. For apply_discount it is the docstring. In other projects it might be a specification, an issue description, or a table of examples you write yourself. If the docstring is vague or missing, write the expected cases by hand in the prompt:
Expected behavior, from the pricing spec:
- apply_discount(100, 10) -> 90.0
- apply_discount(80, 25) -> 60.0
- apply_discount(50, 100) -> 0.0
- apply_discount(-1, 10) raises ValueErrorGiving a few worked values also tells the assistant how precise you want the expectations to be.
How the context flows
The diagram shows where each piece of context enters, and why the review step still follows the output.
The loop from review back to the prompt is how you improve results. If the draft is wrong, ask which piece of context was missing, add it, and generate again.
Ways to get context to the assistant
How you supply context depends on the tool:
- Chat window. You paste code and write the facts in the message. This gives you full control, but you must remember to include everything.
- Tool with file access. The assistant can read files in your repository. You can say "read
pricing.pyandtests/conftest.py" and let it find the real import path and existing fixtures. It will often match existing conventions better than a pasted description would. - Persistent project instructions. Many tools read a rules or instructions file for each project. Put stable facts there once, such as "we use pytest, tests mirror the
srclayout, never edit source files when asked for tests". Then each prompt only needs the facts specific to the task.
In all three cases, point the assistant at an existing test file when one is available. A sample of your real style is more reliable than a description of it.
If your project needs configuration for imports to work, say so. This is a common source of tests that fail only because of setup:
[tool.pytest.ini_options]
pythonpath = ["src"]
testpaths = ["tests"]With this in pyproject.toml, from pricing import apply_discount resolves when pricing.py sits in src/. Tell the assistant the layout you actually have, so it does not add sys.path hacks to the test file.
Keep context relevant and safe
More context is not always better. Two limits apply.
Relevance. Pasting a whole module when you want tests for one function dilutes the request. Include the function, anything it directly calls or depends on, and the conventions that apply. Leave out unrelated code. If a function depends on another one, include that function's signature even when you do not include its body.
Sensitivity. Everything you paste may leave your machine, depending on the tool and your organization's settings. Do not include API keys, tokens, customer data, or production connection strings. Replace them with placeholders. Check what your team permits before sending proprietary code to a hosted assistant. The risks chapter returns to this.
Common errors
- Describing the framework but not the import. The tests look right and fail at collection with
ModuleNotFoundError. Give the exact import line. - Asking for "full coverage" without defining it. The assistant may produce many tests that repeat the same path. List the categories you want: normal, boundary, error.
- Forgetting the prohibitions. If you do not say "do not change the function under test," some tools will modify the source when a test fails.
- Leaving the source of truth implicit. The expected values then come from the implementation, so bugs pass silently.
- Contradictory instructions. "Use unittest style" in a project instruction file and "use pytest" in the prompt produces inconsistent output. Keep stable rules in one place.
- Trusting the claimed paths. The assistant may say it wrote
tests/test_pricing.pywhile writing elsewhere. Check where the file landed and run it.
Check the result of a context change
After you add context, run the output rather than judging it by eye:
python -m pytest tests/test_pricing.py -qIf collection fails, the context about paths or imports is still wrong. If tests pass but you suspect they are tautological, that is a review question, covered in a later chapter.
Exercise
A teammate's prompt says "Write tests for apply_discount" and pastes the function. The assistant returns tests that use unittest, import from src.pricing, and compute each expected value with round(price * (1 - percent / 100), 2). Name three pieces of context to add to the prompt, and the problem each one fixes.
Show answer
(1) The framework and file location ("project uses pytest; tests live in tests/testpricing.py") fixes the wrong framework. (2) The exact import line ("from pricing import applydiscount") fixes the wrong module path. (3) A source of truth plus a prohibition ("derive expected values from the docstring, not by re-implementing the function") fixes the tautological assertions. Adding "do not change the function under test" is also reasonable to protect the source.
Exercise
You want tests for a function that reads a price from a config object, and your config file contains a live API key. What do you include in the prompt, and what do you remove?
Show answer
Include the function's code, the signature or a description of the config object's shape, the framework, the file path and import line, and the coverage requirements. Remove or replace the API key with a placeholder such as "<API_KEY>", since the key is not needed to describe the behavior and should not be sent to the assistant or end up in generated test files.