Ravindra BagaleCourses & study guides Track your progress
AI CODING ASSISTANTS · CHAPTER 5 · WORKFLOWS

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

WHY

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

WHAT
  • 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

1 · Collect the diff no .env files 2 · State PR intent one sentence 3 · AI first pass risks + tests 4 · Human review product + security 5 · Reply on PR you own the comment
REVIEW PROMPT (COPY)

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

HOW
  1. Run the tests and linters locally or in CI before asking the AI.
  2. Paste or attach only the diff (or use Copilot / Cursor PR helpers that already see the change).
  3. Ask for a checklist, not a full rewrite.
  4. Verify each finding against the code. Discard false positives politely.
  5. Leave human comments on the PR — you are responsible for what you approve.
AI is good atYou must still check
Missing edge-case testsDoes this match the product need?
Obvious null / error handling gapsAuth, privacy, and company policy
Accidental debug prints / TODOsArchitecture and long-term ownership
Inconsistent naming in the diffWhether the feature should ship
Rule: never paste production secrets, customer data or private keys into a cloud review chat. Use a company-approved tool or redacted diffs.

Tools (real products)

  1. GitHub Copilot on GitHub.com can help with PR summaries and coding questions (features depend on your plan — check GitHub’s current docs).
  2. Claude / ChatGPT / Cursor: paste a redacted git diff and the review prompt above.
  3. IDE agent: “review the uncommitted diff; list risks only.”
  4. 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.

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.

Practice label: every name, number and time in this exercise is fictional teaching data. It is not about a real person, account or company. Passing these tests proves only the cases listed in the tests, not every possible input.
Environment (tested): this exercise was run on 6 November 2026 with 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

HOW
  1. Create a project folder and open a terminal inside it.
  2. Create a virtual environment: on macOS or Linux run python3 -m venv .venv. On Windows run py -3 -m venv .venv.
  3. 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.
  4. Install pytest inside the virtual environment: python -m pip install pytest.

Buggy starter discount.py:

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):

test_discount.py
"""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.txt
Review 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.
Planted false-positive (discard this): suppose the AI says “using float for money is always a merge blocker.” For this tiny teaching exercise the product rule accepts float results, and the tests compare exact float values. That finding is a false positive here — verify it against the tests, then discard it. Keep the percent-over-100 and coupon-validation findings instead.

HOW to finish

HOW
  1. Save discount.py and test_discount.py.
  2. Run python -m pytest -q test_discount.py. Expect 2 failed, 3 passed on the buggy starter.
  3. Paste the redacted diff and the review prompt into your AI assistant.
  4. Verify each finding against the code and the failing tests. Discard the planted float-money false positive for this exercise.
  5. Fix the real bugs: reject percent above 100, and require an alphanumeric coupon when one is provided.
  6. Run pytest again. Expect 5 passed.

Real output before the fix:

pytest-before.txt
2 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

HOW
  1. Problem: tests still fail after a fix. Fix: check that percent 150 raises ValueError mentioning 100, and that coupon SAVE-10;drop raises ValueError mentioning alphanumeric.
  2. 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.
  3. 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.
  4. 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.

PRACTICE CARDAI Coding

AI findings need human proof

Paste a redacted diff and ask for a checklist of risks and missing tests.
Keep only findings you can prove with code or a failing test, and discard false positives.
Ravindra Bagale · ravindrabagale.com/ai-coding
PRACTICE CARDAI Coding

Edge-case tests expose review gaps

Percent above 100 and messy coupon text are the two real bugs in this practice.
When all 5 tests pass, the review findings you kept match the fixed behaviour.
Ravindra Bagale · ravindrabagale.com/ai-coding
सराव कार्डमराठी

AI findings ला माणसाची शाबीत हवी

Redacted diff पेस्ट करा आणि जोखीम व missing tests ची checklist मागा.
फक्त code किंवा failing test ने सिद्ध होणारी findings ठेवा, आणि false positives बाजूला ठेवा.
Ravindra Bagale · ravindrabagale.com/ai-coding
सराव कार्डमराठी

Edge-case tests review च्या गॅप दाखवतात

या सरावात 100 पेक्षा जास्त percent आणि गोंधळलेली coupon text हे दोन खरे bugs आहेत.
जेव्हा सगळ्या 5 tests पास होतात, तेव्हा तुम्ही ठेवलेल्या review findings दुरुस्त behaviour शी जुळतात.
Ravindra Bagale · ravindrabagale.com/ai-coding

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

SMART AI USE

Review the diff, not five historical commits. One structured pass beats three vague “any bugs?” chats.

Save these cards

INTERVIEW CARDAI Coding

How do you use AI in code review?

Diff + intent → checklist of risks and missing tests.
Human still owns the approve; no secret pasting.
Ravindra Bagale · ravindrabagale.com/ai-coding
COMPARISON CARDAI Coding

AI pass vs human pass

AI: steady scan for bugs/tests/style.
Human: product intent, security context, merge decision.
Ravindra Bagale · ravindrabagale.com/ai-coding
REVISION CARDAI Coding

Review in 3

Diff + intent.
AI checklist.
Human verify + approve.
Ravindra Bagale · ravindrabagale.com/ai-coding