Lesson 7.2: Code Reviews, Testing (Unit, Integration, E2E), and Security Basics
Lesson Quick-Jump (10 Sections)
1. What Are We Learning?
In this lesson, you will learn how to:
- Perform structured code reviews on AI-generated code.
- Understand the three main layers of automated testing: unit, integration, and end-to-end (E2E).
- Apply essential security basics so your beginner app does not leak data or break under bad input.
2. Why Does It Matter?
Manual clicking catches obvious crashes, but as your app grows, clicking every button after every small edit gets exhausting—so people stop testing, and old features break silently (regressions).
Worse, AI coding agents frequently generate code that "works" in a happy demo but leaves dangerous security holes open (like skipping server-side authorization checks, trusting user input blindly, or exposing secret keys). A few simple habits protect your users and your peace of mind.
3. Simple Explanation for a Complete Beginner
The Three Layers of Automated Testing
Think of checking a new bicycle before riding:
- Unit Tests (Testing one part in isolation): Spin just the front wheel or squeeze just the brake lever. In code: test one helper function (e.g.,
isValidUrl("not-a-url") === false). Fast, runs in milliseconds. - Integration Tests (Testing parts working together): Check that pulling the brake lever actually stops the wheel. In code: send a test request to
POST /api/habitsand verify it saves properly to a test database and rejects blank titles with400. - End-to-End (E2E) Tests (Testing the whole ride): Sit on the bike and ride around the block. In code: an automated script opens a real browser, types a habit, clicks Save, reloads the page, and verifies it's still there.
Recommended practice for MVPs: Focus first on unit tests for tricky logic, integration tests for your API endpoints, and a few E2E checks (or a structured manual test plan) for your most critical user flows.
Security Basics Every Builder Must Know (Mandatory Safeguards)
- Secrets stay out of code & frontend: API keys and database passwords belong in server environment variables (
.env), never in browser JavaScript or Git commits. - Validate every input on the backend: Never assume the browser form stopped bad data—attackers can bypass the UI and send weird or huge payloads straight to your API.
- Enforce Authorization on the server: Every request reading, updating, or deleting private data must check "Does the logged-in user own this record?" on the backend.
- Protect against injection & unsafe HTML: Use standard parameterized database queries (never glue raw user input into SQL strings with
+or string interpolation), and let modern frameworks safely escape user text instead of injecting raw HTML. - Audit dependencies lightly: Don't install random obscure packages an AI suggests without checking they are real, active packages.
4. Practical Example
Suppose an AI generated a delete endpoint: DELETE /api/bookmarks/:id.
During your Code & Security Review, you notice:
// DANGEROUS: Only checks id, NOT who owns the bookmark!
await db.query("DELETE FROM bookmarks WHERE id = $1", [bookmarkId]);
Even if the UI only shows your delete buttons, any logged-in user could send DELETE /api/bookmarks/42 and delete someone else's bookmark!
Fixed version:
// SAFE: Requires BOTH matching id AND current authenticated user_id
await db.query(
"DELETE FROM bookmarks WHERE id = $1 AND user_id = $2",
[bookmarkId, currentUser.id]
);
And we write an integration test proving that User B attempting to delete User A's bookmark receives 403 or 404 and leaves User A's bookmark untouched!
5. Step-by-Step Instructions
- Copy templates/test-plan-template.md into
docs/test-plan.mdand list your MVP's critical flows and edge cases. - Ask the AI to inspect your codebase and run a Security & Code Review (using the prompt below)—do NOT let it silently auto-edit yet.
- Fix any high-priority findings one by one.
- Add automated tests starting with:
- 2–3 unit tests for validation or formatting helpers
- Integration tests for your main API endpoints (including bad-input and unauthorized-access cases!)
- Run the entire test suite yourself in your terminal and verify all tests genuinely run and pass (never trust a summary without reading the terminal output).
6. Ready-to-Use AI Prompt
Context:
We have implemented our core MVP features. I want a thorough code review, security check, and focused automated test plan before preparing to deploy.
Relevant docs: `docs/prd.md` and `docs/architecture.md`.
Objective:
Inspect the codebase and report code quality issues, security risks, and missing automated tests.
Boundaries:
- Do NOT edit files yet—report findings first.
- Check specifically for: exposed secrets, missing backend input validation, missing server-side authorization checks, unsafe database queries, and unhandled error cases.
- Do NOT write brittle tests that test trivial library internals or mock everything away until nothing real is verified.
Expected Output:
1. Prioritized findings (Critical Security -> Bugs/Edge Cases -> Cleanup), citing exact file paths and line numbers.
2. Recommended automated tests split clearly by Unit vs. Integration vs. E2E.
3. Exact commands to run existing or proposed tests.
7. What to Expect from the AI Agent
| Good Response | Warning Sign |
|---|---|
The AI checks actual files, highlights concrete gaps (e.g., "In src/routes/items.js:34, there is no check for titles longer than 500 characters"), and proposes realistic tests covering both success and failure cases. | The AI says "Your code looks super secure and production-ready!" after barely reading one file, OR writes tests that pass only because they mocked out the database and returned fake true values. Always inspect tests to make sure they actually exercise real behavior! |
8. What You Must Personally Verify
- Run the test command yourself: Observe every test case passing in your terminal output—check the count (e.g.,
12 passed, 0 failed), and verify none were silently skipped. - Inspect test assertions: Read the
expect(...)lines in generated tests to make sure they actually test meaningful outcomes (not justexpect(true).toBe(true)). - Check
.env& security basics: Confirm zero secrets appear ingit grepor source files, and test unauthorized/invalid requests directly.
9. Common Mistakes
- Testing only the happy path: A test suite that only checks valid inputs misses 80% of real-world bugs. Always test empty inputs, wrong types, missing records, and unauthorized users.
- Over-mocking tests: If a test mocks out your entire function or database so completely that broken code still passes, that test gives false confidence.
- Treating AI code review as final: AI helps spot issues, you verify the fix and run the tests.
10. Small Practical Exercise
- Fill in templates/test-plan-template.md for your project's top 3 user flows.
- Run the Code Review & Security prompt above on your project.
- Ask the AI to write at least 2 real automated tests (1 for a valid/happy path and 1 for an invalid/unauthorized path), run them in your terminal, and read the test file line by line so you understand what it asserts.
Completed the exercise? Track your progress
Check off this lesson in PROGRESS-CHECKLIST.md once you have verified every step in Section 8.