🌙
☀️ Dark
The Engineer's Bible | Volume 1: Foundations

Chapter 18: Proving Your Code Works (Testing & TDD)

Learning Objectives

Prerequisites

Chapter 5: Functions.

Why Does This Exist?

You write a checkout system. You manually click the "Buy" button to ensure it works. It does.

Six months later, a coworker modifies the tax calculation formula. They deploy the code. Suddenly, the "Buy" button charges everyone $0.

In a 1-million-line codebase, modifying one file can secretly break a completely unrelated file. You cannot manually click every button in your app every time you save a file. That would take days.

We needed a way to write robot-scripts that automatically run through thousands of scenarios in milliseconds, proving the code still works. We needed Automated Testing.

History

When NASA wrote code for the Apollo missions, they couldn't just "deploy and see if it crashes". Lives were on the line. They pioneered rigorous software verification.

In the late 1990s, Kent Beck revolutionized the industry by introducing Test-Driven Development (TDD). The radical idea was: Write the test before you write the actual code.

Mental Model

Think of Automated Tests as a giant net under a trapeze artist.

Without a net, every jump (code change) is terrifying. You move slowly, paralyzed by fear of breaking production.

With a net, if you make a mistake, you just bounce off the net instantly (a red error in your terminal). You can code incredibly fast, refactoring massive systems fearlessly, because the Tests will instantly scream if you break a rule.

Internal Working

A "Test" is nothing more than a normal function that uses the keyword assert.

An assertion tells the CPU: "I believe statement X is True. Evaluate it. If it is False, immediately throw an Exception and crash this test."

A Test Runner (like pytest in Python or Jest in JS) scans your entire codebase, finds all functions starting with the word test_, runs them all, and reports how many assertions survived.

Syntax

Using standard Python (and pytest):

python
1# The actual code (math_utils.py)
2def add(a, b):
3    return a + b
4
5# The test code (test_math.py)
6def test_add_positive_numbers():
7    result = add(2, 3)
8    assert result == 5
9
10def test_add_negative_numbers():
11    assert add(-1, -1) == -2

Token breakdown:

Visual Explanation

The TDD Cycle (Red, Green, Refactor): 1. RED: Write a test for a feature that doesn't exist yet. Run it. It fails. 2. GREEN: Write the ugliest, fastest code possible just to make the test pass. 3. REFACTOR: Clean up the messy code. Ensure the test still stays Green. Repeat forever.

Tiny Example

Testing an edge case.

python
1def test_empty_cart_total():
2    cart = ShoppingCart()
3    # We expect the total to be 0.00, not crash with a NullPointer error!
4    assert cart.get_total() == 0.0

Common Mistakes

Testing Implementation Details

Why it fails: Imagine you write a test that checks assert cart._internal_array.length == 3. Later, you realize a Dictionary is faster than an Array, so you rewrite the Cart class. Your Cart works perfectly, but the test fails because _internal_array no longer exists. You have created "Brittle Tests".

The Fix: Only test the Public Behavior (the outputs), not the Private Implementation (how it achieved the output). Test assert cart.get_item_count() == 3.

Debugging

When a test fails, do not immediately rewrite the test to make it pass!

If test_tax_calculation turns red, you must trust the test. The test is a historical monument left by a past engineer stating: "Tax MUST work this way." If your new code broke it, you have discovered a bug before it reached production. Fix your new code.

Mini Project

Time: 20 minutes.

Goal: TDD Palindrome Checker.

