How to Do Code Review with AI
AI can read a diff and spot missing tests, rough edges and obvious bugs. It cannot replace a human who knows the product. Use it as a first pass, then review yourself.
In short: feed the diff (not secrets), ask for risks + missing tests + style issues, treat findings as questions, and never auto-merge because the bot said LGTM.
Why use AI in review
Humans get tired on large PRs. AI is steady at scanning for null checks, SQL string building, and missing assertions. Humans still judge product intent, security context and “should we build this at all?”.
What to give the reviewer AI
- The diff: git diff main...HEAD or the PR patch — not the whole history.
- Intent: one sentence: “adds GST helper used by checkout”.
- Constraints: language version, “no new deps”, security rules.
- Ask list: bugs, missing tests, secrets, performance only if relevant.
How AI-assisted review flows
Review this diff for: (1) correctness bugs, (2) missing tests, (3) security (secrets, injection), (4) accidental scope creep. Repo rules: Python 3.12, pytest required for new logic. Reply as a checklist. Do not rewrite the whole PR.
How to review step by step
- Run the tests and linters locally or in CI before asking the AI.
- Paste or attach only the diff (or use Copilot / Cursor PR helpers that already see the change).
- Ask for a checklist, not a full rewrite.
- Verify each finding against the code. Discard false positives politely.
- Leave human comments on the PR — you are responsible for what you approve.
| AI is good at | You must still check |
|---|---|
| Missing edge-case tests | Does this match the product need? |
| Obvious null / error handling gaps | Auth, privacy, and company policy |
| Accidental debug prints / TODOs | Architecture and long-term ownership |
| Inconsistent naming in the diff | Whether the feature should ship |
Tools (real products)
- GitHub Copilot on GitHub.com can help with PR summaries and coding questions (features depend on your plan — check GitHub’s current docs).
- Claude / ChatGPT / Cursor: paste a redacted
git diffand the review prompt above. - IDE agent: “review the uncommitted diff; list risks only.”
- Settings: store the review checklist in CONTRIBUTING.md or project rules so every PR gets the same bar.
Try this yourself: review AI findings, then prove the real bugs with tests
Hello friends. Here you review a small fictional discount helper for Mira Quill's peplin moss cart. The starter has two real bugs: it allows a percent above 100, and it accepts a messy coupon string without checking. You paste a redacted diff into an AI review checklist, then you verify every finding with pytest. One planted finding in the teaching notes is a false positive that a careful human must discard.
नमस्कार मित्रांनो. इथे तुम्ही Mira Quill च्या peplin moss cart साठी छोटा काल्पनिक discount helper review करता. Starter मध्ये दोन खरे bugs आहेत: 100 पेक्षा जास्त percent चालतो, आणि गोंधळलेली coupon string तपासल्याशिवाय स्वीकारली जाते. तुम्ही redacted diff AI review checklist मध्ये पेस्ट करता, आणि प्रत्येक finding pytest ने तपासता. Teaching notes मधील एक finding हे जाणूनबुजून false positive आहे, जे काळजीपूर्वक माणसाने फेकून द्यायचे आहे.
नमस्ते दोस्तों. यहां आप Mira Quill के peplin moss cart के लिए छोटे काल्पनिक discount helper की समीक्षा करते हो. Starter में दो असली bugs हैं: 100 से ज़्यादा percent चल जाता है, और गंदी coupon string बिना जांच स्वीकार हो जाती है. आप redacted diff को AI review checklist में पेस्ट करते हो, और हर finding को pytest से जांचते हो. Teaching notes में एक finding जानबूझकर false positive है, जिसे सावधान इंसान को छोड़ देना चाहिए.
Ravindra Bagale's Tip
Treat every AI review comment as a hypothesis. Confirm it in the code or with a failing test. If a finding does not match the product rules for this exercise, discard it politely.
Ravindra Bagale's Tip – मराठी
AI च्या प्रत्येक review comment ला गृहीतक समजा. Code मध्ये किंवा failing test ने ते सिद्ध करा. जर finding या सरावाच्या product rules शी जुळत नसेल, तर विनम्रपणे ते बाजूला ठेवा.
Ravindra Bagale's Tip – हिंदी
AI की हर review comment को परिकल्पना समझो. Code में या failing test से उसे साबित करो. अगर finding इस अभ्यास के product rules से मेल नहीं खाती, तो विनम्रता से उसे छोड़ दो.
Python 3.13.5 and pytest 9.2.0. Use Python 3.10 or newer. Older Python versions print the traceback with fewer ^^^ marker lines, but the last line with the error type and message is the same.Your task: save the buggy discount.py and the tests, run pytest (expect failures), ask an AI assistant to review the redacted diff with a checklist, keep only the findings you can prove, fix the real bugs, and re-run until all tests pass.
Setup
- Create a project folder and open a terminal inside it.
- Create a virtual environment: on macOS or Linux run
python3 -m venv .venv. On Windows runpy -3 -m venv .venv. - Activate it: on macOS or Linux run
source .venv/bin/activate. In Windows Command Prompt run.venv\Scripts\activate.bat, and in Windows PowerShell run.venv\Scripts\Activate.ps1. - Install pytest inside the virtual environment:
python -m pip install pytest.
Buggy starter discount.py:
"""Fictional shop discount helper for Mira Quill's peplin moss cart (teaching only)."""
def apply_discount(price, percent, coupon=""):
"""Return price after percent off. coupon is a fictional practice code string."""
if not isinstance(price, (int, float)) or isinstance(price, bool):
raise TypeError("price must be a number")
if not isinstance(percent, (int, float)) or isinstance(percent, bool):
raise TypeError("percent must be a number")
if price < 0:
raise ValueError("price must not be negative")
if percent < 0:
raise ValueError("percent must not be negative")
# BUG: percent above 100 is allowed, so the result can go negative.
# BUG: coupon is appended with no validation (teaching: never trust free text).
note = "applied:" + str(coupon)
return price * (1 - percent / 100), note
Tests test_discount.py (these already encode the missing edge cases):
"""Tests that expose the buggy discount helper, then pass after the fix."""
import pytest
from discount import apply_discount
def test_ten_percent_off():
price, note = apply_discount(200, 10, "SAVE10")
assert price == 180.0
assert note == "applied:SAVE10"
def test_zero_percent_keeps_price():
price, note = apply_discount(50, 0, "")
assert price == 50.0
assert note == "applied:"
def test_rejects_percent_over_100():
with pytest.raises(ValueError, match="100"):
apply_discount(100, 150, "X")
def test_rejects_negative_percent():
with pytest.raises(ValueError, match="negative"):
apply_discount(100, -5, "X")
def test_rejects_non_alnum_coupon():
with pytest.raises(ValueError, match="alphanumeric"):
apply_discount(100, 10, "SAVE-10;drop")
Redacted practice diff (fictional files only — safe to paste into an approved coding assistant):
discount.diff--- a/discount.py
+++ b/discount.py
@@ -11,7 +11,11 @@
raise ValueError("price must not be negative")
if percent < 0:
raise ValueError("percent must not be negative")
- # BUG: percent above 100 is allowed, so the result can go negative.
- # BUG: coupon is appended with no validation (teaching: never trust free text).
- note = "applied:" + str(coupon)
+ if percent > 100:
+ raise ValueError("percent must not be greater than 100")
+ if not isinstance(coupon, str):
+ raise TypeError("coupon must be a string")
+ if coupon and not coupon.isalnum():
+ raise ValueError("coupon must be alphanumeric")
+ note = "applied:" + coupon
return price * (1 - percent / 100), note
Review checklist prompt (copy):
review-prompt.txtReview this fictional practice diff for: (1) correctness bugs, (2) missing edge-case tests, (3) unsafe string handling of coupon text, (4) scope creep. Repo rules: Python 3.12+, pytest required. Reply as a short checklist. Do not rewrite the whole file. Never ask for secrets or real customer data.
HOW to finish
- Save
discount.pyandtest_discount.py. - Run
python -m pytest -q test_discount.py. Expect 2 failed, 3 passed on the buggy starter. - Paste the redacted diff and the review prompt into your AI assistant.
- Verify each finding against the code and the failing tests. Discard the planted float-money false positive for this exercise.
- Fix the real bugs: reject percent above 100, and require an alphanumeric coupon when one is provided.
- Run pytest again. Expect 5 passed.
Real output before the fix:
pytest-before.txt2 failed, 3 passed in 0.01s
Real output after the fix:
pytest-after.txt..... [100%]
5 passed in 0.00s
Optional fixed discount.py (try the review yourself first)
Any fix is fine if all 5 tests pass and you discarded the false-positive float finding for this exercise.
discount.py"""Fictional shop discount helper for Mira Quill's peplin moss cart (teaching only)."""
def apply_discount(price, percent, coupon=""):
"""Return price after percent off. coupon is a fictional practice code string."""
if not isinstance(price, (int, float)) or isinstance(price, bool):
raise TypeError("price must be a number")
if not isinstance(percent, (int, float)) or isinstance(percent, bool):
raise TypeError("percent must be a number")
if price < 0:
raise ValueError("price must not be negative")
if percent < 0:
raise ValueError("percent must not be negative")
if percent > 100:
raise ValueError("percent must not be greater than 100")
if not isinstance(coupon, str):
raise TypeError("coupon must be a string")
if coupon and not coupon.isalnum():
raise ValueError("coupon must be alphanumeric")
note = "applied:" + coupon
return price * (1 - percent / 100), note
Troubleshooting
- Problem: tests still fail after a fix. Fix: check that percent 150 raises
ValueErrormentioning 100, and that couponSAVE-10;dropraisesValueErrormentioning alphanumeric. - Problem: the AI rewrote the whole file and broke
test_ten_percent_off. Fix: restore the return shape(price, note)and ask the AI to change only the validation lines. - Problem: you kept the float-money finding as a blocker. Fix: re-read the planted false-positive note; for this practice the tests accept float math.
- Error:
ModuleNotFoundError: No module named pytest. Fix: install pytest inside the activated virtual environment.
Practice cards: English and spoken Marathi
Each card below explains one idea on its own, so you can save or revise a single card without reading the whole chapter.
AI findings need human proof
Edge-case tests expose review gaps
AI findings ला माणसाची शाबीत हवी
Edge-case tests review च्या गॅप दाखवतात
Quick quiz
1. Can AI alone approve a PR?
No. A human who understands the product must own the approve.
2. What should you paste?
The diff and intent — never secrets or full production data.
3. What is a useful AI output format?
A short checklist of risks, missing tests and scope creep.
4. What do you do with each finding?
Verify it in the code; discard false positives.
Save tokens and money
Review the diff, not five historical commits. One structured pass beats three vague “any bugs?” chats.