mirror of
https://github.com/hanzoai/skills.git
synced 2026-11-19 00:47:36 +00:00
hanzoskills.com/llms.txt now opens with the install line, the API reference index and the company index, so an agent that lands on any one of the three can find the rest. robots.txt claimed 537 documents while llms.txt counts 920. The number is gone from robots.txt; llms.txt derives it. public/ is regenerated from scripts/site.py, which it had fallen behind: the copy-prompt menu and agent bar were in the generator and not in the committed pages. tests/site.mjs passes against the result. Co-authored-by: Hanzo Dev <[email protected]>
793 lines
37 KiB
HTML
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="alternate" type="text/markdown" href="/engineering-test-driven-development.md">
|
|
|
|
<link rel="icon" href="/favicon.svg">
|
|
<link rel="canonical" href="https://hanzoskills.com/engineering-test-driven-development">
|
|
</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't write production code without a failing test</li><li>Don't write more test than sufficient to fail</li><li>Don'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'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="[email protected]", password="secret123")
|
|
user.save()
|
|
|
|
# Act: Execute the action being tested
|
|
result = authenticate(email="[email protected]", password="secret123")
|
|
|
|
# Assert: Verify the result
|
|
assert result.success is True
|
|
assert result.user.email == "[email protected]"</code></pre>
|
|
<p><strong>Given-When-Then</strong> (BDD style):</p>
|
|
<pre><code class="lang-typescript">describe("User Login", () => {
|
|
it("should authenticate user with correct credentials", () => {
|
|
// Given: A registered user
|
|
const user = createUser({ email: "[email protected]", password: "secret" });
|
|
|
|
// When: User attempts to login
|
|
const result = authenticate("[email protected]", "secret");
|
|
|
|
// Then: Authentication succeeds
|
|
expect(result.success).toBe(true);
|
|
expect(result.user.email).toBe("[email protected]");
|
|
});
|
|
});</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="[email protected]",
|
|
subject="Welcome!",
|
|
body="Welcome to our app!"
|
|
)</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) -> 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) -> float:
|
|
if amount < 0:
|
|
raise ValueError("Amount cannot be negative")
|
|
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({"email": email})
|
|
email_service.send(user.email, "Welcome!")
|
|
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="[email protected]")
|
|
|
|
service = UserService(db=mock_db, email_service=mock_email)
|
|
user = service.create_user("[email protected]")
|
|
|
|
# Verify interactions
|
|
mock_db.save.assert_called_once_with({"email": "[email protected]"})
|
|
mock_email.send.assert_called_once_with("[email protected]", "Welcome!")
|
|
assert user.email == "[email protected]"
|
|
|
|
# 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({"email": email})
|
|
self.email_service.send(user.email, "Welcome!")
|
|
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
|
|
}{
|
|
{"Premium user, large purchase", 1000, "premium", 200},
|
|
{"Premium user, small purchase", 50, "premium", 5},
|
|
{"Regular user, large purchase", 1000, "regular", 100},
|
|
{"Regular user, small purchase", 50, "regular", 0},
|
|
{"Guest user", 1000, "guest", 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("CalculateDiscount(%v, %v) = %v, want %v",
|
|
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 = "123"
|
|
mock_api = AsyncMock()
|
|
mock_api.get_user.return_value = {"id": "123", "name": "John"}
|
|
|
|
service = UserService(api=mock_api)
|
|
|
|
# Act
|
|
user = await service.fetch_user_data(user_id)
|
|
|
|
# Assert
|
|
assert user["name"] == "John"
|
|
mock_api.get_user.assert_called_once_with(user_id)</code></pre>
|
|
<p><strong>TypeScript (Promises)</strong>:</p>
|
|
<pre><code class="lang-typescript">describe("fetchUserData", () => {
|
|
it("should fetch user from API", async () => {
|
|
// Arrange
|
|
const mockApi = {
|
|
getUser: jest.fn().mockResolvedValue({ id: "123", name: "John" }),
|
|
};
|
|
const service = new UserService(mockApi);
|
|
|
|
// Act
|
|
const user = await service.fetchUserData("123");
|
|
|
|
// Assert
|
|
expect(user.name).toBe("John");
|
|
expect(mockApi.getUser).toHaveBeenCalledWith("123");
|
|
});
|
|
});</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="invalid-email")
|
|
|
|
assert "Invalid email format" in str(exc_info.value)
|
|
|
|
def test_user_not_found():
|
|
result = find_user(user_id="nonexistent")
|
|
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("input,expected", [
|
|
("hello", "HELLO"),
|
|
("WORLD", "WORLD"),
|
|
("TeSt", "TEST"),
|
|
("", ""),
|
|
])
|
|
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],
|
|
])("add(%i, %i) should return %i", (a, b, expected) => {
|
|
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():
|
|
"""Create a test user for multiple tests"""
|
|
return User(email="[email protected]", name="Test User")
|
|
|
|
@pytest.fixture
|
|
def database():
|
|
"""Set up and tear down test database"""
|
|
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("[email protected]")
|
|
assert found.name == "Test User"</code></pre>
|
|
<p><strong>TypeScript (Jest)</strong>:</p>
|
|
<pre><code class="lang-typescript">describe("UserService", () => {
|
|
let service: UserService;
|
|
let mockDb: Database;
|
|
|
|
beforeEach(() => {
|
|
mockDb = createMockDatabase();
|
|
service = new UserService(mockDb);
|
|
});
|
|
|
|
afterEach(() => {
|
|
mockDb.clear();
|
|
});
|
|
|
|
it("should save user", () => {
|
|
const user = { email: "[email protected]" };
|
|
service.save(user);
|
|
expect(mockDb.count()).toBe(1);
|
|
});
|
|
});</code></pre>
|
|
<hr>
|
|
<h3>Pattern 8: Testing Private Methods (Don't!)</h3>
|
|
<p><strong>Bad Approach</strong>:</p>
|
|
<pre><code class="lang-python"># DON'T: Testing private methods directly
|
|
def test_private_validation():
|
|
obj = MyClass()
|
|
assert obj._validate_input("test") 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("test") # Public method
|
|
assert result.success is True # Private validation tested indirectly
|
|
|
|
def test_public_method_with_invalid_input():
|
|
obj = MyClass()
|
|
result = obj.process("") # 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("") == 0
|
|
|
|
def string_calculator(numbers):
|
|
return 0 # Minimal code to pass
|
|
|
|
# Iteration 2: Single number
|
|
def test_single_number():
|
|
assert string_calculator("5") == 5
|
|
|
|
def string_calculator(numbers):
|
|
if not numbers:
|
|
return 0
|
|
return int(numbers)
|
|
|
|
# Iteration 3: Two numbers
|
|
def test_two_numbers():
|
|
assert string_calculator("1,2") == 3
|
|
|
|
def string_calculator(numbers):
|
|
if not numbers:
|
|
return 0
|
|
return sum(int(n) for n in numbers.split(","))
|
|
|
|
# Iteration 4: Multiple numbers
|
|
def test_multiple_numbers():
|
|
assert string_calculator("1,2,3,4") == 10
|
|
# Already passes with current implementation!
|
|
|
|
# Iteration 5: New line delimiter
|
|
def test_newline_delimiter():
|
|
assert string_calculator("1\n2,3") == 6
|
|
|
|
def string_calculator(numbers):
|
|
if not numbers:
|
|
return 0
|
|
numbers = numbers.replace("\n", ",")
|
|
return sum(int(n) for n in numbers.split(","))
|
|
|
|
# Iteration 6: Negative numbers throw exception
|
|
def test_negative_numbers_throw():
|
|
with pytest.raises(ValueError, match="Negatives not allowed: -2, -5"):
|
|
string_calculator("1,-2,3,-5")
|
|
|
|
def string_calculator(numbers):
|
|
if not numbers:
|
|
return 0
|
|
numbers = numbers.replace("\n", ",")
|
|
nums = [int(n) for n in numbers.split(",")]
|
|
|
|
negatives = [n for n in nums if n < 0]
|
|
if negatives:
|
|
raise ValueError(f"Negatives not allowed: {', '.join(map(str, negatives))}")
|
|
|
|
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("/users", json={
|
|
"email": "[email protected]",
|
|
"name": "Test User"
|
|
})
|
|
|
|
assert response.status_code == 201
|
|
assert response.json["email"] == "[email protected]"
|
|
assert "id" in response.json
|
|
|
|
# GREEN: Implement minimal endpoint
|
|
@app.post("/users")
|
|
def create_user(request):
|
|
data = request.json
|
|
user = User(email=data["email"], name=data["name"])
|
|
db.save(user)
|
|
return {"id": user.id, "email": user.email}, 201
|
|
|
|
# RED: Test validation
|
|
def test_create_user_invalid_email(client):
|
|
response = client.post("/users", json={
|
|
"email": "invalid-email",
|
|
"name": "Test"
|
|
})
|
|
|
|
assert response.status_code == 400
|
|
assert "Invalid email" in response.json["error"]
|
|
|
|
# GREEN: Add validation
|
|
@app.post("/users")
|
|
def create_user(request):
|
|
data = request.json
|
|
|
|
if not is_valid_email(data["email"]):
|
|
return {"error": "Invalid email format"}, 400
|
|
|
|
user = User(email=data["email"], name=data["name"])
|
|
db.save(user)
|
|
return {"id": user.id, "email": user.email}, 201</code></pre>
|
|
<hr>
|
|
<h2>Best Practices</h2>
|
|
<h3>TDD Guidelines</h3>
|
|
<p><strong>Do'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'ts</strong>:</p>
|
|
<ul><li>Don't skip the refactor step</li><li>Don't test private methods</li><li>Don't write tests after implementation (that's not TDD!)</li><li>Don't make tests depend on each other</li><li>Don't test framework code</li><li>Don'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 & 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('./module')</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's type system</li><li>Demonstrates Result<T, E> 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> |