Skip to content

Commit 7c8a6a5

Browse files
emcdclaude
andcommitted
Copier Template: Claude Commands: Split test development into planning and implementation phases.
Split cs-develop-tests.md into two commands: cs-plan-tests.md for coverage analysis and test planning, and cs-develop-tests.md for implementing tests from existing plans. This prevents eager Claudes from rushing to implementation without proper analysis. Updated documentation/common/tests.rst with: - Test data directory structure (tests/data/) - Network testing prohibition with httpx MockTransport example - Module vs function numbering warning - Subpackage naming conventions - tests/README.md maintenance requirements 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com>
1 parent 85c6a85 commit 7c8a6a5

3 files changed

Lines changed: 418 additions & 79 deletions

File tree

documentation/common/tests.rst

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,21 @@ Anti-Patterns to Avoid
5555
* **Testing Implementation Details**: Tests should verify behavior, not
5656
internal implementation specifics.
5757

58+
* **External Network Testing**: NEVER test against real external sites. Use mocks or test doubles instead::
59+
60+
# WRONG - tests against real external services
61+
response = httpx.get( 'https://example.com' )
62+
response = httpx.get( 'https://httpbin.org/post' )
63+
64+
# CORRECT - use httpx MockTransport
65+
def handler( request ):
66+
return httpx.Response( 200, json = { 'result': 'success' } )
67+
68+
transport = httpx.MockTransport( handler )
69+
async with httpx.AsyncClient( transport = transport ) as client:
70+
response = await client.get( 'https://api.example.com/data' )
71+
assert response.json( ) == { 'result': 'success' }
72+
5873
Test Organization
5974
===============================================================================
6075

@@ -68,6 +83,11 @@ Test Directory Structure
6883

6984
tests/
7085
├── README.md # Test organization documentation
86+
├── data/ # Test data and fixtures
87+
│ ├── packages/ # Fake packages for extension testing
88+
│ ├── artifacts/ # Captured artifacts for regression testing
89+
│ ├── snapshots/ # Snapshots for output comparison testing
90+
│ └── mocks/ # Mock data files for structured test input
7191
└── test_000_<packagename>/ # Package-specific test namespace
7292
├── __init__.py # Test package initialization
7393
├── fixtures.py # Common test fixtures and utilities
@@ -89,6 +109,21 @@ Numbering System
89109

90110
* Test modules should generally correspond to source modules
91111
* Siblings can be separated by increments of 10
112+
* **Subpackage modules**: Use format ``test_<M><N>0_<subpackage>_<module>.py``
113+
114+
- ``M`` = major component number (e.g., 1, 2, 3)
115+
- ``N`` = advances by 1 for each module within subpackage (0, 1, 2, ...)
116+
- Examples: ``test_110_auth_tokens.py``, ``test_120_auth_sessions.py``
117+
118+
.. warning::
119+
**Do Not Confuse Module and Function Numbering**
120+
121+
* **Test modules**: ``test_100_exceptions.py`` (hundreds place)
122+
* **Test functions**: ``def test_100_basic_validation():`` (within modules)
123+
124+
These are completely separate numbering schemes. Module numbers indicate
125+
architectural hierarchy; function numbers indicate test organization within
126+
that module.
92127

93128
Test Function Numbering
94129
-------------------------------------------------------------------------------
@@ -118,6 +153,13 @@ Maintain a ``tests/README.md`` file documenting:
118153
* Rationale for any use of ``patch`` or other exceptions to standard patterns
119154
* Project-specific testing conventions and fixtures
120155

156+
**Maintenance Requirements**:
157+
158+
* **Update when adding test modules**: Add entries for new test files with their numbering rationale
159+
* **Keep current**: Remove references to deprecated test modules
160+
* **Document changes**: Note any modifications to testing conventions or fixture usage
161+
* **Responsibility**: Update during test planning phase, not during implementation
162+
121163
Preferred Testing Patterns
122164
===============================================================================
123165

@@ -186,6 +228,19 @@ only when necessary::
186228
result = await async_process_config_file( config_file )
187229
assert result.key == 'value'
188230

231+
Test Data and Fixtures
232+
-------------------------------------------------------------------------------
233+
234+
Store test data files under ``tests/data/`` in organized subdirectories:
235+
236+
* **Fake packages**: ``tests/data/packages/`` for extension mechanism testing
237+
* **Captured artifacts**: ``tests/data/artifacts/`` for regression testing
238+
* **Snapshots**: ``tests/data/snapshots/`` for output comparison testing
239+
* **Mock data files**: ``tests/data/mocks/`` for structured test input
240+
241+
Use fixture files when data is complex or reused across multiple tests.
242+
Prefer in-memory test data for simple, single-use scenarios.
243+
189244
When to Mock
190245
-------------------------------------------------------------------------------
191246

