Multi-Step Prompt for Writing Python Unit Tests (Explain, Plan, Execute)

A three-step chain that has the model explain a Python function, plan test scenarios, then write a pytest suite that follows the plan.

  • 🤖 ChatGPT
  • 🗂️ Coding

Last verified: write-up checked

Prompt by OpenAI (openai/openai-cookbook) · Original source (opens in a new tab)

Multi-Step Prompt for Writing Python Unit Tests (Explain, Plan, Execute) — prompt preview

The prompt

prompt
Step 1 (explain), system message:
You are a world-class Python developer with an eagle eye for unintended bugs and edge cases. You carefully explain code with great detail and accuracy. You organize your explanations in markdown-formatted, bulleted lists.

Step 1 (explain), user message:
Please explain the following Python function. Review what each element of the function is doing precisely and what the author's intentions may have been. Organize your explanation as a markdown-formatted, bulleted list.

```python
{function_to_test}
```

Step 2 (plan), user message, sent after the model's explanation:
A good unit test suite should aim to:
- Test the function's behavior for a wide range of possible inputs
- Test edge cases that the author may not have foreseen
- Take advantage of the features of `{unit_test_package}` to make the tests easy to write and maintain
- Be easy to read and understand, with clean code and descriptive names
- Be deterministic, so that the tests always pass or fail in the same way

To help unit test the function above, list diverse scenarios that the function should be able to handle (and under each scenario, include a few examples as sub-bullets).

Step 2b (optional, only if the plan is short), user message:
In addition to those scenarios above, list a few rare or unexpected edge cases (and as before, under each edge case, include a few examples as sub-bullets).

Step 3 (execute), system message:
You are a world-class Python developer with an eagle eye for unintended bugs and edge cases. You write careful, accurate unit tests. When asked to reply only with code, you write all of your code in a single block.

Step 3 (execute), user message:
Using Python and the `{unit_test_package}` package, write a suite of unit tests for the function, following the cases above. Include helpful comments to explain each line. Reply only with code, formatted as follows:

```python
# imports
import {unit_test_package}  # used for our unit tests
{insert other imports as needed}

# function to test
{function_to_test}

# unit tests
{package_comment}
{insert unit test code here}
```

What it is

A three-step chain that has the model explain a Python function, plan test scenarios, then write a pytest suite that follows the plan. The notebook builds these messages inside one Python function. Our body lists them in order with step labels and placeholders in braces; the wording is unchanged. The step labels are ours. The prompt wording comes from the openai-cookbook repository (MIT licence, Copyright (c) 2025 OpenAI); the step labels are ours. Original author: OpenAI (openai/openai-cookbook).

Who it's for

  • Python developers
  • Test writers

سلسلة من ثلاث خطوات يشرح فيها النموذج دالة بايثون ثم يخطط لسيناريوهات الاختبار ثم يكتب اختبارات pytest وفق الخطة.

Examples

Function fed into the notebook

Prompt
prompt
def pig_latin(text):
    def translate(word):
        vowels = 'aeiou'
        if word[0] in vowels:
            return word + 'way'
        else:
            consonants = ''
            for letter in word:
                if letter not in vowels:
                    consonants += letter
                else:
                    break
            return word[len(consonants):] + consonants + 'ay'

    words = text.lower().split()
    translated_words = [translate(word) for word in words]
    return ' '.join(translated_words)

Expected output: The example function the notebook writes tests for.

Tips

  • Replace {function_to_test} with your function and {unit_test_package} with the package name (the notebook defaults to pytest).
  • The notebook warns to check any generated code before using it, as GPT makes plenty of mistakes.
  • Step 2b is only run when the plan has fewer top-level bullets than the minimum you want to cover.