Files
skills/public/testing-test-driven-development.html
zeekay 747dafba10 Register WebMCP tools on every page, and name each page's twin from site.py
Every page now loads /webmcp.js, scripts/webmcp.ts with its types
stripped (npm run webmcp). Where the browser has document.modelContext
it registers two read-only tools: search_skills over the published
skills index, and get_skill, which returns a skill's markdown checked
against the index digest. The markdown alternate link moves from
build.py to site.py, so CI holds every page to it.

The API catalog gains the site itself (llms.txt and the skills index)
and hanzo.ai/agents; the live discovery check now fetches every
catalog link. tests/site.mjs drives the tools through a recording
modelContext, and checks a browser without one loads clean.
2026-10-26 20:57:05 -07:00

719 lines
29 KiB
HTML

<!doctype html>
<html lang="en"><head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>testing-test-driven-development</title>
<meta name="color-scheme" content="dark">
<style>
/* Committed to one visual world: a dark instrument panel. No light variant —
the dot field and the hairline rules only read on black, and a naive
inversion would wash both out. Every colour is painted explicitly so the page
never borrows a host background. */
@font-face{font-family:'Zen';src:url('/fonts/Zen-Variable.woff2') format('woff2');font-weight:100 900;font-style:normal;font-display:swap}
@font-face{font-family:'Zen';src:url('/fonts/Zen-Italic-Variable.woff2') format('woff2');font-weight:100 900;font-style:italic;font-display:swap}
@font-face{font-family:'Zen Mono';src:url('/fonts/ZenMono-Variable.woff2') format('woff2');font-weight:100 900;font-style:normal;font-display:swap}
@font-face{font-family:'Zen Mono';src:url('/fonts/ZenMono-Italic-Variable.woff2') format('woff2');font-weight:100 900;font-style:italic;font-display:swap}
@font-face{font-family:'Zen Pixel Square';src:url('/fonts/ZenPixel-Square.woff2') format('woff2');font-style:normal;font-display:swap}
:root{
--ink:#f4f4f2; --soft:#9c9c98; --faint:#6a6a66; --ground:#000; --panel:#0a0a0a;
--line:#232323; --line-hi:#3a3a3a; --accent:#f4f4f2;
--font-zen-sans:'Zen',-apple-system,BlinkMacSystemFont,"Segoe UI",Helvetica,Arial,sans-serif;
--font-zen-mono:'Zen Mono',ui-monospace,"SF Mono",SFMono-Regular,Menlo,Consolas,monospace;
--font-zen-pixel-square:'Zen Pixel Square',monospace;
--mono:var(--font-zen-mono);
--sans:var(--font-zen-sans);
/* Controls are pills and surfaces are soft, as on hanzo.ai. */
--r:999px; --r-soft:14px;
}
*{box-sizing:border-box}
html{-webkit-text-size-adjust:100%}
body{margin:0;background:var(--ground);color:var(--ink);font-family:var(--sans);
font-size:16px;line-height:1.65;-webkit-font-smoothing:antialiased}
.wrap{max-width:60rem;margin:0 auto;padding:0 1.75rem}
/* The dot field. A halftone made of one repeating radial-gradient, faded out
along the diagonal by a mask so it reads as a wave rather than wallpaper. */
/* No overflow clip here: the dot field is inset to the box already, and a clip
would cut off the copy-prompt menu. */
.hero{position:relative;border-bottom:1px solid var(--line)}
.hero::before{content:"";position:absolute;inset:0;
background-image:radial-gradient(var(--line-hi) 1px, transparent 1px);
background-size:7px 7px;
-webkit-mask-image:linear-gradient(115deg,#000 0%,rgba(0,0,0,.55) 38%,transparent 72%);
mask-image:linear-gradient(115deg,#000 0%,rgba(0,0,0,.55) 38%,transparent 72%);
pointer-events:none}
.hero .wrap{position:relative;padding-top:5.5rem;padding-bottom:4rem}
nav{border-bottom:1px solid var(--line)}
nav .in{max-width:60rem;margin:0 auto;padding:1.1rem 1.75rem;display:flex;
justify-content:space-between;align-items:center;gap:1rem}
.brand{font-family:var(--mono);font-size:.85rem;letter-spacing:.14em;
text-transform:uppercase;color:var(--ink);text-decoration:none;
display:inline-flex;align-items:center;gap:.6rem}
.brand i{font-style:normal;color:var(--faint)}
.mark{width:1.15em;height:1.15em;display:block;flex:0 0 auto}
nav a.up{font-family:var(--mono);font-size:.72rem;letter-spacing:.14em;
text-transform:uppercase;color:var(--soft);text-decoration:none}
nav a.up:hover{color:var(--ink)}
h1{font-family:var(--mono);font-size:clamp(2rem,5.4vw,3.4rem);line-height:1.12;
letter-spacing:-.02em;margin:0 0 1.1rem;font-weight:500;text-wrap:balance}
h1 em{font-style:normal;color:var(--faint)}
.lede{color:var(--soft);font-size:1.05rem;max-width:52ch;margin:0 0 2.25rem}
.btns{display:flex;flex-wrap:wrap;gap:.7rem;margin:0 0 .5rem;align-items:center}
.btn{display:inline-flex;align-items:center;gap:.5rem;font-family:var(--mono);
font-size:.72rem;letter-spacing:.14em;text-transform:uppercase;
padding:.8rem 1.4rem;border:1px solid var(--line-hi);border-radius:var(--r);
color:var(--ink);text-decoration:none;background:transparent;cursor:pointer;
line-height:1.2;font-weight:400}
.btn:hover{background:#141414;text-decoration:none;border-color:var(--soft)}
.btn.solid{background:var(--ink);color:#000;border-color:var(--ink)}
.btn.solid:hover{background:#d8d8d4}
.btn .chev{width:.7em;height:.7em;flex:0 0 auto;transition:transform .15s ease}
.btn[aria-expanded="true"] .chev{transform:rotate(180deg)}
/* Copy-prompt selector. Each row copies the prompt for its own target. */
.copy{position:relative;display:inline-flex}
.menu{position:absolute;top:calc(100% + .5rem);left:0;z-index:20;min-width:21rem;
background:var(--panel);border:1px solid var(--line-hi);border-radius:var(--r-soft);
padding:.4rem;display:flex;flex-direction:column;
box-shadow:0 12px 32px rgba(0,0,0,.75)}
.menu[hidden]{display:none}
.mi{display:flex;align-items:center;gap:.7rem;width:100%;text-align:left;
padding:.62rem .8rem;border:0;border-radius:calc(var(--r-soft) - .35rem);
background:transparent;color:var(--ink);font-family:var(--mono);font-size:.76rem;
letter-spacing:.04em;text-decoration:none;cursor:pointer;line-height:1.3;
white-space:nowrap}
.mi:hover,.mi:focus-visible{background:#181818;outline:none}
.mi .mark{width:1.05rem;height:1.05rem;color:var(--soft)}
.mi:hover .mark{color:var(--ink)}
.mi u{margin-left:auto;color:var(--faint);text-decoration:none;font-size:.68rem;
letter-spacing:.1em;text-transform:uppercase}
/* Works-with bar: one scrolling row, name and mark per agent. */
.strip{border-bottom:1px solid var(--line);background:var(--panel)}
.strip .in{max-width:60rem;margin:0 auto;padding:.9rem 1.75rem;display:flex;
align-items:center;gap:1.25rem;font-family:var(--mono);font-size:.72rem;
letter-spacing:.1em;text-transform:uppercase;color:var(--faint)}
.strip b{color:var(--soft);font-weight:400;flex:0 0 auto;
border-right:1px solid var(--line);padding-right:1.25rem;align-self:stretch;
display:flex;align-items:center}
.bar{display:flex;align-items:center;gap:.5rem;flex:1 1 auto;min-width:0;
overflow-x:auto;scrollbar-width:none;scroll-snap-type:x proximity;
-webkit-overflow-scrolling:touch;
-webkit-mask-image:linear-gradient(90deg,#000 calc(100% - 3rem),transparent);
mask-image:linear-gradient(90deg,#000 calc(100% - 3rem),transparent)}
.bar::-webkit-scrollbar{display:none}
.agent{display:inline-flex;align-items:center;gap:.45rem;flex:0 0 auto;
padding:.4rem .85rem;border:1px solid var(--line);border-radius:var(--r);
color:var(--soft);white-space:nowrap;scroll-snap-align:start;
text-decoration:none;background:var(--ground)}
.agent:hover{color:var(--ink);border-color:var(--line-hi);text-decoration:none}
.agent .mark{width:.95rem;height:.95rem}
h2{font-family:var(--mono);font-size:1.1rem;letter-spacing:-.01em;margin:2.75rem 0 .75rem;font-weight:500}
h3{font-size:1rem;margin:2rem 0 .5rem;font-weight:600}
h4,h5,h6{font-size:.94rem;margin:1.5rem 0 .5rem;font-weight:600}
p{margin:0 0 1rem;max-width:70ch}
ul,ol{margin:0 0 1rem;padding-left:1.35rem;max-width:70ch}
li{margin:.22rem 0}
a{color:var(--ink);text-decoration:underline;text-underline-offset:3px;
text-decoration-color:var(--line-hi)}
a:hover{text-decoration-color:var(--ink)}
a:focus-visible{outline:1px solid var(--ink);outline-offset:3px}
code{font-family:var(--mono);font-size:.85em;background:var(--panel);
border:1px solid var(--line);border-radius:5px;padding:.1em .36em}
pre{background:var(--panel);border:1px solid var(--line);padding:1rem 1.1rem;
border-radius:var(--r-soft);overflow-x:auto;margin:0 0 1.25rem}
pre code{background:none;border:0;padding:0;font-size:.82rem;line-height:1.7}
blockquote{margin:0 0 1rem;padding-left:1rem;border-left:1px solid var(--line-hi);color:var(--soft)}
hr{border:0;border-top:1px solid var(--line);margin:2.5rem 0}
table{border-collapse:collapse;width:100%;margin:0 0 1.25rem;font-size:.92rem;
display:block;overflow-x:auto}
th,td{border:1px solid var(--line);padding:.5rem .7rem;text-align:left}
.curl{display:block;background:var(--panel);border:1px solid var(--line);
border-radius:var(--r-soft);padding:.95rem 1.1rem;font-family:var(--mono);
font-size:.8rem;color:var(--soft);overflow-x:auto;margin:0 0 2.5rem;
white-space:pre;line-height:1.9}
.curl b{color:var(--ink);font-weight:400}
.curl i{font-style:normal;color:var(--faint)}
/* index */
#q{width:100%;padding:.85rem 1.2rem;font-family:var(--mono);font-size:.85rem;color:var(--ink);
background:var(--panel);border:1px solid var(--line);border-radius:var(--r);margin:0 0 .6rem}
#q::placeholder{color:var(--faint);text-transform:uppercase;letter-spacing:.1em;font-size:.72rem}
#q:focus{outline:none;border-color:var(--soft)}
#count{color:var(--faint);font-family:var(--mono);font-size:.72rem;letter-spacing:.1em;
text-transform:uppercase;margin:0 0 2rem}
.cat{margin:2.5rem 0 .5rem;font-family:var(--mono);font-size:.7rem;letter-spacing:.16em;
text-transform:uppercase;color:var(--faint);border-bottom:1px solid var(--line);
padding-bottom:.45rem}
.row{display:block;padding:.6rem .9rem;margin:0 -.9rem;border-bottom:1px solid var(--line);
border-radius:var(--r-soft);text-decoration:none}
.row:hover{background:#0a0a0a}
.nm{font-family:var(--mono);font-size:.84rem;color:var(--ink);display:block}
.ds{color:var(--soft);font-size:.9rem;display:block;margin-top:.12rem}
footer{margin-top:4rem;padding:2rem 0 4rem;border-top:1px solid var(--line);
color:var(--faint);font-size:.85rem}
footer a{color:var(--soft)}
.fmap{display:grid;gap:1.75rem;grid-template-columns:repeat(auto-fit,minmax(11rem,1fr));
margin:0 0 2rem;font-size:.85rem}
.fmap b{display:block;font-family:var(--mono);font-size:.68rem;letter-spacing:.16em;
text-transform:uppercase;color:var(--faint);font-weight:400;margin:0 0 .6rem;
border-bottom:1px solid var(--line);padding-bottom:.4rem}
.fmap a{display:inline-block;color:var(--ink);text-decoration:none;margin:.3rem .35rem 0 0}
.fmap a:hover{text-decoration:underline}
.fmap div{color:var(--faint);line-height:1.5}
.fend{border-top:1px solid var(--line);padding-top:1.25rem;font-size:.82rem}
@media (max-width:640px){
.hero .wrap{padding-top:3.25rem;padding-bottom:2.75rem}
.btns{gap:.5rem}
.btn{padding:.75rem 1.15rem;font-size:.68rem}
.copy,.copy .btn{width:100%;justify-content:center}
.menu{left:0;right:0;min-width:0}
.strip .in{flex-direction:column;align-items:flex-start;gap:.6rem;padding:.9rem 1.75rem}
.strip b{border-right:0;padding-right:0}
.bar{width:100%}
}
</style>
<link rel="icon" href="/favicon.svg">
<link rel="canonical" href="https://hanzoskills.com/testing-test-driven-development">
<link rel="alternate" type="text/markdown" href="/testing-test-driven-development.md">
<script type="module" src="/webmcp.js"></script>
</head>
<!-- Reading this with a machine? Every page here is also plain markdown.
This one: https://hanzoskills.com/testing-test-driven-development.md
Index: https://hanzoskills.com/llms.txt
Corpus: https://hanzoskills.com/all.md
Append .md to any path for the markdown twin. -->
<body>
<nav><div class="in">
<a class="brand" href="/"><svg class="mark" viewBox="0 0 67 67" fill="currentColor" aria-hidden="true"><path d="M22.21 67V44.6369H0V67H22.21Z"/><path d="M66.7038 22.3184H22.2534L0.0878906 44.6367H44.4634L66.7038 22.3184Z"/><path d="M22.21 0H0V22.3184H22.21V0Z"/><path d="M66.7198 0H44.5098V22.3184H66.7198V0Z"/><path d="M66.7198 67V44.6369H44.5098V67H66.7198Z"/></svg> HANZO<i>SKILLS</i></a>
<a class="up" href="/">All skills</a>
</div></nav>
<div class="wrap">
<h1>testing-test-driven-development</h1><p class="lede">Design APIs and interfaces through tests</p><h1>Test-Driven Development (TDD)</h1>
<h2>When to Use This Skill</h2>
<p>Use this skill when you need to:</p>
<ul><li>Design APIs and interfaces through tests</li><li>Ensure code is testable from the start</li><li>Build confidence before implementation</li><li>Refactor safely with comprehensive test coverage</li><li>Clarify requirements through test examples</li><li>Reduce debugging time with tight feedback loops</li><li>Decide when TDD is appropriate vs when to skip it</li></ul>
<p><strong>ACTIVATE THIS SKILL</strong>: When starting new features, fixing bugs, or refactoring complex code</p>
<h2>Core Concepts</h2>
<h3>The Red-Green-Refactor Cycle</h3>
<p><strong>RED</strong>: Write a failing test</p>
<ul><li>Test doesn&#x27;t compile OR test fails</li><li>Defines desired behavior</li><li>Forces you to think about API design</li></ul>
<p><strong>GREEN</strong>: Make it pass with minimal code</p>
<ul><li>Simplest implementation that works</li><li>Don&#x27;t worry about elegance yet</li><li>Just make the test pass</li></ul>
<p><strong>REFACTOR</strong>: Improve code without changing behavior</p>
<ul><li>Clean up duplication</li><li>Improve names and structure</li><li>Tests stay green</li></ul>
<pre><code>RED → GREEN → REFACTOR → RED → GREEN → REFACTOR → ...
↓ ↓ ↓
Fail Pass Improve</code></pre>
<h3>The Three Laws of TDD (Uncle Bob)</h3>
<ol><li><strong>Don&#x27;t write production code</strong> until you have a failing test</li><li><strong>Don&#x27;t write more of a test</strong> than is sufficient to fail</li><li><strong>Don&#x27;t write more production code</strong> than is sufficient to pass the test</li></ol>
<h3>TDD vs Test-After</h3>
<p><strong>Test-After</strong> (Traditional):</p>
<pre><code>Write code → Test it → Fix bugs → Ship</code></pre>
<p>Problems: Hard to test, low coverage, bugs found late</p>
<p><strong>TDD</strong>:</p>
<pre><code>Write test → Write code → Refactor → Ship</code></pre>
<p>Benefits: Testable design, high coverage, bugs prevented</p>
<h2>Patterns</h2>
<h3>Classic TDD: Function Implementation</h3>
<pre><code class="lang-python"># Step 1: RED - Write failing test
def test_calculate_discount():
# Arrange
original_price = 100
discount_percent = 10
# Act
final_price = calculate_discount(original_price, discount_percent)
# Assert
assert final_price == 90
# Run: FAILS - calculate_discount doesn&#x27;t exist
# Step 2: GREEN - Minimal implementation
def calculate_discount(price: float, discount: float) -&gt; float:
return price - (price * discount / 100)
# Run: PASSES
# Step 3: REFACTOR - Improve (if needed)
def calculate_discount(price: float, discount_percent: float) -&gt; float:
&quot;&quot;&quot;Calculate final price after applying discount percentage.&quot;&quot;&quot;
if discount_percent &lt; 0 or discount_percent &gt; 100:
raise ValueError(&quot;Discount must be between 0 and 100&quot;)
discount_amount = price * (discount_percent / 100)
return price - discount_amount
# Add test for edge case
def test_calculate_discount_invalid():
with pytest.raises(ValueError):
calculate_discount(100, -10)</code></pre>
<h3>TDD for Class Design</h3>
<pre><code class="lang-typescript">// Step 1: RED - Define interface through tests
describe(&#x27;ShoppingCart&#x27;, () =&gt; {
it(&#x27;starts empty&#x27;, () =&gt; {
const cart = new ShoppingCart();
expect(cart.itemCount).toBe(0);
expect(cart.total).toBe(0);
});
// FAILS: ShoppingCart doesn&#x27;t exist
});
// Step 2: GREEN - Minimal implementation
class ShoppingCart {
itemCount = 0;
total = 0;
}
// Step 3: RED - Next behavior
it(&#x27;adds items to cart&#x27;, () =&gt; {
const cart = new ShoppingCart();
cart.addItem({ name: &#x27;Laptop&#x27;, price: 1000 });
expect(cart.itemCount).toBe(1);
expect(cart.total).toBe(1000);
});
// Step 4: GREEN - Implement
class ShoppingCart {
private items: Item[] = [];
get itemCount() {
return this.items.length;
}
get total() {
return this.items.reduce((sum, item) =&gt; sum + item.price, 0);
}
addItem(item: Item) {
this.items.push(item);
}
}
// Step 5: RED - Add more behavior
it(&#x27;removes items from cart&#x27;, () =&gt; {
const cart = new ShoppingCart();
const item = { name: &#x27;Laptop&#x27;, price: 1000 };
cart.addItem(item);
cart.removeItem(item);
expect(cart.itemCount).toBe(0);
expect(cart.total).toBe(0);
});
// Step 6: GREEN - Implement
removeItem(item: Item) {
const index = this.items.indexOf(item);
if (index &gt; -1) {
this.items.splice(index, 1);
}
}
// Step 7: REFACTOR - Improve (add discount support, etc.)</code></pre>
<h3>Outside-In TDD (London School)</h3>
<p><strong>Start with acceptance test, work inward</strong>:</p>
<pre><code class="lang-python"># Step 1: Acceptance test (fails)
def test_user_can_register():
# Arrange
api = UserAPI()
# Act
response = api.register(
username=&quot;alice&quot;,
email=&quot;[email protected]&quot;,
password=&quot;secret123&quot;
)
# Assert
assert response.status_code == 201
assert response.user_id is not None
# Step 2: Mock dependencies, implement UserAPI
class UserAPI:
def __init__(self):
self.user_service = Mock(UserService)
self.email_service = Mock(EmailService)
def register(self, username, email, password):
user = self.user_service.create_user(username, email, password)
self.email_service.send_welcome_email(user.email)
return Response(status_code=201, user_id=user.id)
# Step 3: Now test UserService (unit test)
def test_user_service_creates_user():
repo = Mock(UserRepository)
service = UserService(repo)
user = service.create_user(&quot;alice&quot;, &quot;[email protected]&quot;, &quot;secret123&quot;)
assert user.username == &quot;alice&quot;
repo.save.assert_called_once_with(user)
# Step 4: Implement UserService
# Step 5: Test UserRepository
# Step 6: Implement UserRepository</code></pre>
<h3>Inside-Out TDD (Chicago School)</h3>
<p><strong>Start with smallest unit, build up</strong>:</p>
<pre><code class="lang-python"># Step 1: Test pure function
def test_hash_password():
hashed = hash_password(&quot;secret123&quot;)
assert hashed != &quot;secret123&quot;
assert len(hashed) == 60 # bcrypt length
# Step 2: Implement
import bcrypt
def hash_password(password: str) -&gt; str:
return bcrypt.hashpw(password.encode(), bcrypt.gensalt()).decode()
# Step 3: Test User model
def test_user_creation():
user = User(username=&quot;alice&quot;, email=&quot;[email protected]&quot;, password_hash=&quot;hashed&quot;)
assert user.username == &quot;alice&quot;
assert user.is_active is True
# Step 4: Implement User
@dataclass
class User:
username: str
email: str
password_hash: str
is_active: bool = True
# Step 5: Test UserService (using real dependencies)
def test_user_service_creates_user():
repo = InMemoryUserRepository()
service = UserService(repo)
user = service.create_user(&quot;alice&quot;, &quot;[email protected]&quot;, &quot;secret123&quot;)
assert user.username == &quot;alice&quot;
assert repo.find_by_username(&quot;alice&quot;) is not None</code></pre>
<h3>TDD for Bug Fixes</h3>
<pre><code class="lang-python"># Bug report: &quot;Users can register with duplicate emails&quot;
# Step 1: RED - Write failing test that reproduces bug
def test_cannot_register_duplicate_email():
service = UserService()
service.register(&quot;alice&quot;, &quot;[email protected]&quot;, &quot;pass1&quot;)
with pytest.raises(DuplicateEmailError):
service.register(&quot;bob&quot;, &quot;[email protected]&quot;, &quot;pass2&quot;)
# Run: FAILS - No DuplicateEmailError raised (bug confirmed)
# Step 2: GREEN - Fix the bug
class UserService:
def register(self, username, email, password):
if self.repository.find_by_email(email):
raise DuplicateEmailError(f&quot;Email {email} already registered&quot;)
user = User(username, email, hash_password(password))
self.repository.save(user)
return user
# Run: PASSES - Bug fixed
# Step 3: REFACTOR - Add index to database
# Add migration for unique email constraint</code></pre>
<h3>TDD for Refactoring</h3>
<pre><code class="lang-python"># Step 1: Ensure comprehensive tests exist
def test_order_total_calculation():
order = Order()
order.add_item(Item(&quot;Laptop&quot;, price=1000, quantity=1))
order.add_item(Item(&quot;Mouse&quot;, price=25, quantity=2))
assert order.calculate_total() == 1050
def test_order_total_with_discount():
order = Order(discount_code=&quot;SAVE10&quot;)
order.add_item(Item(&quot;Laptop&quot;, price=1000, quantity=1))
assert order.calculate_total() == 900
# Step 2: All tests GREEN
# Step 3: Refactor (e.g., extract calculation logic)
class OrderCalculator:
def calculate_total(self, items: List[Item], discount_code: str = None) -&gt; float:
subtotal = sum(item.price * item.quantity for item in items)
if discount_code:
discount = self.get_discount(discount_code)
subtotal -= subtotal * discount
return subtotal
class Order:
def __init__(self, discount_code=None):
self.items = []
self.discount_code = discount_code
self.calculator = OrderCalculator()
def calculate_total(self):
return self.calculator.calculate_total(self.items, self.discount_code)
# Step 4: Tests still GREEN - refactor successful</code></pre>
<h2>Examples by Language</h2>
<h3>Python (pytest)</h3>
<pre><code class="lang-python"># Step 1: RED
def test_fizzbuzz_returns_number():
assert fizzbuzz(1) == &quot;1&quot;
assert fizzbuzz(2) == &quot;2&quot;
# FAILS: fizzbuzz not defined
# Step 2: GREEN
def fizzbuzz(n: int) -&gt; str:
return str(n)
# PASSES
# Step 3: RED
def test_fizzbuzz_multiples_of_three():
assert fizzbuzz(3) == &quot;Fizz&quot;
assert fizzbuzz(6) == &quot;Fizz&quot;
# FAILS
# Step 4: GREEN
def fizzbuzz(n: int) -&gt; str:
if n % 3 == 0:
return &quot;Fizz&quot;
return str(n)
# Step 5: RED
def test_fizzbuzz_multiples_of_five():
assert fizzbuzz(5) == &quot;Buzz&quot;
assert fizzbuzz(10) == &quot;Buzz&quot;
# Step 6: GREEN
def fizzbuzz(n: int) -&gt; str:
if n % 3 == 0:
return &quot;Fizz&quot;
if n % 5 == 0:
return &quot;Buzz&quot;
return str(n)
# Step 7: RED
def test_fizzbuzz_multiples_of_fifteen():
assert fizzbuzz(15) == &quot;FizzBuzz&quot;
assert fizzbuzz(30) == &quot;FizzBuzz&quot;
# Step 8: GREEN
def fizzbuzz(n: int) -&gt; str:
if n % 15 == 0:
return &quot;FizzBuzz&quot;
if n % 3 == 0:
return &quot;Fizz&quot;
if n % 5 == 0:
return &quot;Buzz&quot;
return str(n)</code></pre>
<h3>Rust</h3>
<pre><code class="lang-rust">// Step 1: RED
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_empty_vec_sum_is_zero() {
let result = sum(vec![]);
assert_eq!(result, 0);
}
}
// FAILS: sum not defined
// Step 2: GREEN
pub fn sum(numbers: Vec&lt;i32&gt;) -&gt; i32 {
0
}
// Step 3: RED
#[test]
fn test_single_number() {
assert_eq!(sum(vec![5]), 5);
}
// Step 4: GREEN
pub fn sum(numbers: Vec&lt;i32&gt;) -&gt; i32 {
numbers.iter().sum()
}
// PASSES for all tests
// Step 5: REFACTOR (generic version)
pub fn sum&lt;T: std::iter::Sum&gt;(numbers: Vec&lt;T&gt;) -&gt; T {
numbers.into_iter().sum()
}</code></pre>
<h3>Go</h3>
<pre><code class="lang-go">// Step 1: RED
func TestReverseString(t *testing.T) {
result := Reverse(&quot;hello&quot;)
expected := &quot;olleh&quot;
if result != expected {
t.Errorf(&quot;got %s, want %s&quot;, result, expected)
}
}
// FAILS: Reverse not defined
// Step 2: GREEN
func Reverse(s string) string {
runes := []rune(s)
for i, j := 0, len(runes)-1; i &lt; j; i, j = i+1, j-1 {
runes[i], runes[j] = runes[j], runes[i]
}
return string(runes)
}
// PASSES
// Step 3: RED - Edge cases
func TestReverseEmptyString(t *testing.T) {
assert.Equal(t, &quot;&quot;, Reverse(&quot;&quot;))
}
func TestReverseUnicode(t *testing.T) {
assert.Equal(t, &quot;😀👋&quot;, Reverse(&quot;👋😀&quot;))
}
// PASSES (already handles these cases)</code></pre>
<h3>TypeScript (Vitest)</h3>
<pre><code class="lang-typescript">// Step 1: RED
describe(&#x27;Stack&#x27;, () =&gt; {
it(&#x27;starts empty&#x27;, () =&gt; {
const stack = new Stack&lt;number&gt;();
expect(stack.isEmpty()).toBe(true);
expect(stack.size()).toBe(0);
});
});
// FAILS: Stack doesn&#x27;t exist
// Step 2: GREEN
class Stack&lt;T&gt; {
isEmpty() {
return true;
}
size() {
return 0;
}
}
// Step 3: RED
it(&#x27;pushes items&#x27;, () =&gt; {
const stack = new Stack&lt;number&gt;();
stack.push(1);
expect(stack.isEmpty()).toBe(false);
expect(stack.size()).toBe(1);
});
// Step 4: GREEN
class Stack&lt;T&gt; {
private items: T[] = [];
isEmpty() {
return this.items.length === 0;
}
size() {
return this.items.length;
}
push(item: T) {
this.items.push(item);
}
}
// Continue: pop, peek, etc.</code></pre>
<h2>When to Use TDD</h2>
<h3>✅ GOOD Use Cases</h3>
<p><strong>New features with clear requirements</strong>:</p>
<ul><li>API endpoints with defined contracts</li><li>Business logic with known rules</li><li>Data transformations with examples</li></ul>
<p><strong>Bug fixes</strong>:</p>
<ul><li>Write failing test that reproduces bug</li><li>Fix code until test passes</li><li>Prevents regression</li></ul>
<p><strong>Complex algorithms</strong>:</p>
<ul><li>TDD helps break down problem</li><li>Tests document expected behavior</li><li>Safe to refactor later</li></ul>
<p><strong>Refactoring</strong>:</p>
<ul><li>Comprehensive tests before refactoring</li><li>Tests stay green during refactor</li><li>Confidence in changes</li></ul>
<h3>❌ Poor Use Cases</h3>
<p><strong>Exploratory coding</strong>:</p>
<ul><li>Don&#x27;t know what you&#x27;re building yet</li><li>Spike first, TDD later</li></ul>
<p><strong>UI/UX experimentation</strong>:</p>
<ul><li>Visual design requires iteration</li><li>E2E tests after design settles</li></ul>
<p><strong>Prototypes and throwaway code</strong>:</p>
<ul><li>Not worth the overhead</li><li>TDD when productionizing</li></ul>
<p><strong>Trivial code</strong>:</p>
<ul><li>Simple getters/setters</li><li>Boilerplate with no logic</li></ul>
<h2>Checklist</h2>
<p><strong>Before Starting TDD</strong>:</p>
<ul><li>[ ] Requirements are clear (or will be discovered)</li><li>[ ] You know what &quot;done&quot; looks like</li><li>[ ] Test framework is set up</li><li>[ ] You can run tests quickly (&lt; 1 second)</li></ul>
<p><strong>During TDD Cycle</strong>:</p>
<ul><li>[ ] Write smallest possible failing test</li><li>[ ] Run test and see it fail (RED)</li><li>[ ] Write simplest code to pass (GREEN)</li><li>[ ] Run test and see it pass</li><li>[ ] Refactor if needed (tests stay GREEN)</li><li>[ ] Commit (green state only)</li></ul>
<p><strong>Test Quality</strong>:</p>
<ul><li>[ ] Tests are readable (describe behavior)</li><li>[ ] Tests are independent (no order dependency)</li><li>[ ] Tests are fast (&lt; 100ms unit tests)</li><li>[ ] One concept per test</li><li>[ ] Descriptive test names</li></ul>
<p><strong>After TDD Session</strong>:</p>
<ul><li>[ ] All tests passing</li><li>[ ] Code coverage is high (80%+ for TDD&#x27;d code)</li><li>[ ] Code is clean (refactored)</li><li>[ ] Tests document behavior</li><li>[ ] No skipped or ignored tests</li></ul>
<h2>Anti-Patterns</h2>
<pre><code>❌ NEVER: Write production code before test
→ Defeats purpose of TDD
❌ NEVER: Write all tests upfront
→ Too much investment before feedback
❌ NEVER: Skip refactor step
→ Accumulates technical debt
❌ NEVER: Make big leaps (many changes at once)
→ Hard to debug when test fails
❌ NEVER: Keep tests passing by commenting out assertions
→ False confidence
❌ NEVER: Test implementation details
→ Breaks during refactoring
❌ NEVER: Use TDD for everything
→ Wrong tool for exploratory work</code></pre>
<h2>Related Skills</h2>
<p><strong>Foundation</strong>:</p>
<ul><li><code>unit-testing-patterns.md</code> - How to write good unit tests</li><li><code>test-coverage-strategy.md</code> - What to test and coverage goals</li></ul>
<p><strong>Advanced</strong>:</p>
<ul><li><code>integration-testing.md</code> - TDD for integration tests</li><li><code>refactoring-patterns.md</code> - Safe refactoring with tests</li></ul>
<p><strong>Supporting</strong>:</p>
<ul><li><code>mocking-strategies.md</code> - Mock dependencies in TDD</li><li><code>test-doubles.md</code> - Stubs, mocks, spies, fakes</li></ul>
<p><strong>Philosophy</strong>:</p>
<ul><li>Kent Beck: &quot;Test-Driven Development by Example&quot;</li><li>Uncle Bob: &quot;Clean Code&quot; (TDD chapter)</li><li>Martin Fowler: &quot;Is TDD Dead?&quot; series</li></ul>
<footer>
<div class="fmap">
<div><b>Build</b>
<a href="https://hanzo.app">hanzo.app</a> app builder
<a href="https://hanzo.codes">hanzo.codes</a> code with an agent
<a href="https://hanzoskills.com">hanzoskills.com</a> what an agent reads</div>
<div><b>Run</b>
<a href="https://console.hanzo.ai">console.hanzo.ai</a> cloud console
<a href="https://api.hanzo.ai">api.hanzo.ai</a> the API</div>
<div><b>Account</b>
<a href="https://hanzo.id">hanzo.id</a> sign in
<a href="https://pay.hanzo.ai">pay.hanzo.ai</a> top up
<a href="https://billing.hanzo.ai">billing.hanzo.ai</a> invoices and usage</div>
<div><b>Company</b>
<a href="https://hanzo.ai">hanzo.ai</a> canonical
<a href="https://hanzo.ventures">hanzo.ventures</a> ventures</div>
</div>
<div class="fend"><a href="/testing-test-driven-development.md">This page as plain text</a> · <a href="/llms.txt">Index for agents</a></div>
</footer>
</div></body></html>