Lines changed: 112 additions & 79 deletions
Original file line numberDiff line numberDiff line change
@@ -1,39 +1,39 @@
11
---
22
allowed-tools: Bash(hatch --env develop run:*), Bash(git status), Bash(git log:*), Bash(echo:*), Bash(ls:*), Bash(find:*), LS, Read, Glob, Grep, Write, Edit, MultiEdit, WebFetch
3-
description: Write comprehensive tests following project testing guidelines and improve coverage
3+
description: Implement comprehensive tests following an existing test plan and project guidelines
44
---
55

6-
# Write Tests
6+
# Implement Tests
77

88
**NOTE: This is an experimental workflow! If anything seems unclear or missing,
99
please stop for consultation with the user.**
1010

11-
For systematic test creation following project testing guidelines and conventions.
11+
For systematic test implementation following a pre-created test plan and project testing guidelines.
1212

13-
Test requirements: `$ARGUMENTS`
13+
Test plan path: `$ARGUMENTS`
1414

15-
**CRITICAL**: Apply project testing principles consistently.
15+
**CRITICAL**: Implement tests according to the provided test plan only.
1616
**HALT if**:
17-
- No test requirements are provided
18-
- Target code cannot be analyzed
19-
- Testing principles would be violated
17+
- No test plan path is provided
18+
- Test plan cannot be read or is invalid
19+
- Plan conflicts with project testing principles
20+
- Implementation deviates from plan without justification
2021

2122
## Context
2223

2324
- Current git status: !`git status --porcelain`
2425
- Current branch: !`git branch --show-current`
25-
- Current test coverage: !`hatch --env develop run coverage report --skip-covered || echo "No coverage data available"`
26+
- Test plan to implement: !`ls "$ARGUMENTS" 2>/dev/null && echo "Present" || echo "Missing - HALT"`
2627
- Existing test structure: !`find tests -name "*.py" | head -20`
2728
- Test README: !`ls tests/README.md 2>/dev/null && echo "Present" || echo "Missing"`
2829

2930
## Prerequisites
3031