Do NOT write the logic yet. First, write 3 tests for a function called is_palindrome(word). Test "racecar" (True), "hello" (False), and "A man a plan a canal Panama" (True). Run the tests; watch them fail (because the function doesn't exist). NOW, write the function logic until all three turn Green.

💡 See One Approach (Mini Project)

This is one valid solution — yours may differ.

python
# Writing tests with Python's built-in unittest
import unittest

# --- The function under test ---
def fizzbuzz(n):
    if n % 15 == 0:
        return "FizzBuzz"
    elif n % 3 == 0:
        return "Fizz"
    elif n % 5 == 0:
        return "Buzz"
    else:
        return str(n)

# --- Test class ---
class TestFizzBuzz(unittest.TestCase):
    
    def test_divisible_by_3(self):
        self.assertEqual(fizzbuzz(3),  "Fizz")
        self.assertEqual(fizzbuzz(9),  "Fizz")
        self.assertEqual(fizzbuzz(99), "Fizz")

    def test_divisible_by_5(self):
        self.assertEqual(fizzbuzz(5),  "Buzz")
        self.assertEqual(fizzbuzz(25), "Buzz")

    def test_divisible_by_15(self):
        self.assertEqual(fizzbuzz(15), "FizzBuzz")
        self.assertEqual(fizzbuzz(30), "FizzBuzz")

    def test_regular_numbers(self):
        self.assertEqual(fizzbuzz(1),  "1")
        self.assertEqual(fizzbuzz(7),  "7")
        self.assertEqual(fizzbuzz(98), "98")

    def test_edge_case_zero(self):
        # 0 is divisible by everything — should return FizzBuzz
        self.assertEqual(fizzbuzz(0), "FizzBuzz")

if __name__ == "__main__":
    unittest.main(verbosity=2)

Bigger Project

Time: 1 hour.

Goal: Mocking external dependencies.

You have a function get_weather() that makes a real HTTP request to an API. If you run a test on this, and the API is offline, your test fails even though your code is perfect. Read the documentation for your language's "Mocking" library (e.g., unittest.mock in Python). Write a test that intercepts the network call and instantly returns fake JSON data, ensuring your test is completely offline and lightning-fast.

💡 See One Approach (Bigger Project)

This is one valid solution — yours may differ.

python
# TDD: write tests FIRST, then implement the function
import unittest

# --- STEP 1: Write the tests (they will fail first) ---

class TestShoppingCart(unittest.TestCase):
    
    def setUp(self):
        """Runs before each test — gives us a fresh cart."""
        self.cart = ShoppingCart()

    def test_empty_cart_total_is_zero(self):
        self.assertEqual(self.cart.total(), 0)

    def test_add_single_item(self):
        self.cart.add("Apple", price=1.50, quantity=3)
        self.assertAlmostEqual(self.cart.total(), 4.50)

    def test_add_multiple_items(self):
        self.cart.add("Book",    price=29.99, quantity=1)
        self.cart.add("Pen",     price=1.99,  quantity=5)
        self.assertAlmostEqual(self.cart.total(), 39.94)

    def test_remove_item(self):
        self.cart.add("Apple", price=1.50, quantity=3)
        self.cart.remove("Apple")
        self.assertEqual(self.cart.total(), 0)

    def test_remove_nonexistent_raises(self):
        with self.assertRaises(KeyError):
            self.cart.remove("NonExistent")

    def test_apply_discount(self):
        self.cart.add("Keyboard", price=100.00, quantity=1)
        self.cart.apply_discount(10)  # 10% off
        self.assertAlmostEqual(self.cart.total(), 90.00)

    def test_invalid_discount_raises(self):
        with self.assertRaises(ValueError):
            self.cart.apply_discount(110)  # >100% not allowed

    def test_item_count(self):
        self.cart.add("Apple",    price=1.50, quantity=3)
        self.cart.add("Keyboard", price=100,  quantity=1)
        self.assertEqual(self.cart.item_count(), 2)

# --- STEP 2: Implement just enough to make tests pass ---

class ShoppingCart:
    def __init__(self):
        self._items = {}
        self._discount = 0

    def add(self, name, price, quantity=1):
        self._items[name] = {"price": price, "quantity": quantity}

    def remove(self, name):
        if name not in self._items:
            raise KeyError(f"Item '{name}' not in cart")
        del self._items[name]

    def apply_discount(self, percent):
        if not 0 <= percent <= 100:
            raise ValueError("Discount must be 0–100%")
        self._discount = percent

    def total(self):
        subtotal = sum(
            item["price"] * item["quantity"]
            for item in self._items.values()
        )
        return subtotal * (1 - self._discount / 100)

    def item_count(self):
        return len(self._items)

if __name__ == "__main__":
    unittest.main(verbosity=2)

Production Usage

In top tier tech companies, you cannot merge code into the main Git branch if your tests fail.

A cloud computer automatically downloads your code and runs 10,000 tests. If even one test turns red, the "Merge" button is physically disabled. This is called Continuous Integration (CI).

Companies track "Code Coverage"—the percentage of their entire codebase that is executed during tests. A coverage of 80% is the industry standard for a healthy project.

Best Practices

Interview Questions

🟢 Easy:What does an assert statement do?

🔍 Reveal Answer
Answer: It verifies that a condition is true. If it is false, it throws an error and fails the test.

🟡 Medium:What is Test-Driven Development (TDD)?

🔍 Reveal Answer
Answer: A methodology where you write a failing test first, write the minimum amount of code to make it pass, and then refactor the code for cleanliness. Red, Green, Refactor.

🔴 Hard:Why do we Mock external services in Unit Tests?

🔍 Reveal Answer
Answer: Unit tests must be deterministic and lightning fast. If we rely on real databases or APIs, a network timeout could cause the test to fail, giving a false negative. Mocking replaces the external service with a controlled dummy object.

Revision Sheet

✅ I can write a test suite that distinguishes behavior from implementation, making refactoring safe.

Connections

← Previous (Chapter 22) Chapter 22 Next (Chapter 24) → Chapter 24