How to prompt AI to write unit tests
Write unit tests in Python using unittest for this function to get precise, runnable test code.PREREQUISITES
Python 3.8+OpenAI API key (free tier works)pip install openai>=1.0
Setup
Install the OpenAI Python SDK and set your API key as an environment variable to authenticate requests.
pip install openai>=1.0 Step by step
Use the OpenAI SDK to send a prompt that includes the function code and a clear instruction to generate unit tests using unittest. The example below demonstrates a complete runnable script.
import os
from openai import OpenAI
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
function_code = '''
def add(a, b):
"""Return the sum of a and b."""
return a + b
'''
prompt = f"""Write Python unit tests using unittest for the following function:\n{function_code}"""
response = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": prompt}]
)
test_code = response.choices[0].message.content
print(test_code) import unittest
class TestAddFunction(unittest.TestCase):
def test_add_positive_numbers(self):
self.assertEqual(add(2, 3), 5)
def test_add_negative_numbers(self):
self.assertEqual(add(-1, -1), -2)
def test_add_zero(self):
self.assertEqual(add(0, 0), 0)
if __name__ == '__main__':
unittest.main() Common variations
You can prompt for different testing frameworks like pytest, request async test functions, or use other models such as claude-3-5-haiku-20241022. Adjust the prompt accordingly.
import os
import anthropic
client = anthropic.Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])
function_code = '''
async def fetch_data(url):
"""Fetch data asynchronously from a URL."""
pass
'''
prompt = f"""Write async unit tests using pytest-asyncio for this function:\n{function_code}"""
message = client.messages.create(
model="claude-3-5-haiku-20241022",
max_tokens=1024,
system="You are a helpful assistant.",
messages=[{"role": "user", "content": prompt}]
)
print(message.content[0].text) # Example output with async pytest tests for fetch_data function
Troubleshooting
If the AI generates incomplete or incorrect tests, refine your prompt by specifying the expected input-output pairs, edge cases, and the testing framework explicitly. Also, verify your API key and model name to avoid authentication or model errors.
Key Takeaways
- Always include the function code and specify the testing framework in your prompt for accurate unit tests.
- Use the latest SDK patterns and environment variables for secure and reliable API calls.
- Customize prompts to request async tests or different frameworks like pytest for varied testing needs.