Files
skills/public/engineering-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

793 lines
37 KiB
HTML

<!doctype html>
<html lang="en"><head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>engineering-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/engineering-test-driven-development">
<link rel="alternate" type="text/markdown" href="/engineering-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/engineering-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>engineering-test-driven-development</h1><p class="lede">Test-Driven Development methodology, red-green-refactor cycle, unit testing best practices, and mocking strategies</p><h1>Test-Driven Development (TDD)</h1>
<p><strong>Scope</strong>: Comprehensive guide to TDD methodology, red-green-refactor cycle, unit testing, mocking, and test design <strong>Lines</strong>: ~380 <strong>Last Updated</strong>: 2025-10-27 <strong>Format Version</strong>: 1.0 (Atomic)</p>
<hr>
<h2>When to Use This Skill</h2>
<p>Activate this skill when:</p>
<ul><li>Starting new features or projects from scratch</li><li>Improving test coverage in existing code</li><li>Designing highly testable code</li><li>Establishing testing culture in a team</li><li>Reducing bug rates through disciplined testing</li><li>Clarifying requirements through test cases</li><li>Refactoring with confidence</li><li>Building critical business logic that must be correct</li></ul>
<h2>Core Concepts</h2>
<h3>Concept 1: The Red-Green-Refactor Cycle</h3>
<p><strong>The TDD Mantra</strong>: Red → Green → Refactor</p>
<pre><code>1. RED: Write a failing test
↓
2. GREEN: Write minimal code to make it pass
↓
3. REFACTOR: Improve code without changing behavior
↓
4. REPEAT</code></pre>
<p><strong>Rules</strong>:</p>
<ul><li>Don&#x27;t write production code without a failing test</li><li>Don&#x27;t write more test than sufficient to fail</li><li>Don&#x27;t write more production code than sufficient to pass</li></ul>
<p><strong>Example Cycle</strong>:</p>
<pre><code class="lang-python"># RED: Write failing test
def test_add_two_numbers():
calculator = Calculator()
assert calculator.add(2, 3) == 5 # Fails - Calculator doesn&#x27;t exist
# GREEN: Minimal code to pass
class Calculator:
def add(self, a, b):
return 5 # Hardcoded - but test passes!
# RED: Write another test
def test_add_different_numbers():
calculator = Calculator()
assert calculator.add(10, 20) == 30 # Fails with hardcoded 5
# GREEN: Real implementation
class Calculator:
def add(self, a, b):
return a + b # Now all tests pass
# REFACTOR: Clean up if needed (none needed here)</code></pre>
<hr>
<h3>Concept 2: Test Structure (AAA Pattern)</h3>
<p><strong>Arrange-Act-Assert</strong>:</p>
<pre><code class="lang-python">def test_user_login():
# Arrange: Set up test data
user = User(email=&quot;[email protected]&quot;, password=&quot;secret123&quot;)
user.save()
# Act: Execute the action being tested
result = authenticate(email=&quot;[email protected]&quot;, password=&quot;secret123&quot;)
# Assert: Verify the result
assert result.success is True
assert result.user.email == &quot;[email protected]&quot;</code></pre>
<p><strong>Given-When-Then</strong> (BDD style):</p>
<pre><code class="lang-typescript">describe(&quot;User Login&quot;, () =&gt; {
it(&quot;should authenticate user with correct credentials&quot;, () =&gt; {
// Given: A registered user
const user = createUser({ email: &quot;[email protected]&quot;, password: &quot;secret&quot; });
// When: User attempts to login
const result = authenticate(&quot;[email protected]&quot;, &quot;secret&quot;);
// Then: Authentication succeeds
expect(result.success).toBe(true);
expect(result.user.email).toBe(&quot;[email protected]&quot;);
});
});</code></pre>
<hr>
<h3>Concept 3: Test Doubles (Mocks, Stubs, Fakes)</h3>
<p><strong>Stub</strong>: Returns predefined data</p>
<pre><code class="lang-python">class StubEmailService:
def send(self, to, subject, body):
return True # Always succeeds</code></pre>
<p><strong>Mock</strong>: Verifies interactions</p>
<pre><code class="lang-python">mock_email = Mock()
service.send_welcome_email(user)
mock_email.send.assert_called_once_with(
to=&quot;[email protected]&quot;,
subject=&quot;Welcome!&quot;,
body=&quot;Welcome to our app!&quot;
)</code></pre>
<p><strong>Fake</strong>: Working implementation (simplified)</p>
<pre><code class="lang-python">class FakeDatabase:
def __init__(self):
self.data = {}
def save(self, key, value):
self.data[key] = value
def get(self, key):
return self.data.get(key)</code></pre>
<hr>
<h2>Patterns</h2>
<h3>Pattern 1: Testing Pure Functions (Easiest)</h3>
<p><strong>Pure Function</strong>: Same inputs → Same outputs, no side effects</p>
<pre><code class="lang-python"># RED: Write test first
def test_calculate_tax():
assert calculate_tax(100, 0.08) == 8.0
assert calculate_tax(50, 0.10) == 5.0
assert calculate_tax(0, 0.08) == 0.0
# GREEN: Implement
def calculate_tax(amount: float, rate: float) -&gt; float:
return amount * rate
# REFACTOR: Add edge case tests
def test_calculate_tax_negative():
with pytest.raises(ValueError):
calculate_tax(-100, 0.08)
def calculate_tax(amount: float, rate: float) -&gt; float:
if amount &lt; 0:
raise ValueError(&quot;Amount cannot be negative&quot;)
return amount * rate</code></pre>
<hr>
<h3>Pattern 2: Testing with Dependencies (Mocking)</h3>
<p><strong>Before TDD</strong> (hard to test):</p>
<pre><code class="lang-python">class UserService:
def create_user(self, email):
db = PostgresDatabase() # Hard-coded dependency!
email_service = SendGridEmailService() # Another one!
user = db.save({&quot;email&quot;: email})
email_service.send(user.email, &quot;Welcome!&quot;)
return user</code></pre>
<p><strong>TDD Approach</strong> (test first drives design):</p>
<pre><code class="lang-python"># RED: Write test with mocks
def test_create_user():
mock_db = Mock()
mock_email = Mock()
mock_db.save.return_value = User(id=1, email=&quot;[email protected]&quot;)
service = UserService(db=mock_db, email_service=mock_email)
user = service.create_user(&quot;[email protected]&quot;)
# Verify interactions
mock_db.save.assert_called_once_with({&quot;email&quot;: &quot;[email protected]&quot;})
mock_email.send.assert_called_once_with(&quot;[email protected]&quot;, &quot;Welcome!&quot;)
assert user.email == &quot;[email protected]&quot;
# GREEN: Implement with dependency injection
class UserService:
def __init__(self, db, email_service):
self.db = db
self.email_service = email_service
def create_user(self, email):
user = self.db.save({&quot;email&quot;: email})
self.email_service.send(user.email, &quot;Welcome!&quot;)
return user</code></pre>
<p><strong>TDD Forced Good Design</strong>: Dependency injection makes code testable!</p>
<hr>
<h3>Pattern 3: Table-Driven Tests (Go Style)</h3>
<pre><code class="lang-go">func TestCalculateDiscount(t *testing.T) {
tests := []struct {
name string
amount float64
userType string
want float64
}{
{&quot;Premium user, large purchase&quot;, 1000, &quot;premium&quot;, 200},
{&quot;Premium user, small purchase&quot;, 50, &quot;premium&quot;, 5},
{&quot;Regular user, large purchase&quot;, 1000, &quot;regular&quot;, 100},
{&quot;Regular user, small purchase&quot;, 50, &quot;regular&quot;, 0},
{&quot;Guest user&quot;, 1000, &quot;guest&quot;, 0},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := CalculateDiscount(tt.amount, tt.userType)
if got != tt.want {
t.Errorf(&quot;CalculateDiscount(%v, %v) = %v, want %v&quot;,
tt.amount, tt.userType, got, tt.want)
}
})
}
}</code></pre>
<hr>
<h3>Pattern 4: Testing Async Code</h3>
<p><strong>Python (async/await)</strong>:</p>
<pre><code class="lang-python">import pytest
@pytest.mark.asyncio
async def test_fetch_user_data():
# Arrange
user_id = &quot;123&quot;
mock_api = AsyncMock()
mock_api.get_user.return_value = {&quot;id&quot;: &quot;123&quot;, &quot;name&quot;: &quot;John&quot;}
service = UserService(api=mock_api)
# Act
user = await service.fetch_user_data(user_id)
# Assert
assert user[&quot;name&quot;] == &quot;John&quot;
mock_api.get_user.assert_called_once_with(user_id)</code></pre>
<p><strong>TypeScript (Promises)</strong>:</p>
<pre><code class="lang-typescript">describe(&quot;fetchUserData&quot;, () =&gt; {
it(&quot;should fetch user from API&quot;, async () =&gt; {
// Arrange
const mockApi = {
getUser: jest.fn().mockResolvedValue({ id: &quot;123&quot;, name: &quot;John&quot; }),
};
const service = new UserService(mockApi);
// Act
const user = await service.fetchUserData(&quot;123&quot;);
// Assert
expect(user.name).toBe(&quot;John&quot;);
expect(mockApi.getUser).toHaveBeenCalledWith(&quot;123&quot;);
});
});</code></pre>
<hr>
<h3>Pattern 5: Testing Error Conditions</h3>
<pre><code class="lang-python">def test_divide_by_zero():
calculator = Calculator()
with pytest.raises(ZeroDivisionError):
calculator.divide(10, 0)
def test_invalid_email():
with pytest.raises(ValidationError) as exc_info:
create_user(email=&quot;invalid-email&quot;)
assert &quot;Invalid email format&quot; in str(exc_info.value)
def test_user_not_found():
result = find_user(user_id=&quot;nonexistent&quot;)
assert result is None # Or raises UserNotFoundError</code></pre>
<hr>
<h3>Pattern 6: Parameterized Tests</h3>
<p><strong>Python (pytest)</strong>:</p>
<pre><code class="lang-python">@pytest.mark.parametrize(&quot;input,expected&quot;, [
(&quot;hello&quot;, &quot;HELLO&quot;),
(&quot;WORLD&quot;, &quot;WORLD&quot;),
(&quot;TeSt&quot;, &quot;TEST&quot;),
(&quot;&quot;, &quot;&quot;),
])
def test_uppercase(input, expected):
assert uppercase(input) == expected</code></pre>
<p><strong>TypeScript (Jest)</strong>:</p>
<pre><code class="lang-typescript">test.each([
[1, 1, 2],
[2, 2, 4],
[5, 3, 8],
])(&quot;add(%i, %i) should return %i&quot;, (a, b, expected) =&gt; {
expect(add(a, b)).toBe(expected);
});</code></pre>
<hr>
<h3>Pattern 7: Test Fixtures and Setup</h3>
<p><strong>Python (pytest fixtures)</strong>:</p>
<pre><code class="lang-python">@pytest.fixture
def sample_user():
&quot;&quot;&quot;Create a test user for multiple tests&quot;&quot;&quot;
return User(email=&quot;[email protected]&quot;, name=&quot;Test User&quot;)
@pytest.fixture
def database():
&quot;&quot;&quot;Set up and tear down test database&quot;&quot;&quot;
db = create_test_database()
yield db
db.drop_all()
def test_save_user(database, sample_user):
database.save(sample_user)
assert database.count() == 1
def test_find_user(database, sample_user):
database.save(sample_user)
found = database.find_by_email(&quot;[email protected]&quot;)
assert found.name == &quot;Test User&quot;</code></pre>
<p><strong>TypeScript (Jest)</strong>:</p>
<pre><code class="lang-typescript">describe(&quot;UserService&quot;, () =&gt; {
let service: UserService;
let mockDb: Database;
beforeEach(() =&gt; {
mockDb = createMockDatabase();
service = new UserService(mockDb);
});
afterEach(() =&gt; {
mockDb.clear();
});
it(&quot;should save user&quot;, () =&gt; {
const user = { email: &quot;[email protected]&quot; };
service.save(user);
expect(mockDb.count()).toBe(1);
});
});</code></pre>
<hr>
<h3>Pattern 8: Testing Private Methods (Don&#x27;t!)</h3>
<p><strong>Bad Approach</strong>:</p>
<pre><code class="lang-python"># DON&#x27;T: Testing private methods directly
def test_private_validation():
obj = MyClass()
assert obj._validate_input(&quot;test&quot;) is True # Testing private method</code></pre>
<p><strong>Good Approach</strong>:</p>
<pre><code class="lang-python"># DO: Test through public interface
def test_public_method_with_valid_input():
obj = MyClass()
result = obj.process(&quot;test&quot;) # Public method
assert result.success is True # Private validation tested indirectly
def test_public_method_with_invalid_input():
obj = MyClass()
result = obj.process(&quot;&quot;) # Public method
assert result.success is False # Private validation tested indirectly</code></pre>
<p><strong>Principle</strong>: Tests should verify behavior, not implementation details</p>
<hr>
<h2>TDD Workflow Examples</h2>
<h3>Example 1: Building a String Calculator (Classic Kata)</h3>
<p><strong>Requirement</strong>: Create a calculator that adds numbers in a string</p>
<pre><code class="lang-python"># Iteration 1: Empty string
def test_empty_string_returns_zero():
assert string_calculator(&quot;&quot;) == 0
def string_calculator(numbers):
return 0 # Minimal code to pass
# Iteration 2: Single number
def test_single_number():
assert string_calculator(&quot;5&quot;) == 5
def string_calculator(numbers):
if not numbers:
return 0
return int(numbers)
# Iteration 3: Two numbers
def test_two_numbers():
assert string_calculator(&quot;1,2&quot;) == 3
def string_calculator(numbers):
if not numbers:
return 0
return sum(int(n) for n in numbers.split(&quot;,&quot;))
# Iteration 4: Multiple numbers
def test_multiple_numbers():
assert string_calculator(&quot;1,2,3,4&quot;) == 10
# Already passes with current implementation!
# Iteration 5: New line delimiter
def test_newline_delimiter():
assert string_calculator(&quot;1\n2,3&quot;) == 6
def string_calculator(numbers):
if not numbers:
return 0
numbers = numbers.replace(&quot;\n&quot;, &quot;,&quot;)
return sum(int(n) for n in numbers.split(&quot;,&quot;))
# Iteration 6: Negative numbers throw exception
def test_negative_numbers_throw():
with pytest.raises(ValueError, match=&quot;Negatives not allowed: -2, -5&quot;):
string_calculator(&quot;1,-2,3,-5&quot;)
def string_calculator(numbers):
if not numbers:
return 0
numbers = numbers.replace(&quot;\n&quot;, &quot;,&quot;)
nums = [int(n) for n in numbers.split(&quot;,&quot;)]
negatives = [n for n in nums if n &lt; 0]
if negatives:
raise ValueError(f&quot;Negatives not allowed: {&#x27;, &#x27;.join(map(str, negatives))}&quot;)
return sum(nums)</code></pre>
<p><strong>TDD Benefits Demonstrated</strong>:</p>
<ul><li>Requirements clarified through tests</li><li>Code grows organically</li><li>Always working (green) state</li><li>Refactoring is safe</li></ul>
<hr>
<h3>Example 2: TDD for API Endpoints</h3>
<pre><code class="lang-python"># RED: Test first
def test_create_user_endpoint(client):
response = client.post(&quot;/users&quot;, json={
&quot;email&quot;: &quot;[email protected]&quot;,
&quot;name&quot;: &quot;Test User&quot;
})
assert response.status_code == 201
assert response.json[&quot;email&quot;] == &quot;[email protected]&quot;
assert &quot;id&quot; in response.json
# GREEN: Implement minimal endpoint
@app.post(&quot;/users&quot;)
def create_user(request):
data = request.json
user = User(email=data[&quot;email&quot;], name=data[&quot;name&quot;])
db.save(user)
return {&quot;id&quot;: user.id, &quot;email&quot;: user.email}, 201
# RED: Test validation
def test_create_user_invalid_email(client):
response = client.post(&quot;/users&quot;, json={
&quot;email&quot;: &quot;invalid-email&quot;,
&quot;name&quot;: &quot;Test&quot;
})
assert response.status_code == 400
assert &quot;Invalid email&quot; in response.json[&quot;error&quot;]
# GREEN: Add validation
@app.post(&quot;/users&quot;)
def create_user(request):
data = request.json
if not is_valid_email(data[&quot;email&quot;]):
return {&quot;error&quot;: &quot;Invalid email format&quot;}, 400
user = User(email=data[&quot;email&quot;], name=data[&quot;name&quot;])
db.save(user)
return {&quot;id&quot;: user.id, &quot;email&quot;: user.email}, 201</code></pre>
<hr>
<h2>Best Practices</h2>
<h3>TDD Guidelines</h3>
<p><strong>Do&#x27;s</strong>:</p>
<ul><li>Write tests first (red → green → refactor)</li><li>Keep tests simple and focused</li><li>Test behavior, not implementation</li><li>Use descriptive test names</li><li>One assertion per test (when practical)</li><li>Run tests frequently (every few minutes)</li><li>Commit after each green state</li></ul>
<p><strong>Don&#x27;ts</strong>:</p>
<ul><li>Don&#x27;t skip the refactor step</li><li>Don&#x27;t test private methods</li><li>Don&#x27;t write tests after implementation (that&#x27;s not TDD!)</li><li>Don&#x27;t make tests depend on each other</li><li>Don&#x27;t test framework code</li><li>Don&#x27;t write overly complex test setups</li></ul>
<hr>
<h3>Test Naming Conventions</h3>
<p><strong>Good Test Names</strong>:</p>
<pre><code class="lang-python">def test_add_returns_sum_of_two_numbers()
def test_divide_raises_error_when_divisor_is_zero()
def test_create_user_saves_to_database()
def test_authenticate_fails_with_invalid_password()</code></pre>
<p><strong>Pattern</strong>: <code>test_[method]_[scenario]_[expected_result]</code></p>
<hr>
<h2>Anti-Patterns</h2>
<h3>Common TDD Mistakes</h3>
<pre><code>❌ Writing all tests upfront
→ Write one test at a time, see it fail, make it pass
❌ Testing getters/setters
→ Test actual behavior, not trivial code
❌ Overly complex test setup
→ Simplify with fixtures or factory functions
❌ Tests that depend on each other
→ Each test should be independent
❌ Not seeing tests fail first
→ Always see red before green (ensures test works)
❌ Skipping refactor step
→ Refactor to keep code clean
❌ Testing implementation details
→ Test through public interface
❌ Slow tests
→ Use mocks/stubs for fast unit tests</code></pre>
<hr>
<h2>Tools &amp; Frameworks</h2>
<h3>Python</h3>
<pre><code class="lang-bash"># pytest: Most popular Python test framework
pytest tests/
# Coverage
pytest --cov=src --cov-report=html
# Watch mode (rerun on changes)
pytest-watch
# Mocking
from unittest.mock import Mock, patch</code></pre>
<h3>TypeScript/JavaScript</h3>
<pre><code class="lang-bash"># Jest: Popular testing framework
npm test
# Watch mode
npm test -- --watch
# Coverage
npm test -- --coverage
# Mocking
jest.mock(&#x27;./module&#x27;)</code></pre>
<h3>Go</h3>
<pre><code class="lang-bash"># Built-in testing
go test ./...
# Coverage
go test -cover ./...
# Table-driven tests (idiomatic Go)</code></pre>
<h3>Test Runners</h3>
<pre><code class="lang-bash"># Continuous testing
npm install -g wallaby.js # IDE integration
npm install -g jest --watch # CLI watch mode</code></pre>
<hr>
<h2>Level 3: Resources</h2>
<h3>Comprehensive Reference</h3>
<p><strong>Location</strong>: <code>skills/engineering/test-driven-development/resources/REFERENCE.md</code> (~900 lines)</p>
<p>Complete reference covering:</p>
<ul><li>TDD fundamentals and the three laws</li><li>Red-Green-Refactor cycle in depth</li><li>Test-first development principles</li><li>Unit test design patterns (fixtures, builders, object mothers)</li><li>Test doubles and mocking strategies (dummies, stubs, spies, mocks, fakes)</li><li>Inside-Out vs Outside-In TDD approaches</li><li>ATDD (Acceptance Test-Driven Development)</li><li>BDD (Behavior-Driven Development)</li><li>TDD with different paradigms (OOP, functional, property-based)</li><li>Common TDD mistakes and solutions</li><li>Refactoring safely with tests</li><li>TDD metrics and benefits (coverage, defect density, velocity)</li><li>TDD in different contexts (Web APIs, frontend, databases, CLI tools)</li><li>Advanced TDD techniques (mutation testing, contract testing, characterization tests)</li><li>TDD anti-patterns (Free Ride, The Liar, The Mockery, The Inspector, The Slowpoke)</li></ul>
<h3>Scripts</h3>
<p><strong>Location</strong>: <code>skills/engineering/test-driven-development/resources/scripts/</code></p>
<p><strong>1. TDD Session Tracker</strong> (<code>tdd_session.py</code>)</p>
<ul><li>Interactive tracker for Red-Green-Refactor cycles</li><li>Times each phase (RED, GREEN, REFACTOR)</li><li>Tracks cycle metrics and session statistics</li><li>Identifies slow phases and suggests improvements</li><li>Exports session data to JSON for analysis</li></ul>
<pre><code class="lang-bash"># Start interactive TDD session
./tdd_session.py start
# Analyze completed session
./tdd_session.py analyze --session-file session.json
# Get session statistics
./tdd_session.py stats --session-file session.json --json</code></pre>
<p><strong>2. TDD Metrics Analyzer</strong> (<code>analyze_tdd_metrics.py</code>)</p>
<ul><li>Calculate test-to-code ratios</li><li>Analyze coverage trends and progression</li><li>Detect test smells and anti-patterns</li><li>Generate TDD health scores (0-100)</li><li>Track metrics across git history</li></ul>
<pre><code class="lang-bash"># Calculate test-to-code ratio
./analyze_tdd_metrics.py ratio --source-dir src/ --test-dir tests/
# Analyze TDD health
./analyze_tdd_metrics.py health --source-dir src/ --test-dir tests/ --coverage-file .coverage
# Track metrics across commits
./analyze_tdd_metrics.py history --repo-dir . --commits 10 --json</code></pre>
<p><strong>3. Test Template Generator</strong> (<code>generate_test_template.sh</code>)</p>
<ul><li>Generate language-specific test templates</li><li>Support for Python (pytest), TypeScript (Jest), Rust, Go</li><li>BDD (Given-When-Then) or AAA (Arrange-Act-Assert) styles</li><li>Includes fixtures, parameterized tests, and best practices</li></ul>
<pre><code class="lang-bash"># Python pytest template
./generate_test_template.sh python Calculator --framework pytest
# TypeScript Jest template with BDD style
./generate_test_template.sh typescript UserService --style bdd
# Rust test template
./generate_test_template.sh rust string_utils
# Go table-driven test template
./generate_test_template.sh go Validator</code></pre>
<h3>Examples</h3>
<p><strong>Location</strong>: <code>skills/engineering/test-driven-development/resources/examples/</code></p>
<p><strong>Python</strong> (<code>python/tdd_example.py</code>)</p>
<ul><li>String Calculator kata showing full TDD progression</li><li>Before/after comparison (implementation-first vs test-first)</li><li>Complete Red-Green-Refactor cycles for each requirement</li><li>Demonstrates incremental development and continuous refactoring</li><li>Test suite evolution from simple to comprehensive</li></ul>
<p><strong>TypeScript</strong> (<code>typescript/tdd_example.test.ts</code>)</p>
<ul><li>Bowling Game kata in TypeScript with Jest</li><li>Shows TDD rhythm in a stateful object</li><li>Demonstrates test organization with describe blocks</li><li>Helper functions to reduce test duplication</li><li>Complete progression from gutter game to perfect game</li></ul>
<p><strong>Rust</strong> (<code>rust/tdd_example.rs</code>)</p>
<ul><li>Stack implementation showing TDD with Rust&#x27;s type system</li><li>Demonstrates Result&lt;T, E&gt; error handling in tests</li><li>Shows how ownership/borrowing influences test design</li><li>Property-based testing examples (with proptest)</li><li>Nested test modules for organization</li></ul>
<p><strong>Workflow Guide</strong> (<code>workflows/tdd-workflow.md</code>)</p>
<ul><li>Daily TDD workflow (morning routine, core cycle, end of day)</li><li>Project setup for TDD (frameworks, configuration, IDE setup)</li><li>Feature development step-by-step guide</li><li>Debugging workflow when tests fail</li><li>Refactoring workflow with TDD safety net</li><li>Code review checklist for TDD</li><li>Common scenarios (new feature, bug fix, validation, legacy code, external dependencies)</li></ul>
<h3>Usage</h3>
<p><strong>Start a TDD session</strong>:</p>
<pre><code class="lang-bash">cd skills/engineering/test-driven-development/resources
./scripts/tdd_session.py start</code></pre>
<p><strong>Generate test template for new feature</strong>:</p>
<pre><code class="lang-bash">./scripts/generate_test_template.sh python UserAuthentication --framework pytest --style bdd</code></pre>
<p><strong>Check TDD health</strong>:</p>
<pre><code class="lang-bash">./scripts/analyze_tdd_metrics.py health \
--source-dir ../../../src \
--test-dir ../../../tests \
--coverage-file ../../../.coverage</code></pre>
<p><strong>Study examples</strong>:</p>
<pre><code class="lang-bash"># Python example with full TDD progression
cat examples/python/tdd_example.py
# TypeScript kata
cat examples/typescript/tdd_example.test.ts
# Rust with type system
cat examples/rust/tdd_example.rs
# Complete workflow guide
cat examples/workflows/tdd-workflow.md</code></pre>
<hr>
<h2>Related Skills</h2>
<ul><li><strong>engineering-code-review</strong>: Reviewing tests in PRs</li><li><strong>engineering-refactoring-patterns</strong>: Refactoring with test safety net</li><li><strong>engineering-code-quality</strong>: Tests improve code quality</li><li><strong>engineering-continuous-integration</strong>: Automating test execution</li><li><strong>engineering-design-patterns</strong>: Testing pattern implementations</li></ul>
<hr>
<h2>References</h2>
<ul><li><a href="https://www.amazon.com/Test-Driven-Development-Kent-Beck/dp/0321146530">Test Driven Development by Kent Beck</a></li><li><a href="https://www.amazon.com/Growing-Object-Oriented-Software-Guided-Tests/dp/0321503627">Growing Object-Oriented Software, Guided by Tests</a></li><li><a href="https://docs.pytest.org/">Pytest Documentation</a></li><li><a href="https://jestjs.io/">Jest Documentation</a></li><li><a href="https://pkg.go.dev/testing">Go Testing Package</a></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="/engineering-test-driven-development.md">This page as plain text</a> · <a href="/llms.txt">Index for agents</a></div>
</footer>
</div></body></html>