3132
Ensure that you:
32-
- have verified access to / read target code modules
33-
- understand what specific tests need to be written
34-
- have read any relevant `CLAUDE.md` file
35-
- understand the [test-writing
36-
guidelines](https://raw.githubusercontent.com/emcd/python-project-common/refs/tags/docs-1/documentation/common/tests.rst).
33+
- Have a valid test plan document
34+
- Have verified access to target code modules referenced in the plan
35+
- Have read any relevant `CLAUDE.md` file
36+
- Understand the [test-writing guidelines](https://raw.githubusercontent.com/emcd/python-project-common/refs/tags/docs-1/documentation/common/tests.rst)
3737

3838
## Testing Principles (from project guidelines)
3939

@@ -62,97 +62,122 @@ Ensure that you:
6262
**CRITICAL**: You MUST halt the process and consult with the user if ANY of the
6363
following occur:
6464

65-
- **Anti-Pattern Detection**: If proposed tests violate project principles
66-
- **Coverage Regression**: If tests would reduce existing coverage
65+
- **Plan Deviation**: If implementation cannot follow the test plan as specified
66+
- **Anti-Pattern Detection**: If plan requires tests that violate project principles
6767
- **Architecture Conflicts**: If tests require monkey-patching internal code
68-
- **Numbering Conflicts**: If test numbering clashes with existing conventions
69-
- **Missing Dependencies**: If required test fixtures or dependencies are
70-
unavailable
68+
- **Numbering Conflicts**: If planned test numbering clashes with existing conventions
69+
- **Missing Dependencies**: If required test fixtures or dependencies are unavailable
70+
- **Plan Inconsistencies**: If the test plan contains contradictions or unclear instructions
7171

7272
**Your responsibilities:**
73-
- Follow project style and test-writing conventions exactly.
74-
- Use dependency injection patterns consistently.
75-
- Prefer pyfakefs for filesystem operations.
76-
- Maintain systematic test numbering.
77-
- Ensure tests validate behavior, not implementation.
73+
- Follow the test plan precisely while adhering to project conventions
74+
- Use dependency injection patterns as specified in the plan
75+
- Implement tests exactly as planned without adding extras
76+
- Maintain systematic test numbering as outlined in the plan
77+
- Ensure tests validate behavior, not implementation
78+
- Document any necessary deviations from the plan with clear justification
7879

79-
## Test Writing Process
80+
## Test Implementation Process
8081

81-
Execute the following steps for test requirements: `$ARGUMENTS`
82+
Execute the following steps for test plan: `$ARGUMENTS`
8283

8384
### 0. Pre-Flight Verification
84-
**MANDATORY - Verify access to test-writing guide:**
85+
**MANDATORY - Verify access to project guidelines:**
8586

86-
Use WebFetch to access and confirm you can read the complete testing
87-
guidelines:
88-
https://raw.githubusercontent.com/emcd/python-project-common/refs/tags/docs-1/documentation/common/tests.rst
87+
Use WebFetch to access and confirm you can read the complete project guidelines:
88+
- Testing: https://raw.githubusercontent.com/emcd/python-project-common/refs/tags/docs-1/documentation/common/tests.rst
89+
- Practices: https://raw.githubusercontent.com/emcd/python-project-common/refs/tags/docs-1/documentation/common/practices.rst
90+
- Style: https://raw.githubusercontent.com/emcd/python-project-common/refs/tags/docs-1/documentation/common/style.rst
8991

90-
**CRITICAL**: You MUST successfully access and read the guide before
91-
proceeding. If WebFetch fails, HALT and consult with the user.
92+
**CRITICAL**: You MUST successfully access and read all three guides before
93+
proceeding. If WebFetch fails for any guide, HALT and consult with the user.
9294

93-
### 1. Code Analysis Phase
94-
Examine the target code to understand testing needs:
95+
### 1. Test Plan Reading and Validation
96+
**CRITICAL - Read and validate the provided test plan:**
9597

96-
**Check for existing related tests to avoid duplication:**
97-
- Search for existing test files covering target modules
98-
- Review test coverage reports for current state
99-
- Identify gaps rather than recreating existing tests
98+
Read the test plan document at the provided path:
99+
```
100+
Read the test plan file at: $ARGUMENTS
101+
```
102+
103+
**Validate plan completeness:**
104+
- Verify plan contains coverage analysis summary
105+
- Confirm test strategy is clearly defined
106+
- Check that component-specific tests are detailed
107+
- Ensure implementation notes are present
108+
- Validate success metrics are specified
109+
110+
**HALT if the plan is incomplete, unclear, or missing critical sections.**
100111

101-
**For each target file:**
102-
- Read the source code to understand public API
103-
- Identify functions/classes that need testing
104-
- Note dependency injection points
105-
- Check for existing test coverage gaps
112+
### 2. Plan Compliance Verification
113+
**Ensure plan aligns with project principles:**
106114

107-
### 2. Test Structure Planning
108-
Determine appropriate test organization and categories:
115+
**Verify plan adheres to project testing guidelines:**
116+
- No monkey-patching of internal code required
117+
- Dependency injection patterns are viable
118+
- Test numbering follows project conventions
119+
- No external network testing planned
109120

110-
**Review existing test structure and plan test numbering following project conventions.**
121+
**Check for conflicts with existing tests:**
122+
- Review planned test module names against existing files
123+
- Verify planned test function numbering doesn't conflict
124+
- Ensure no duplication of existing test coverage
111125

112-
**If tests/README.md is missing, create it with:**
113-
- Test module numbering scheme specific to the package
114-
- Rationale for any use of patch or other exceptions to standard patterns
115-
- Project-specific testing conventions and fixtures
126+
### 3. Test Data and Fixture Setup
127+
**Prepare test data as specified in the plan:**
116128

117-
**Test Categories to Include:**
118-
- **Basic Functionality Tests (000-099):** Happy path scenarios, input validation, basic error conditions
119-
- **Feature-Specific Tests (100+ blocks):** Each public function/class gets its own 100-block with normal usage patterns, edge cases, and error handling
120-
- **Integration Tests (higher numbers):** Cross-module interactions and end-to-end workflows
129+
**Create required test data under tests/data/:**
130+
- Set up fake packages for extension mechanisms (if planned)
131+
- Prepare captured artifacts and snapshots (if planned)
132+
- Create any mock data files as specified in the plan
121133

122-
### 3. Test Implementation
123-
Create tests following project conventions:
134+
**CRITICAL**: Only create test data explicitly mentioned in the test plan.
135+
136+
### 4. Test Module Creation/Updates
137+
**Implement test modules following the plan:**
138+
139+
**For each planned test module:**
140+
- Create or update test files with planned naming (e.g., `test_100_exceptions.py`)
141+
- Follow planned test function numbering within modules
142+
- Implement only the tests specified in the plan
143+
- Use dependency injection patterns as outlined in the plan
124144

125145
**Key Implementation Guidelines:**
126-
- Use dependency injection for all external dependencies
127-
- Prefer `pyfakefs.Patcher()` for filesystem operations
146+
- Use dependency injection for all external dependencies as planned
147+
- Prefer `pyfakefs.Patcher()` for filesystem operations as specified
128148
- Mock only third-party services, never internal code
129-
- Include docstrings explaining what behavior is tested
149+
- **Insert tests in numerical order within files** - do NOT append to end
150+
- **Write behavior-focused docstrings**: "Functionality is correct with Y" NOT "function_name does X with Y"
130151
- Follow existing naming conventions and code style
152+
- Implement tests in the exact order and numbering specified in the plan
131153

132154
### 5. Coverage Validation
133-
Verify tests improve coverage without regressions:
155+
**Verify implementation matches plan coverage goals:**
134156
```bash
135157
hatch --env develop run testers
136158
hatch --env develop run coverage report --show-missing
137159
```
138160

139-
**CRITICAL - VERIFY COVERAGE IMPROVEMENT:**
161+
**CRITICAL - VERIFY PLAN COMPLIANCE:**
140162
- Run full test suite to ensure no regressions
141-
- Check that new tests increase overall coverage
142-
- Verify no existing functionality is broken
143-
- Confirm tests follow project numbering conventions
163+
- Check that coverage matches the plan's target metrics
164+
- Verify all planned test functions are implemented
165+
- Confirm coverage gaps identified in the plan are addressed
166+
- Ensure no existing functionality is broken
144167

145168
### 6. Code Quality Validation
146-
Ensure tests meet project standards:
169+
**Ensure implemented tests meet project standards:**
147170
```bash
148171
hatch --env develop run linters
149172
```
150173

151174
**Requirements:**
152175
- All linting checks must pass
176+
- Note that the linters do not check style; you must verify style compliance
153177
- No violations of project coding standards
154178
- Test docstrings are clear and descriptive
155179
- Proper imports and dependencies
180+
- Implementation follows all conventions specified in the plan
156181

157182
## Test Pattern Examples
158183

@@ -163,7 +188,7 @@ async def test_100_process_with_custom_processor( ):
163188
def mock_processor( data ):
164189
return f"processed: {data}"
165190

166-
result = await process_data( "test", processor = mock_processor )
191+
result = await process_data( 'test', processor = mock_processor )
167192
assert result == "processed: test"
168193
```
169194

@@ -174,7 +199,6 @@ def test_200_config_file_processing( ):
174199
with Patcher( ) as patcher:
175200
fs = patcher.fs
176201
fs.create_file( '/fake/config.toml', contents = '[section]\nkey="value"' )
177-
178202
result = process_config_file( Path( '/fake/config.toml' ) )
179203
assert result.key == 'value'
180204
```
@@ -189,24 +213,33 @@ def test_300_invalid_input_handling( ):
189213

190214
## Success Criteria
191215

192-
Tests are complete when:
193-
- [ ] Coverage has measurably improved
216+
Implementation is complete when:
217+
- [ ] All tests specified in the plan have been implemented
218+
- [ ] Coverage matches or exceeds the plan's target metrics
219+
- [ ] All planned test modules and functions are created with correct numbering
220+
- [ ] Test data and fixtures are set up as specified in the plan
194221
- [ ] All new tests pass consistently
195222
- [ ] No existing tests are broken
196223
- [ ] Linting passes without issues
197-
- [ ] Tests follow project numbering conventions
198-
- [ ] Dependency injection is used appropriately
224+
- [ ] Project coding practices and style have been followed
225+
- [ ] Tests follow project numbering conventions as planned
226+
- [ ] Tests are inserted in proper numerical order within files
227+
- [ ] Test docstrings focus on behavior, not function names
228+
- [ ] Dependency injection is used as specified in the plan
199229
- [ ] No monkey-patching of internal code
200-
- [ ] Performance-conscious patterns are applied
230+
- [ ] Performance-conscious patterns are applied as planned
201231

202-
**Note**: Always run full validation (`hatch --env develop run testers && hatch
203-
--env develop run linters`) before considering the task complete.
232+
**Note**: Always run full validation (`hatch --env develop run linters && hatch
233+
--env develop run testers`) before considering the task complete.
204234

205235
## Final Report
206236

207237
Upon completion, provide a brief report covering:
208-
- Coverage improvements achieved (before/after percentages)
209-
- Any technical conflicts encountered (e.g., dataclass/protocol issues, __slots__ conflicts)
210-
- How any conflicts were resolved or worked around
211-
- Pragma directives applied (# pragma: no cover, # pragma: no branch) and rationale
212-
- Any deviations from standard patterns and justification
238+
- **Plan Compliance**: Confirmation that all planned tests were implemented as specified
239+
- **Coverage Achievement**: Final coverage percentages vs. plan targets
240+
- **Deviations from Plan**: Any necessary changes made to the plan during implementation with justification
241+
- **Technical Issues Resolved**: Any conflicts encountered and how they were resolved
242+
- **Pragma Directives Applied**: Any `# pragma: no cover` or `# pragma: no branch` added with rationale
243+
- **Test Data Created**: Summary of fixtures and test data files created under `tests/data/`
244+
- **Module Updates**: List of test modules created or updated with their numbering
245+
- **Code Quality**: Confirmation that tests are properly ordered and have behavior-focused docstrings

0 commit comments

Comments
 (0)