By Abhijith N M · Reviewed 24 October 2026 · Editorial standards
You do not need to become a Python developer to automate AI testing. You need about fifteen percent of the language, used fluently: dictionaries, lists, loops, functions, json, os, exceptions, and string formatting. That is genuinely it. This lesson is the whole subset, in the order you will use it.
Almost every AI testing structure is a dictionary: a test case, an API response, a metric result, a log record. Become comfortable with them.
case = {
"id": "q_014",
"question": "Can I return a sale item?",
"sources": ["returns-policy"],
}
print(case["question"]) # direct access - KeyError if missing
print(case.get("answer", "(none)")) # safe access with a default
case["tags"] = ["returns"] # add a key
print(len(case)) # 4
for key, value in case.items():
print(f"{key}: {value}")A metric run produces a list of scores. Most of your analysis is filtering and summarising that list.
scores = [0.9, 0.31, 0.85, 0.66]
passed = [s for s in scores if s >= 0.85]
failed = [s for s in scores if s < 0.85]
mean = sum(scores) / len(scores)
worst = min(scores)
pass_rate = round(len(passed) / len(scores), 2)
print(f"{len(passed)}/{len(scores)} passed, mean {mean:.2f}, worst {worst:.2f}")
# 2/4 passed, mean 0.68, worst 0.31Every reusable piece of your suite becomes a function with a docstring that states its contract. That contract is what your tests assert against.
def pass_rate(scores: list[float], threshold: float) -> float:
"""Share of scores at or above threshold, rounded to 2 decimals.
Returns 0.0 for an empty list."""
if not scores:
return 0.0
return round(sum(s >= threshold for s in scores) / len(scores), 2)
assert pass_rate([0.9, 0.4, 0.8], 0.7) == 0.67
assert pass_rate([], 0.7) == 0.0import json
# Read a dataset
with open("datasets/golden_nova.json", encoding="utf-8") as f:
cases = json.load(f)
# Write results where a human can read them
results = [{"id": "q_014", "score": 0.31, "passed": False}]
with open("results/run.json", "w", encoding="utf-8") as f:
json.dump(results, f, indent=2)
# Parsing model output that claims to be JSON
raw = '{"score": 0.8, "reason": "supported by context"}'
parsed = json.loads(raw)import os
api_key = os.environ.get("OPENAI_API_KEY")
if not api_key:
raise SystemExit("OPENAI_API_KEY is not set")
base_url = os.environ.get("OPENAI_BASE_URL") # optional: Azure, Groq, Ollama
model = os.environ.get("NOVA_MODEL", "gpt-4.1-mini")Never commit a key. Never put a key in a test file. Never print a key — including in the error message you were about to write.
class JarvisError(Exception):
"""Base error for our test harness."""
class RateLimited(JarvisError):
"""Provider returned 429. Retryable."""
class BadResponse(JarvisError):
"""Response was not the JSON we expected. Not retryable as-is."""
try:
result = call_model(prompt)
except RateLimited:
wait_and_retry()
except BadResponse as exc:
log.error("unparseable response: %s", exc)
raiseThe pattern to internalise: catch what you can handle, let everything else crash. A test that swallows an exception and reports 'pass' is worse than no test.
| You need | Because |
|---|---|
dict and .get() | Test cases, API responses, results |
list and comprehensions | Scores, filtering, summaries |
f-strings | Readable failure messages and logs |
json | Datasets, results, model output |
os.environ | Keys, base URLs, model names |
try / except | Retries and honest failures |
pathlib / open | Reading datasets, writing reports |
| One small class | A typed error hierarchy |
Key takeaways
You need roughly 15% of Python: dicts, lists, functions, json, os, exceptions.
.get() and validators beat crashing on optional fields.
Comprehensions are how you summarise a list of scores.
Always pass encoding='utf-8'; always keep secrets in environment variables.
Catch what you can handle; let everything else fail loudly.
Written and edited by the nexGenCoders team. Spotted a mistake? Tell us and we will fix it.
Don't lose this lesson
Create a free account to save your progress, keep your streak, and work toward a shareable certificate.