my-opencode 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +163 -0
- package/agents/architect.md +30 -0
- package/agents/code-reviewer.md +29 -0
- package/agents/executor.md +30 -0
- package/agents/fullstack-dev.md +53 -0
- package/agents/spec-writer.md +37 -0
- package/agents/team-lead.md +60 -0
- package/agents/tech-writer.md +30 -0
- package/agents/test-engineer.md +30 -0
- package/agents/verifier.md +33 -0
- package/bin/cli.js +272 -0
- package/opencode.json +164 -0
- package/package.json +44 -0
- package/skills/adr/SKILL.md +91 -0
- package/skills/adr/references/templates.md +100 -0
- package/skills/adr/scripts/README.md +5 -0
- package/skills/dev-flow/SKILL.md +188 -0
- package/skills/dev-flow/references/code-phase.md +72 -0
- package/skills/dev-flow/references/contract-phase.md +81 -0
- package/skills/dev-flow/references/verify-phase.md +129 -0
- package/skills/dev-flow/scripts/README.md +3 -0
- package/skills/docs-gen/SKILL.md +162 -0
- package/skills/docs-gen/references/doc-styles.md +216 -0
- package/skills/docs-gen/scripts/README.md +5 -0
- package/skills/orchestrate/SKILL.md +112 -0
- package/skills/orchestrate/references/orchestration-patterns.md +56 -0
- package/skills/pr-review/SKILL.md +110 -0
- package/skills/pr-review/references/review-dimensions.md +117 -0
- package/skills/pr-review/references/security-checklist.md +122 -0
- package/skills/pr-review/scripts/README.md +5 -0
- package/skills/test-gen/SKILL.md +143 -0
- package/skills/test-gen/references/framework-detection.md +105 -0
- package/skills/test-gen/references/test-patterns.md +260 -0
- package/skills/test-gen/scripts/README.md +5 -0
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
# Security Checklist — Language-Specific Patterns
|
|
2
|
+
|
|
3
|
+
## TypeScript / JavaScript
|
|
4
|
+
|
|
5
|
+
### Injection
|
|
6
|
+
```
|
|
7
|
+
// ❌ DANGEROUS
|
|
8
|
+
eval(userInput)
|
|
9
|
+
innerHTML = userInput
|
|
10
|
+
new Function(userInput)
|
|
11
|
+
require(`./${userInput}`)
|
|
12
|
+
child_process.exec(`command ${userInput}`)
|
|
13
|
+
|
|
14
|
+
// ✅ SAFE
|
|
15
|
+
textContent = userInput
|
|
16
|
+
child_process.execFile('command', [userInput])
|
|
17
|
+
DOMPurify.sanitize(userInput)
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
### SQL
|
|
21
|
+
```
|
|
22
|
+
// ❌ DANGEROUS
|
|
23
|
+
`SELECT * FROM users WHERE id = ${userId}`
|
|
24
|
+
|
|
25
|
+
// ✅ SAFE
|
|
26
|
+
db.query('SELECT * FROM users WHERE id = ?', [userId])
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
### Auth
|
|
30
|
+
- [ ] JWT verified with proper library (jsonwebtoken.verify)
|
|
31
|
+
- [ ] No hardcoded tokens or API keys
|
|
32
|
+
- [ ] Rate limiting on auth endpoints
|
|
33
|
+
|
|
34
|
+
---
|
|
35
|
+
|
|
36
|
+
## Python
|
|
37
|
+
|
|
38
|
+
### Injection
|
|
39
|
+
```python
|
|
40
|
+
# ❌ DANGEROUS
|
|
41
|
+
os.system(f"command {user_input}")
|
|
42
|
+
subprocess.run(f"command {user_input}", shell=True)
|
|
43
|
+
eval(user_input)
|
|
44
|
+
|
|
45
|
+
# ✅ SAFE
|
|
46
|
+
subprocess.run(["command", user_input])
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
### SQL
|
|
50
|
+
```python
|
|
51
|
+
# ❌ DANGEROUS
|
|
52
|
+
cursor.execute(f"SELECT * FROM users WHERE id = {user_id}")
|
|
53
|
+
|
|
54
|
+
# ✅ SAFE
|
|
55
|
+
cursor.execute("SELECT * FROM users WHERE id = ?", (user_id,))
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
### Pickle
|
|
59
|
+
```python
|
|
60
|
+
# ❌ DANGEROUS (arbitrary code execution)
|
|
61
|
+
data = pickle.loads(untrusted_input)
|
|
62
|
+
|
|
63
|
+
# ✅ SAFE
|
|
64
|
+
data = json.loads(untrusted_input)
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
---
|
|
68
|
+
|
|
69
|
+
## Go
|
|
70
|
+
|
|
71
|
+
### Injection
|
|
72
|
+
```go
|
|
73
|
+
// ❌ DANGEROUS
|
|
74
|
+
cmd := exec.Command("bash", "-c", userInput)
|
|
75
|
+
|
|
76
|
+
// ✅ SAFE
|
|
77
|
+
cmd := exec.Command("command", userInput)
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
### SQL
|
|
81
|
+
```go
|
|
82
|
+
// ❌ DANGEROUS
|
|
83
|
+
db.Query(fmt.Sprintf("SELECT * FROM users WHERE id = %s", userID))
|
|
84
|
+
|
|
85
|
+
// ✅ SAFE
|
|
86
|
+
db.Query("SELECT * FROM users WHERE id = ?", userID)
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
---
|
|
90
|
+
|
|
91
|
+
## Rust
|
|
92
|
+
|
|
93
|
+
### Unsafe
|
|
94
|
+
```rust
|
|
95
|
+
// ❌ DANGEROUS - verify necessity and safety invariants
|
|
96
|
+
unsafe { ... }
|
|
97
|
+
|
|
98
|
+
// ✅ SAFE - prefer safe abstractions
|
|
99
|
+
safe_api()
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
### Injection
|
|
103
|
+
```rust
|
|
104
|
+
// ❌ DANGEROUS
|
|
105
|
+
Command::new("sh").arg("-c").arg(user_input)
|
|
106
|
+
|
|
107
|
+
// ✅ SAFE
|
|
108
|
+
Command::new("command").arg(user_input)
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
---
|
|
112
|
+
|
|
113
|
+
## General Security Rules
|
|
114
|
+
|
|
115
|
+
1. **Never trust input** — validate type, range, format, length
|
|
116
|
+
2. **Least privilege** — minimal permissions, minimal scope
|
|
117
|
+
3. **Defense in depth** — don't rely on a single security measure
|
|
118
|
+
4. **Fail securely** — errors should default to denied/closed
|
|
119
|
+
5. **No secrets in code** — use env vars, secret managers, or vaults
|
|
120
|
+
6. **Log securely** — no secrets in logs, no user data in error messages
|
|
121
|
+
7. **Dependencies** — check for known CVEs, prefer maintained libraries
|
|
122
|
+
8. **Cryptography** — use established libraries, don't roll your own
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: test-gen
|
|
3
|
+
description: |
|
|
4
|
+
Analyze source code and generate meaningful tests — unit, integration, and E2E.
|
|
5
|
+
Detects project test framework, conventions, and existing test patterns automatically.
|
|
6
|
+
Use PROACTIVELY when asked to "add tests", "write tests", "test this", "cover with tests", "increase coverage".
|
|
7
|
+
Triggers on: "test", "coverage", "unit test", "integration test", "spec"
|
|
8
|
+
---
|
|
9
|
+
|
|
10
|
+
# Test Generation
|
|
11
|
+
|
|
12
|
+
Analyze source code, detect test framework, and generate meaningful tests following project conventions.
|
|
13
|
+
|
|
14
|
+
## When to Use
|
|
15
|
+
|
|
16
|
+
- Adding tests for new code
|
|
17
|
+
- Backfilling tests for existing code
|
|
18
|
+
- Converting manual test plans to automated tests
|
|
19
|
+
- Increasing test coverage in specific modules
|
|
20
|
+
|
|
21
|
+
## Workflow
|
|
22
|
+
|
|
23
|
+
```
|
|
24
|
+
Code Input → Framework Detection → Pattern Analysis → Test Generation → Verification
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
### Step 1: Framework Detection
|
|
28
|
+
|
|
29
|
+
Determine the test framework and runner:
|
|
30
|
+
|
|
31
|
+
#### Node.js (check `package.json` devDependencies)
|
|
32
|
+
| Detected | Framework | Runner |
|
|
33
|
+
|----------|-----------|--------|
|
|
34
|
+
| vitest | Vitest | `vitest` |
|
|
35
|
+
| jest | Jest | `jest` |
|
|
36
|
+
| mocha + chai | Mocha | `mocha` |
|
|
37
|
+
| ava | Ava | `ava` |
|
|
38
|
+
|
|
39
|
+
#### Python (check `pyproject.toml`, `requirements*.txt`, or installed tools)
|
|
40
|
+
| Detected | Framework | Runner |
|
|
41
|
+
|----------|-----------|--------|
|
|
42
|
+
| pytest | Pytest | `pytest` |
|
|
43
|
+
| unittest | unittest | `python -m unittest` |
|
|
44
|
+
|
|
45
|
+
#### Rust (check `Cargo.toml`)
|
|
46
|
+
| Detected | Framework | Runner |
|
|
47
|
+
|----------|-----------|--------|
|
|
48
|
+
| cargo | built-in test | `cargo test` |
|
|
49
|
+
|
|
50
|
+
#### Go
|
|
51
|
+
| Detected | Framework | Runner |
|
|
52
|
+
|----------|-----------|--------|
|
|
53
|
+
| testing | built-in test | `go test` |
|
|
54
|
+
|
|
55
|
+
If unclear, check for `test/` or `__tests__` directories, `*.test.*` or `*.spec.*` files, and examine one existing test to infer conventions.
|
|
56
|
+
|
|
57
|
+
See `references/framework-detection.md` for detailed detection logic.
|
|
58
|
+
|
|
59
|
+
### Step 2: Pattern Analysis
|
|
60
|
+
|
|
61
|
+
Read 2-3 existing tests in the project to understand:
|
|
62
|
+
|
|
63
|
+
- **File naming:** `*.test.ts`, `*.spec.ts`, `test_*.py`?
|
|
64
|
+
- **Directory structure:** co-located or `tests/` directory?
|
|
65
|
+
- **Setup patterns:** `beforeEach`/`setup_method`? Fixtures? Factories?
|
|
66
|
+
- **Mocking style:** jest.mock, unittest.mock, monkeypatch, dependency injection?
|
|
67
|
+
- **Assertion style:** `expect().toBe()`, `assertEqual`, `assert!`?
|
|
68
|
+
- **Naming conventions:** `describe/it`, `def test_`, `func Test`?
|
|
69
|
+
|
|
70
|
+
### Step 3: Test Generation
|
|
71
|
+
|
|
72
|
+
For each unit/module under test:
|
|
73
|
+
|
|
74
|
+
#### Unit Tests
|
|
75
|
+
- Happy path — expected inputs produce expected outputs
|
|
76
|
+
- Edge cases — empty, null, boundary values
|
|
77
|
+
- Error paths — invalid input, failure modes, exceptions
|
|
78
|
+
- State transitions — if applicable
|
|
79
|
+
- Focus on public API, not implementation details
|
|
80
|
+
|
|
81
|
+
#### Integration Tests (when applicable)
|
|
82
|
+
- Module interactions
|
|
83
|
+
- Database/file system round-trips
|
|
84
|
+
- API endpoint behavior
|
|
85
|
+
|
|
86
|
+
#### Test Structure Template
|
|
87
|
+
```typescript
|
|
88
|
+
describe('Module/Function', () => {
|
|
89
|
+
beforeEach(() => {
|
|
90
|
+
// setup
|
|
91
|
+
})
|
|
92
|
+
|
|
93
|
+
it('should handle happy path', () => {
|
|
94
|
+
// arrange
|
|
95
|
+
// act
|
|
96
|
+
// assert
|
|
97
|
+
})
|
|
98
|
+
|
|
99
|
+
it('should handle edge case: <description>', () => {
|
|
100
|
+
// ...
|
|
101
|
+
})
|
|
102
|
+
|
|
103
|
+
it('should handle error: <description>', () => {
|
|
104
|
+
// ...
|
|
105
|
+
})
|
|
106
|
+
})
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
### Step 4: Verification
|
|
110
|
+
|
|
111
|
+
Run the generated tests to confirm they pass:
|
|
112
|
+
|
|
113
|
+
```bash
|
|
114
|
+
# Framework detected in step 1
|
|
115
|
+
npm test -- --run # vitest
|
|
116
|
+
npx jest # jest
|
|
117
|
+
pytest -v # pytest
|
|
118
|
+
python -m unittest -v # unittest
|
|
119
|
+
cargo test # Rust
|
|
120
|
+
go test ./... # Go
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
## Test Quality Guidelines
|
|
124
|
+
|
|
125
|
+
| Quality | Criteria |
|
|
126
|
+
|---------|----------|
|
|
127
|
+
| ✅ Great | Tests behavior, covers edge cases, deterministic, fast |
|
|
128
|
+
| ⚠️ Adequate | Tests happy path only, some duplication |
|
|
129
|
+
| ❌ Poor | Tests implementation, brittle, flaky, no assertions |
|
|
130
|
+
|
|
131
|
+
## Anti-Patterns
|
|
132
|
+
|
|
133
|
+
- ❌ Testing implementation details (private methods, internal state)
|
|
134
|
+
- ❌ Snapshot testing without review (giant snapshots)
|
|
135
|
+
- ❌ Mocking everything (tests lose meaning)
|
|
136
|
+
- ❌ Flaky tests (time, random, network dependencies)
|
|
137
|
+
- ❌ No assertions (tests that can't fail)
|
|
138
|
+
- ❌ Copy-paste test patterns without adapting to context
|
|
139
|
+
|
|
140
|
+
## Related Skills
|
|
141
|
+
|
|
142
|
+
- `dev-flow` — Verify phase runs generated tests
|
|
143
|
+
- `pr-review` — Reviews test quality as part of code review
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
# Framework Detection — Detailed Reference
|
|
2
|
+
|
|
3
|
+
## Detection Order
|
|
4
|
+
|
|
5
|
+
1. Check project config files
|
|
6
|
+
2. Check for test directories (`test/`, `__tests__/`, `spec/`)
|
|
7
|
+
3. Check for existing test files (`*.test.*`, `*.spec.*`, `test_*`)
|
|
8
|
+
4. Read one existing test to confirm conventions
|
|
9
|
+
|
|
10
|
+
---
|
|
11
|
+
|
|
12
|
+
## Node.js / TypeScript
|
|
13
|
+
|
|
14
|
+
### Detection by config file
|
|
15
|
+
|
|
16
|
+
Look in `package.json` `devDependencies` and `scripts`:
|
|
17
|
+
|
|
18
|
+
| Pattern | Framework | Test Command |
|
|
19
|
+
|---------|-----------|-------------|
|
|
20
|
+
| `"vitest"` in devDeps | Vitest | `npm run test` or `npx vitest` |
|
|
21
|
+
| `"jest"` in devDeps | Jest | `npx jest` |
|
|
22
|
+
| `"mocha"` + `"chai"` in devDeps | Mocha + Chai | `npx mocha` |
|
|
23
|
+
| `"ava"` in devDeps | AVA | `npx ava` |
|
|
24
|
+
| `"test": "vitest"` in scripts | Vitest | `npm test` |
|
|
25
|
+
| `"test": "jest"` in scripts | Jest | `npm test` |
|
|
26
|
+
|
|
27
|
+
### Vitest specifics
|
|
28
|
+
- Config: `vitest.config.ts` or `vite.config.ts` with `test` block
|
|
29
|
+
- File patterns: `*.test.ts`, `*.spec.ts`, `**/__tests__/*.ts`
|
|
30
|
+
- Globals: `describe`, `it`, `expect`, `beforeEach` available without import
|
|
31
|
+
- `vi.mock()` for mocking
|
|
32
|
+
- Run: `npx vitest run` (single run) or `npx vitest` (watch)
|
|
33
|
+
|
|
34
|
+
### Jest specifics
|
|
35
|
+
- Config: `jest.config.ts` or `jest.config.js`
|
|
36
|
+
- File patterns: `*.test.ts`, `*.spec.ts`, `**/__tests__/*.ts`
|
|
37
|
+
- `jest.mock()` for mocking
|
|
38
|
+
- Run: `npx jest`
|
|
39
|
+
|
|
40
|
+
### File naming conventions
|
|
41
|
+
|
|
42
|
+
| Convention | Example | Framework |
|
|
43
|
+
|------------|---------|-----------|
|
|
44
|
+
| Co-located `.test.ts` | `user.ts` → `user.test.ts` | Vitest, Jest |
|
|
45
|
+
| Co-located `.spec.ts` | `user.ts` → `user.spec.ts` | Vitest, Jest |
|
|
46
|
+
| `__tests__/` dir | `__tests__/user.test.ts` | Jest |
|
|
47
|
+
| `test/` dir mirrored | `test/user.test.ts` | Mocha |
|
|
48
|
+
|
|
49
|
+
---
|
|
50
|
+
|
|
51
|
+
## Python
|
|
52
|
+
|
|
53
|
+
### Detection by config file
|
|
54
|
+
|
|
55
|
+
| File | Framework |
|
|
56
|
+
|------|-----------|
|
|
57
|
+
| `pyproject.toml` with `[tool.pytest]` | pytest |
|
|
58
|
+
| `pytest.ini` | pytest |
|
|
59
|
+
| `setup.cfg` with `[tool:pytest]` | pytest |
|
|
60
|
+
|
|
61
|
+
### Pytest specifics
|
|
62
|
+
- File patterns: `test_*.py`, `*_test.py`
|
|
63
|
+
- Function patterns: `def test_<name>()`
|
|
64
|
+
- Class patterns: `class Test<Name>` with `def test_<name>()`
|
|
65
|
+
- Fixtures: `@pytest.fixture`, conftest.py
|
|
66
|
+
- Parametrize: `@pytest.mark.parametrize`
|
|
67
|
+
- Mock: `unittest.mock` or `pytest-mock` (`mocker` fixture)
|
|
68
|
+
- Run: `pytest -v`, `pytest -v test_file.py`
|
|
69
|
+
|
|
70
|
+
### Unittest specifics
|
|
71
|
+
- File patterns: `test_*.py`
|
|
72
|
+
- Class: `class Test<Name>(unittest.TestCase)`
|
|
73
|
+
- Setup: `setUp()` / `setUpClass()`
|
|
74
|
+
- Assert: `self.assertEqual()`, `self.assertTrue()`, etc.
|
|
75
|
+
- Mock: `@unittest.mock.patch()`
|
|
76
|
+
- Run: `python -m unittest -v`
|
|
77
|
+
|
|
78
|
+
### File naming conventions
|
|
79
|
+
| Convention | Example |
|
|
80
|
+
|------------|---------|
|
|
81
|
+
| `tests/` dir | `tests/test_user.py` |
|
|
82
|
+
| Co-located | `user.py` → `test_user.py` (next to it) |
|
|
83
|
+
|
|
84
|
+
---
|
|
85
|
+
|
|
86
|
+
## Rust
|
|
87
|
+
|
|
88
|
+
### Built-in test framework
|
|
89
|
+
- Attribute: `#[test]` on functions
|
|
90
|
+
- File location: tests live in `tests/` (integration) or inside source files (unit)
|
|
91
|
+
- Unit tests: `#[cfg(test)] mod tests { ... }` at bottom of source file
|
|
92
|
+
- Integration tests: `tests/<name>.rs` files
|
|
93
|
+
- Assert: `assert!()`, `assert_eq!()`, `assert_ne!()`
|
|
94
|
+
- Run: `cargo test`, `cargo test <test_name>`
|
|
95
|
+
|
|
96
|
+
---
|
|
97
|
+
|
|
98
|
+
## Go
|
|
99
|
+
|
|
100
|
+
### Built-in test framework
|
|
101
|
+
- File patterns: `*_test.go`
|
|
102
|
+
- Function: `func Test<Name>(t *testing.T)`
|
|
103
|
+
- Table-driven tests common: `tests := []struct{ ... }`
|
|
104
|
+
- Assert: `t.Errorf()`, `t.Fatal()`, or `require`/`assert` from testify
|
|
105
|
+
- Run: `go test ./...`, `go test -v ./...`
|
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
# Test Patterns — Language & Framework Specific
|
|
2
|
+
|
|
3
|
+
## TypeScript / JavaScript — Vitest
|
|
4
|
+
|
|
5
|
+
### Basic structure
|
|
6
|
+
```typescript
|
|
7
|
+
import { describe, it, expect, beforeEach, vi } from 'vitest'
|
|
8
|
+
import { userService } from './userService'
|
|
9
|
+
|
|
10
|
+
describe('userService', () => {
|
|
11
|
+
beforeEach(() => {
|
|
12
|
+
vi.restoreAllMocks()
|
|
13
|
+
})
|
|
14
|
+
|
|
15
|
+
it('should create a user with valid data', async () => {
|
|
16
|
+
const user = await userService.create({ name: 'Alice', email: 'alice@test.com' })
|
|
17
|
+
expect(user).toMatchObject({ name: 'Alice' })
|
|
18
|
+
expect(user.id).toBeDefined()
|
|
19
|
+
})
|
|
20
|
+
|
|
21
|
+
it('should reject duplicate emails', async () => {
|
|
22
|
+
await userService.create({ name: 'Alice', email: 'dup@test.com' })
|
|
23
|
+
await expect(userService.create({ name: 'Bob', email: 'dup@test.com' }))
|
|
24
|
+
.rejects.toThrow('Email already exists')
|
|
25
|
+
})
|
|
26
|
+
|
|
27
|
+
it('should handle empty name', async () => {
|
|
28
|
+
await expect(userService.create({ name: '', email: 'x@test.com' }))
|
|
29
|
+
.rejects.toThrow('Name is required')
|
|
30
|
+
})
|
|
31
|
+
})
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
### Mocking external dependencies
|
|
35
|
+
```typescript
|
|
36
|
+
import { describe, it, expect, vi } from 'vitest'
|
|
37
|
+
import { sendEmail } from './emailService'
|
|
38
|
+
import { emailClient } from './emailClient'
|
|
39
|
+
|
|
40
|
+
vi.mock('./emailClient')
|
|
41
|
+
|
|
42
|
+
it('should send welcome email', async () => {
|
|
43
|
+
vi.mocked(emailClient.send).mockResolvedValue({ id: 'msg_123' })
|
|
44
|
+
const result = await sendEmail('user@test.com', 'Welcome!')
|
|
45
|
+
expect(result.success).toBe(true)
|
|
46
|
+
expect(emailClient.send).toHaveBeenCalledWith(
|
|
47
|
+
expect.objectContaining({ to: 'user@test.com' })
|
|
48
|
+
)
|
|
49
|
+
})
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
### Parametrized tests
|
|
53
|
+
```typescript
|
|
54
|
+
it.each([
|
|
55
|
+
{ input: '', expected: false },
|
|
56
|
+
{ input: 'a@b', expected: true },
|
|
57
|
+
{ input: '@b.com', expected: false },
|
|
58
|
+
])('should validate email: $input', ({ input, expected }) => {
|
|
59
|
+
expect(validateEmail(input)).toBe(expected)
|
|
60
|
+
})
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
---
|
|
64
|
+
|
|
65
|
+
## TypeScript / JavaScript — Jest
|
|
66
|
+
|
|
67
|
+
Same patterns as Vitest with these differences:
|
|
68
|
+
- `jest.mock()` instead of `vi.mock()`
|
|
69
|
+
- `jest.fn()` instead of `vi.fn()`
|
|
70
|
+
- No built-in `it.each` (use `test.each` or `it.each` from `@jest/globals`)
|
|
71
|
+
|
|
72
|
+
```typescript
|
|
73
|
+
jest.mock('./emailClient')
|
|
74
|
+
jest.spyOn(console, 'error').mockImplementation(() => {})
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
---
|
|
78
|
+
|
|
79
|
+
## Python — Pytest
|
|
80
|
+
|
|
81
|
+
### Basic structure
|
|
82
|
+
```python
|
|
83
|
+
import pytest
|
|
84
|
+
from user_service import create_user
|
|
85
|
+
|
|
86
|
+
def test_create_user_with_valid_data():
|
|
87
|
+
user = create_user(name="Alice", email="alice@test.com")
|
|
88
|
+
assert user.name == "Alice"
|
|
89
|
+
assert user.id is not None
|
|
90
|
+
|
|
91
|
+
def test_reject_duplicate_emails():
|
|
92
|
+
create_user(name="Alice", email="dup@test.com")
|
|
93
|
+
with pytest.raises(ValueError, match="Email already exists"):
|
|
94
|
+
create_user(name="Bob", email="dup@test.com")
|
|
95
|
+
|
|
96
|
+
def test_handle_empty_name():
|
|
97
|
+
with pytest.raises(ValueError, match="Name is required"):
|
|
98
|
+
create_user(name="", email="x@test.com")
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
### Fixtures
|
|
102
|
+
```python
|
|
103
|
+
@pytest.fixture
|
|
104
|
+
def db_session():
|
|
105
|
+
session = create_test_session()
|
|
106
|
+
yield session
|
|
107
|
+
session.close()
|
|
108
|
+
|
|
109
|
+
def test_user_query(db_session):
|
|
110
|
+
users = db_session.query(User).all()
|
|
111
|
+
assert len(users) > 0
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
### Parametrize
|
|
115
|
+
```python
|
|
116
|
+
@pytest.mark.parametrize("email,expected", [
|
|
117
|
+
("", False),
|
|
118
|
+
("a@b", True),
|
|
119
|
+
("@b.com", False),
|
|
120
|
+
])
|
|
121
|
+
def test_email_validation(email, expected):
|
|
122
|
+
assert validate_email(email) == expected
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
### Mocking with mocker (pytest-mock)
|
|
126
|
+
```python
|
|
127
|
+
def test_send_email(mocker):
|
|
128
|
+
mock_client = mocker.patch("email_service.email_client.send")
|
|
129
|
+
mock_client.return_value = {"id": "msg_123"}
|
|
130
|
+
result = send_email("user@test.com", "Welcome!")
|
|
131
|
+
assert result["success"] is True
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
---
|
|
135
|
+
|
|
136
|
+
## Python — unittest
|
|
137
|
+
|
|
138
|
+
```python
|
|
139
|
+
import unittest
|
|
140
|
+
from unittest.mock import patch
|
|
141
|
+
from user_service import create_user
|
|
142
|
+
|
|
143
|
+
class TestUserService(unittest.TestCase):
|
|
144
|
+
def test_create_user_valid(self):
|
|
145
|
+
user = create_user(name="Alice", email="alice@test.com")
|
|
146
|
+
self.assertEqual(user.name, "Alice")
|
|
147
|
+
self.assertIsNotNone(user.id)
|
|
148
|
+
|
|
149
|
+
def test_reject_duplicate(self):
|
|
150
|
+
create_user(name="Alice", email="dup@test.com")
|
|
151
|
+
with self.assertRaises(ValueError):
|
|
152
|
+
create_user(name="Bob", email="dup@test.com")
|
|
153
|
+
|
|
154
|
+
@patch("email_service.email_client.send")
|
|
155
|
+
def test_send_email(self, mock_send):
|
|
156
|
+
mock_send.return_value = {"id": "msg_123"}
|
|
157
|
+
result = send_email("user@test.com", "Welcome!")
|
|
158
|
+
self.assertTrue(result["success"])
|
|
159
|
+
|
|
160
|
+
if __name__ == "__main__":
|
|
161
|
+
unittest.main()
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
---
|
|
165
|
+
|
|
166
|
+
## Rust
|
|
167
|
+
|
|
168
|
+
```rust
|
|
169
|
+
#[cfg(test)]
|
|
170
|
+
mod tests {
|
|
171
|
+
use super::*;
|
|
172
|
+
|
|
173
|
+
#[test]
|
|
174
|
+
fn test_create_user_with_valid_data() {
|
|
175
|
+
let user = User::new("Alice", "alice@test.com").unwrap();
|
|
176
|
+
assert_eq!(user.name, "Alice");
|
|
177
|
+
assert!(user.id.is_some());
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
#[test]
|
|
181
|
+
fn test_reject_duplicate_emails() {
|
|
182
|
+
User::new("Alice", "dup@test.com").unwrap();
|
|
183
|
+
let result = User::new("Bob", "dup@test.com");
|
|
184
|
+
assert!(result.is_err());
|
|
185
|
+
assert_eq!(result.unwrap_err().to_string(), "Email already exists");
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
#[test]
|
|
189
|
+
fn test_handle_empty_name() {
|
|
190
|
+
let result = User::new("", "x@test.com");
|
|
191
|
+
assert!(result.is_err());
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
```
|
|
195
|
+
|
|
196
|
+
---
|
|
197
|
+
|
|
198
|
+
## Go
|
|
199
|
+
|
|
200
|
+
```go
|
|
201
|
+
package user
|
|
202
|
+
|
|
203
|
+
import "testing"
|
|
204
|
+
|
|
205
|
+
func TestCreateUser_ValidData(t *testing.T) {
|
|
206
|
+
user, err := NewUser("Alice", "alice@test.com")
|
|
207
|
+
if err != nil {
|
|
208
|
+
t.Fatalf("unexpected error: %v", err)
|
|
209
|
+
}
|
|
210
|
+
if user.Name != "Alice" {
|
|
211
|
+
t.Errorf("got name %q, want %q", user.Name, "Alice")
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
func TestCreateUser_DuplicateEmail(t *testing.T) {
|
|
216
|
+
NewUser("Alice", "dup@test.com")
|
|
217
|
+
_, err := NewUser("Bob", "dup@test.com")
|
|
218
|
+
if err == nil {
|
|
219
|
+
t.Fatal("expected error for duplicate email")
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
// Table-driven test
|
|
224
|
+
func TestValidateEmail(t *testing.T) {
|
|
225
|
+
tests := []struct {
|
|
226
|
+
email string
|
|
227
|
+
expected bool
|
|
228
|
+
}{
|
|
229
|
+
{"", false},
|
|
230
|
+
{"a@b", true},
|
|
231
|
+
{"@b.com", false},
|
|
232
|
+
}
|
|
233
|
+
for _, tc := range tests {
|
|
234
|
+
got := ValidateEmail(tc.email)
|
|
235
|
+
if got != tc.expected {
|
|
236
|
+
t.Errorf("ValidateEmail(%q) = %v, want %v", tc.email, got, tc.expected)
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
```
|
|
241
|
+
|
|
242
|
+
---
|
|
243
|
+
|
|
244
|
+
## Test Structure Decision Tree
|
|
245
|
+
|
|
246
|
+
```
|
|
247
|
+
What kind of code?
|
|
248
|
+
├── Pure function / utility
|
|
249
|
+
│ └── Unit test — test input/output pairs, edge cases
|
|
250
|
+
├── Service / business logic
|
|
251
|
+
│ └── Unit test — mock external dependencies, test logic
|
|
252
|
+
├── API endpoint
|
|
253
|
+
│ └── Integration test — hit the endpoint, check response
|
|
254
|
+
├── Database query
|
|
255
|
+
│ └── Integration test — use test DB or in-memory DB
|
|
256
|
+
├── CLI command
|
|
257
|
+
│ └── Integration test — invoke CLI, check output
|
|
258
|
+
└── UI component
|
|
259
|
+
└── Component test — render, interact, assert
|
|
260
|
+
```
|