spec-test 0.1.0__tar.gz

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.
@@ -0,0 +1,95 @@
1
+ Metadata-Version: 2.4
2
+ Name: spec-test
3
+ Version: 0.1.0
4
+ Summary: Specification-driven development tool with test verification
5
+ Author: Pulse Team
6
+ License: MIT
7
+ Requires-Python: >=3.11
8
+ Requires-Dist: pydantic>=2.0.0
9
+ Requires-Dist: pytest>=8.0.0
10
+ Requires-Dist: rich>=13.0.0
11
+ Requires-Dist: typer>=0.9.0
12
+ Provides-Extra: dev
13
+ Requires-Dist: mypy>=1.0.0; extra == 'dev'
14
+ Requires-Dist: pytest-cov>=4.0.0; extra == 'dev'
15
+ Requires-Dist: ruff>=0.1.0; extra == 'dev'
16
+ Description-Content-Type: text/markdown
17
+
18
+ # spec-test
19
+
20
+ Specification-driven development tool that verifies your specs have passing tests.
21
+
22
+ ## Philosophy
23
+
24
+ **Every claim about system behavior must be backed by a passing test.**
25
+
26
+ - If there's no test, the behavior is unverified
27
+ - Specs are written first, then implementation, then tests
28
+ - `spec-test verify` is the source of truth for project health
29
+
30
+ ## Installation
31
+
32
+ ```bash
33
+ pip install spec-test
34
+ # or with uv
35
+ uv add spec-test
36
+ ```
37
+
38
+ ## Quick Start
39
+
40
+ 1. Create a spec file anywhere in your project (must be `spec-*.md`):
41
+
42
+ ```markdown
43
+ # docs/specs/spec-auth.md
44
+
45
+ ## Requirements
46
+ - **AUTH-001**: User can login with email and password
47
+ - **AUTH-002**: Invalid credentials return 401 error
48
+ ```
49
+
50
+ 2. Write tests with the `@spec` decorator:
51
+
52
+ ```python
53
+ from spec_test import spec
54
+
55
+ @spec("AUTH-001", "User can login with email and password")
56
+ def test_user_login():
57
+ response = client.post("/login", json={"email": "test@example.com", "password": "secret"})
58
+ assert response.status_code == 200
59
+
60
+ @spec("AUTH-002", "Invalid credentials return 401 error")
61
+ def test_invalid_login():
62
+ response = client.post("/login", json={"email": "test@example.com", "password": "wrong"})
63
+ assert response.status_code == 401
64
+ ```
65
+
66
+ 3. Verify all specs have passing tests:
67
+
68
+ ```bash
69
+ spec-test verify
70
+ ```
71
+
72
+ ## Commands
73
+
74
+ ```bash
75
+ spec-test verify # Verify all specs have passing tests
76
+ spec-test list-specs # List all specs found
77
+ spec-test check AUTH-001 # Check a single spec
78
+ spec-test init # Initialize spec-test in a project
79
+ ```
80
+
81
+ ## Spec File Format
82
+
83
+ Spec files must:
84
+ - Be named `spec-*.md` (e.g., `spec-auth.md`, `spec-api.md`)
85
+ - Can be anywhere in the project (nested directories supported)
86
+ - Use `**ID**: description` format for requirements
87
+
88
+ ```markdown
89
+ - **AUTH-001**: User can login with email and password
90
+ - **AUTH-002** [manual]: Requires manual verification
91
+ ```
92
+
93
+ ## License
94
+
95
+ MIT
@@ -0,0 +1,78 @@
1
+ # spec-test
2
+
3
+ Specification-driven development tool that verifies your specs have passing tests.
4
+
5
+ ## Philosophy
6
+
7
+ **Every claim about system behavior must be backed by a passing test.**
8
+
9
+ - If there's no test, the behavior is unverified
10
+ - Specs are written first, then implementation, then tests
11
+ - `spec-test verify` is the source of truth for project health
12
+
13
+ ## Installation
14
+
15
+ ```bash
16
+ pip install spec-test
17
+ # or with uv
18
+ uv add spec-test
19
+ ```
20
+
21
+ ## Quick Start
22
+
23
+ 1. Create a spec file anywhere in your project (must be `spec-*.md`):
24
+
25
+ ```markdown
26
+ # docs/specs/spec-auth.md
27
+
28
+ ## Requirements
29
+ - **AUTH-001**: User can login with email and password
30
+ - **AUTH-002**: Invalid credentials return 401 error
31
+ ```
32
+
33
+ 2. Write tests with the `@spec` decorator:
34
+
35
+ ```python
36
+ from spec_test import spec
37
+
38
+ @spec("AUTH-001", "User can login with email and password")
39
+ def test_user_login():
40
+ response = client.post("/login", json={"email": "test@example.com", "password": "secret"})
41
+ assert response.status_code == 200
42
+
43
+ @spec("AUTH-002", "Invalid credentials return 401 error")
44
+ def test_invalid_login():
45
+ response = client.post("/login", json={"email": "test@example.com", "password": "wrong"})
46
+ assert response.status_code == 401
47
+ ```
48
+
49
+ 3. Verify all specs have passing tests:
50
+
51
+ ```bash
52
+ spec-test verify
53
+ ```
54
+
55
+ ## Commands
56
+
57
+ ```bash
58
+ spec-test verify # Verify all specs have passing tests
59
+ spec-test list-specs # List all specs found
60
+ spec-test check AUTH-001 # Check a single spec
61
+ spec-test init # Initialize spec-test in a project
62
+ ```
63
+
64
+ ## Spec File Format
65
+
66
+ Spec files must:
67
+ - Be named `spec-*.md` (e.g., `spec-auth.md`, `spec-api.md`)
68
+ - Can be anywhere in the project (nested directories supported)
69
+ - Use `**ID**: description` format for requirements
70
+
71
+ ```markdown
72
+ - **AUTH-001**: User can login with email and password
73
+ - **AUTH-002** [manual]: Requires manual verification
74
+ ```
75
+
76
+ ## License
77
+
78
+ MIT
@@ -0,0 +1,48 @@
1
+ [project]
2
+ name = "spec-test"
3
+ version = "0.1.0"
4
+ description = "Specification-driven development tool with test verification"
5
+ authors = [{ name = "Pulse Team" }]
6
+ readme = "README.md"
7
+ license = { text = "MIT" }
8
+ requires-python = ">=3.11"
9
+ dependencies = [
10
+ "pytest>=8.0.0",
11
+ "rich>=13.0.0",
12
+ "typer>=0.9.0",
13
+ "pydantic>=2.0.0",
14
+ ]
15
+
16
+ [project.optional-dependencies]
17
+ dev = [
18
+ "pytest-cov>=4.0.0",
19
+ "ruff>=0.1.0",
20
+ "mypy>=1.0.0",
21
+ ]
22
+
23
+ [project.scripts]
24
+ spec-test = "spec_test.cli:app"
25
+
26
+ [project.entry-points.pytest11]
27
+ spec_test = "spec_test.pytest_plugin"
28
+
29
+ [build-system]
30
+ requires = ["hatchling"]
31
+ build-backend = "hatchling.build"
32
+
33
+ [tool.hatch.build.targets.sdist]
34
+ include = ["src/spec_test"]
35
+
36
+ [tool.hatch.build.targets.wheel]
37
+ packages = ["src/spec_test"]
38
+
39
+ [tool.hatch.build]
40
+ sources = ["src"]
41
+
42
+ [tool.ruff]
43
+ line-length = 100
44
+ target-version = "py311"
45
+
46
+ [tool.mypy]
47
+ python_version = "3.11"
48
+ strict = true
@@ -0,0 +1,32 @@
1
+ """spec-test: Specification-driven development with test verification."""
2
+
3
+ from .decorators import get_spec_registry, spec, specs
4
+ from .reporter import Reporter
5
+ from .types import (
6
+ SpecRequirement,
7
+ SpecResult,
8
+ SpecStatus,
9
+ SpecTest,
10
+ VerificationReport,
11
+ VerificationType,
12
+ )
13
+ from .verifier import SpecVerifier
14
+
15
+ __version__ = "0.1.0"
16
+
17
+ __all__ = [
18
+ # Decorators
19
+ "spec",
20
+ "specs",
21
+ "get_spec_registry",
22
+ # Types
23
+ "SpecStatus",
24
+ "SpecRequirement",
25
+ "SpecTest",
26
+ "SpecResult",
27
+ "VerificationReport",
28
+ "VerificationType",
29
+ # Classes
30
+ "SpecVerifier",
31
+ "Reporter",
32
+ ]
@@ -0,0 +1,165 @@
1
+ """Command-line interface for spec-test."""
2
+
3
+ from pathlib import Path
4
+ from typing import Optional
5
+
6
+ import typer
7
+ from rich.console import Console
8
+
9
+ from .collector import collect_specs
10
+ from .reporter import Reporter
11
+ from .verifier import SpecVerifier
12
+
13
+ app = typer.Typer(
14
+ name="spec-test",
15
+ help="Specification-driven development tool with test verification",
16
+ )
17
+ console = Console()
18
+
19
+
20
+ @app.command()
21
+ def verify(
22
+ specs_dir: Path = typer.Option(
23
+ Path("docs/specs"),
24
+ "--specs",
25
+ "-s",
26
+ help="Directory containing spec markdown files",
27
+ ),
28
+ tests_dir: Path = typer.Option(
29
+ Path("tests"),
30
+ "--tests",
31
+ "-t",
32
+ help="Directory containing test files",
33
+ ),
34
+ output: Optional[Path] = typer.Option(
35
+ None,
36
+ "--output",
37
+ "-o",
38
+ help="Output markdown report to file",
39
+ ),
40
+ verbose: bool = typer.Option(
41
+ False,
42
+ "--verbose",
43
+ "-v",
44
+ help="Verbose output",
45
+ ),
46
+ fail_on_missing: bool = typer.Option(
47
+ True,
48
+ "--fail-on-missing/--no-fail-on-missing",
49
+ help="Exit with error if specs are missing tests",
50
+ ),
51
+ ):
52
+ """
53
+ Verify all specifications have passing tests.
54
+
55
+ Reads specs from markdown files, discovers @spec decorated tests,
56
+ and reports coverage.
57
+ """
58
+ verifier = SpecVerifier(
59
+ specs_dir=specs_dir,
60
+ tests_dir=tests_dir,
61
+ )
62
+
63
+ report = verifier.verify(verbose=verbose)
64
+
65
+ reporter = Reporter()
66
+ reporter.print_terminal(report)
67
+
68
+ if output:
69
+ reporter.generate_markdown(report, output)
70
+ console.print(f"\n[green]Report saved to {output}[/green]")
71
+
72
+ # Exit code
73
+ if report.failing > 0:
74
+ raise typer.Exit(code=1)
75
+ if fail_on_missing and report.missing > 0:
76
+ raise typer.Exit(code=2)
77
+
78
+
79
+ @app.command()
80
+ def list_specs(
81
+ specs_dir: Path = typer.Option(
82
+ Path("docs/specs"),
83
+ "--specs",
84
+ "-s",
85
+ help="Directory containing spec markdown files",
86
+ ),
87
+ ):
88
+ """List all specifications found in spec files."""
89
+ specs = collect_specs(specs_dir)
90
+
91
+ if not specs:
92
+ console.print("[yellow]No specifications found[/yellow]")
93
+ raise typer.Exit(code=0)
94
+
95
+ console.print(f"\n[bold]Found {len(specs)} specifications:[/bold]\n")
96
+
97
+ for spec in sorted(specs, key=lambda s: s.id):
98
+ console.print(f" [cyan]{spec.id}[/cyan]: {spec.description}")
99
+ console.print(f" [dim]{spec.source_file}:{spec.source_line}[/dim]")
100
+ console.print()
101
+
102
+
103
+ @app.command()
104
+ def check(
105
+ spec_id: str = typer.Argument(..., help="Spec ID to check (e.g., AUTH-001)"),
106
+ specs_dir: Path = typer.Option(Path("docs/specs"), "--specs", "-s"),
107
+ tests_dir: Path = typer.Option(Path("tests"), "--tests", "-t"),
108
+ ):
109
+ """Check a single specification."""
110
+ verifier = SpecVerifier(specs_dir=specs_dir, tests_dir=tests_dir)
111
+ result = verifier.verify_single(spec_id)
112
+
113
+ if not result:
114
+ console.print(f"[red]Spec {spec_id} not found[/red]")
115
+ raise typer.Exit(code=1)
116
+
117
+ reporter = Reporter()
118
+ status_str = reporter._status_emoji(result.status)
119
+
120
+ console.print(f"\n{status_str} [bold]{result.spec.id}[/bold]: {result.spec.description}")
121
+
122
+ if result.test:
123
+ console.print(f" Test: [dim]{result.test.test_path}[/dim]")
124
+ if result.error_message:
125
+ console.print(f" [red]{result.error_message}[/red]")
126
+
127
+
128
+ @app.command()
129
+ def init(
130
+ path: Path = typer.Argument(
131
+ Path("."),
132
+ help="Project root to initialize",
133
+ ),
134
+ ):
135
+ """Initialize spec-test in a project."""
136
+ specs_dir = path / "docs" / "specs"
137
+ specs_dir.mkdir(parents=True, exist_ok=True)
138
+
139
+ # Create example spec file (must match spec-*.md pattern)
140
+ example_spec = specs_dir / "spec-example.md"
141
+ if not example_spec.exists():
142
+ example_spec.write_text("""# Example Specification
143
+
144
+ ## Overview
145
+ This is an example specification file. Replace with your actual specs.
146
+ Spec files must be named spec-*.md to be discovered.
147
+
148
+ ## Requirements
149
+
150
+ ### Core Features
151
+ - **EXAMPLE-001**: The system should do something useful
152
+ - **EXAMPLE-002**: The system should handle errors gracefully
153
+ - **EXAMPLE-003** [manual]: Code follows project naming conventions
154
+ """)
155
+
156
+ console.print(f"[green]Initialized spec-test in {path}[/green]")
157
+ console.print(f" Created: {specs_dir}")
158
+ console.print(f"\nNext steps:")
159
+ console.print(f" 1. Edit {example_spec}")
160
+ console.print(f" 2. Write tests with @spec decorator")
161
+ console.print(f" 3. Run: spec-test verify")
162
+
163
+
164
+ if __name__ == "__main__":
165
+ app()
@@ -0,0 +1,76 @@
1
+ """Collect specifications from markdown files."""
2
+
3
+ import re
4
+ from pathlib import Path
5
+ from typing import Iterator
6
+
7
+ from .types import SpecRequirement, VerificationType
8
+
9
+ # Pattern: **SPEC-001**: Description
10
+ # Or: - **SPEC-001**: Description
11
+ # Or with verification type: **SPEC-001** [manual]: Description
12
+ SPEC_PATTERN = re.compile(
13
+ r"\*\*([A-Z]+-\d+)\*\*" # **SPEC-001**
14
+ r"(?:\s*\[(\w+)\])?" # Optional [verification_type]
15
+ r":\s*(.+?)$", # : Description
16
+ re.MULTILINE,
17
+ )
18
+
19
+
20
+ def collect_specs(specs_dir: str | Path) -> list[SpecRequirement]:
21
+ """
22
+ Collect all specification requirements from spec-*.md files.
23
+
24
+ Args:
25
+ specs_dir: Directory to search for spec-*.md files (searches recursively)
26
+
27
+ Returns:
28
+ List of SpecRequirement objects
29
+ """
30
+ specs_path = Path(specs_dir)
31
+ if not specs_path.exists():
32
+ return []
33
+
34
+ specs = []
35
+ # Only collect from files matching spec-*.md pattern
36
+ for md_file in specs_path.glob("**/spec-*.md"):
37
+ specs.extend(_parse_spec_file(md_file))
38
+
39
+ return specs
40
+
41
+
42
+ def _parse_spec_file(file_path: Path) -> Iterator[SpecRequirement]:
43
+ """Parse a single markdown file for spec requirements."""
44
+ content = file_path.read_text()
45
+ lines = content.split("\n")
46
+
47
+ for line_num, line in enumerate(lines, 1):
48
+ match = SPEC_PATTERN.search(line)
49
+ if not match:
50
+ continue
51
+
52
+ spec_id = match.group(1)
53
+ verification_type_str = match.group(2)
54
+ description = match.group(3).strip()
55
+
56
+ # Determine verification type
57
+ if verification_type_str:
58
+ try:
59
+ verification_type = VerificationType(verification_type_str.lower())
60
+ except ValueError:
61
+ verification_type = VerificationType.TEST
62
+ else:
63
+ verification_type = VerificationType.TEST
64
+
65
+ yield SpecRequirement(
66
+ id=spec_id,
67
+ description=description,
68
+ source_file=file_path,
69
+ source_line=line_num,
70
+ verification_type=verification_type,
71
+ )
72
+
73
+
74
+ def collect_spec_ids(specs_dir: str | Path) -> set[str]:
75
+ """Collect just the spec IDs (for quick lookups)."""
76
+ return {spec.id for spec in collect_specs(specs_dir)}
@@ -0,0 +1,113 @@
1
+ """Decorators for linking tests to specifications."""
2
+
3
+ import functools
4
+ from typing import Callable, Optional
5
+
6
+ import pytest
7
+
8
+ # Global registry: spec_id -> list of test paths
9
+ _spec_registry: dict[str, list[dict]] = {}
10
+
11
+
12
+ def spec(
13
+ spec_id: str,
14
+ description: str,
15
+ verification_notes: Optional[str] = None,
16
+ ):
17
+ """
18
+ Decorator that links a test function to a specification requirement.
19
+
20
+ Args:
21
+ spec_id: Unique identifier matching the spec doc (e.g., "AUTH-001")
22
+ description: Brief description of what this test verifies
23
+ verification_notes: Optional notes about how this test verifies the spec
24
+
25
+ Usage:
26
+ @spec("AUTH-001", "User can create API token")
27
+ def test_create_token_returns_valid_jwt():
28
+ ...
29
+ """
30
+
31
+ def decorator(func: Callable) -> Callable:
32
+ # Register this test
33
+ if spec_id not in _spec_registry:
34
+ _spec_registry[spec_id] = []
35
+
36
+ _spec_registry[spec_id].append(
37
+ {
38
+ "test_path": f"{func.__module__}::{func.__qualname__}",
39
+ "description": description,
40
+ "notes": verification_notes,
41
+ }
42
+ )
43
+
44
+ # Attach metadata to function
45
+ func._spec_id = spec_id
46
+ func._spec_description = description
47
+ func._spec_notes = verification_notes
48
+
49
+ # Add pytest marker for filtering: pytest -m "spec"
50
+ marked = pytest.mark.spec(func)
51
+ marked = pytest.mark.spec_id(spec_id)(marked)
52
+
53
+ @functools.wraps(func)
54
+ def wrapper(*args, **kwargs):
55
+ return func(*args, **kwargs)
56
+
57
+ # Preserve spec metadata on wrapper
58
+ wrapper._spec_id = spec_id
59
+ wrapper._spec_description = description
60
+ wrapper._spec_notes = verification_notes
61
+
62
+ return wrapper
63
+
64
+ return decorator
65
+
66
+
67
+ def get_spec_registry() -> dict[str, list[dict]]:
68
+ """Get all registered spec -> test mappings."""
69
+ return _spec_registry.copy()
70
+
71
+
72
+ def clear_registry():
73
+ """Clear the registry (useful for testing)."""
74
+ _spec_registry.clear()
75
+
76
+
77
+ def specs(*spec_ids: str):
78
+ """
79
+ Decorator for tests that verify multiple specs.
80
+
81
+ Usage:
82
+ @specs("AUTH-001", "AUTH-002")
83
+ def test_token_creation_and_validation():
84
+ ...
85
+ """
86
+
87
+ def decorator(func: Callable) -> Callable:
88
+ for spec_id in spec_ids:
89
+ if spec_id not in _spec_registry:
90
+ _spec_registry[spec_id] = []
91
+ _spec_registry[spec_id].append(
92
+ {
93
+ "test_path": f"{func.__module__}::{func.__qualname__}",
94
+ "description": f"Multi-spec test covering {', '.join(spec_ids)}",
95
+ "notes": None,
96
+ }
97
+ )
98
+
99
+ func._spec_ids = spec_ids
100
+
101
+ # Add markers
102
+ marked = pytest.mark.spec(func)
103
+ for sid in spec_ids:
104
+ marked = pytest.mark.spec_id(sid)(marked)
105
+
106
+ @functools.wraps(func)
107
+ def wrapper(*args, **kwargs):
108
+ return func(*args, **kwargs)
109
+
110
+ wrapper._spec_ids = spec_ids
111
+ return wrapper
112
+
113
+ return decorator
@@ -0,0 +1,9 @@
1
+ """pytest plugin for spec-test integration."""
2
+
3
+ import pytest
4
+
5
+
6
+ def pytest_configure(config):
7
+ """Register custom markers."""
8
+ config.addinivalue_line("markers", "spec: mark test as linked to a specification")
9
+ config.addinivalue_line("markers", "spec_id(id): mark test with specific spec ID")
@@ -0,0 +1,141 @@
1
+ """Generate verification reports."""
2
+
3
+ from datetime import datetime
4
+ from pathlib import Path
5
+
6
+ from rich import box
7
+ from rich.console import Console
8
+ from rich.panel import Panel
9
+ from rich.table import Table
10
+
11
+ from .types import SpecResult, SpecStatus, VerificationReport
12
+
13
+
14
+ class Reporter:
15
+ """Generate and display verification reports."""
16
+
17
+ def __init__(self):
18
+ self.console = Console()
19
+
20
+ def print_terminal(self, report: VerificationReport):
21
+ """Print report to terminal with rich formatting."""
22
+
23
+ # Header
24
+ self.console.print()
25
+ self.console.print(
26
+ Panel.fit(
27
+ "[bold]Specification Verification Report[/bold]",
28
+ border_style="blue",
29
+ )
30
+ )
31
+ self.console.print()
32
+
33
+ # Results table
34
+ table = Table(box=box.ROUNDED, show_header=True, header_style="bold")
35
+ table.add_column("Spec ID", style="cyan")
36
+ table.add_column("Description")
37
+ table.add_column("Status", justify="center")
38
+ table.add_column("Test / Notes")
39
+
40
+ for result in report.results:
41
+ status_str = self._status_emoji(result.status)
42
+ test_info = self._get_test_info(result)
43
+
44
+ table.add_row(
45
+ result.spec.id,
46
+ result.spec.description[:50] + "..."
47
+ if len(result.spec.description) > 50
48
+ else result.spec.description,
49
+ status_str,
50
+ test_info,
51
+ )
52
+
53
+ self.console.print(table)
54
+ self.console.print()
55
+
56
+ # Summary
57
+ self._print_summary(report)
58
+
59
+ # Failures detail
60
+ if report.failing > 0 or report.missing > 0:
61
+ self._print_failures(report)
62
+
63
+ def _status_emoji(self, status: SpecStatus) -> str:
64
+ """Convert status to emoji string."""
65
+ return {
66
+ SpecStatus.PASSING: "[green]PASS[/green]",
67
+ SpecStatus.FAILING: "[red]FAIL[/red]",
68
+ SpecStatus.PENDING: "[yellow]NO TEST[/yellow]",
69
+ SpecStatus.SKIPPED: "[dim]SKIP[/dim]",
70
+ }.get(status, "?")
71
+
72
+ def _get_test_info(self, result: SpecResult) -> str:
73
+ """Get test path or status notes."""
74
+ if result.test:
75
+ return f"[dim]{result.test.test_path}[/dim]"
76
+ if result.error_message:
77
+ return f"[dim]{result.error_message[:40]}[/dim]"
78
+ return "-"
79
+
80
+ def _print_summary(self, report: VerificationReport):
81
+ """Print summary statistics."""
82
+ total = report.total_specs
83
+
84
+ summary = f"""[bold]Summary[/bold]
85
+
86
+ Total Specs: {total}
87
+ [green]Passing:[/green] {report.passing}
88
+ [red]Failing:[/red] {report.failing}
89
+ [yellow]Missing Tests:[/yellow] {report.missing}
90
+
91
+ [bold]Coverage:[/bold] {report.coverage_percent:.1f}%
92
+ """
93
+ self.console.print(Panel(summary, title="Results", border_style="blue"))
94
+
95
+ def _print_failures(self, report: VerificationReport):
96
+ """Print details about failures."""
97
+ self.console.print()
98
+ self.console.print("[bold red]Issues Found:[/bold red]")
99
+ self.console.print()
100
+
101
+ for result in report.results:
102
+ if result.status == SpecStatus.PENDING:
103
+ self.console.print(f" [yellow]! {result.spec.id}[/yellow]: No test")
104
+ self.console.print(
105
+ f" [dim]{result.spec.source_file}:{result.spec.source_line}[/dim]"
106
+ )
107
+ elif result.status == SpecStatus.FAILING:
108
+ self.console.print(f" [red]X {result.spec.id}[/red]: Test failing")
109
+ if result.test:
110
+ self.console.print(f" [dim]{result.test.test_path}[/dim]")
111
+
112
+ def generate_markdown(self, report: VerificationReport, output: Path):
113
+ """Generate markdown report file."""
114
+ lines = [
115
+ "# Specification Status Report",
116
+ "",
117
+ f"*Generated: {datetime.now().isoformat()}*",
118
+ "",
119
+ f"**Coverage: {report.coverage_percent:.1f}%** | "
120
+ f"PASS {report.passing} | FAIL {report.failing} | NO TEST {report.missing}",
121
+ "",
122
+ "## Results",
123
+ "",
124
+ "| Spec ID | Description | Status | Test |",
125
+ "|---------|-------------|--------|------|",
126
+ ]
127
+
128
+ for result in report.results:
129
+ status = {
130
+ SpecStatus.PASSING: "PASS",
131
+ SpecStatus.FAILING: "FAIL",
132
+ SpecStatus.PENDING: "NO TEST",
133
+ SpecStatus.SKIPPED: "SKIP",
134
+ }.get(result.status, "?")
135
+
136
+ test_path = result.test.test_path if result.test else "-"
137
+ desc = result.spec.description.replace("|", "\\|")
138
+
139
+ lines.append(f"| {result.spec.id} | {desc} | {status} | `{test_path}` |")
140
+
141
+ output.write_text("\n".join(lines))
@@ -0,0 +1,150 @@
1
+ """Run tests and collect results."""
2
+
3
+ import ast
4
+ import os
5
+ import subprocess
6
+ import sys
7
+ from pathlib import Path
8
+ from typing import Optional
9
+
10
+ from .types import SpecTest
11
+
12
+
13
+ def discover_spec_tests(tests_dir: str | Path) -> dict[str, SpecTest]:
14
+ """
15
+ Discover all tests decorated with @spec.
16
+
17
+ Returns:
18
+ Dict mapping spec_id -> SpecTest
19
+ """
20
+ tests_path = Path(tests_dir)
21
+ if not tests_path.exists():
22
+ return {}
23
+
24
+ return _discover_from_files(tests_path)
25
+
26
+
27
+ def _discover_from_files(tests_dir: Path) -> dict[str, SpecTest]:
28
+ """Parse test files to find @spec decorators."""
29
+ spec_tests: dict[str, SpecTest] = {}
30
+
31
+ for py_file in tests_dir.glob("**/*.py"):
32
+ if py_file.name.startswith("__"):
33
+ continue
34
+
35
+ try:
36
+ tree = ast.parse(py_file.read_text())
37
+ except SyntaxError:
38
+ continue
39
+
40
+ for node in ast.walk(tree):
41
+ if not isinstance(node, ast.FunctionDef):
42
+ continue
43
+
44
+ spec_info = _extract_spec_decorator(node)
45
+ if spec_info:
46
+ spec_id, description = spec_info
47
+ # Use file path format for pytest: /path/to/file.py::test_name
48
+ test_path = f"{py_file}::{node.name}"
49
+
50
+ spec_tests[spec_id] = SpecTest(
51
+ spec_id=spec_id,
52
+ description=description,
53
+ test_path=test_path,
54
+ test_file=py_file,
55
+ test_line=node.lineno,
56
+ )
57
+
58
+ return spec_tests
59
+
60
+
61
+ def _extract_spec_decorator(node: ast.FunctionDef) -> Optional[tuple[str, str]]:
62
+ """Extract @spec decorator info from a function node."""
63
+ for decorator in node.decorator_list:
64
+ if isinstance(decorator, ast.Call):
65
+ func = decorator.func
66
+ if isinstance(func, ast.Name) and func.id == "spec":
67
+ args = decorator.args
68
+ if len(args) >= 2:
69
+ spec_id = _get_string_value(args[0])
70
+ description = _get_string_value(args[1])
71
+ if spec_id and description:
72
+ return (spec_id, description)
73
+ return None
74
+
75
+
76
+ def _get_string_value(node: ast.expr) -> Optional[str]:
77
+ """Extract string value from AST node."""
78
+ if isinstance(node, ast.Constant) and isinstance(node.value, str):
79
+ return node.value
80
+ return None
81
+
82
+
83
+ def _get_env_with_pythonpath() -> dict[str, str]:
84
+ """Get environment with current Python path included."""
85
+ env = os.environ.copy()
86
+ # Ensure the current Python's site-packages are available
87
+ python_path = os.pathsep.join(sys.path)
88
+ if "PYTHONPATH" in env:
89
+ env["PYTHONPATH"] = python_path + os.pathsep + env["PYTHONPATH"]
90
+ else:
91
+ env["PYTHONPATH"] = python_path
92
+ return env
93
+
94
+
95
+ def run_test(test_path: str, tests_dir: Path) -> tuple[bool, Optional[str]]:
96
+ """
97
+ Run a specific test and return pass/fail status.
98
+
99
+ Returns:
100
+ Tuple of (passed: bool, error_message: Optional[str])
101
+ """
102
+ result = subprocess.run(
103
+ [
104
+ sys.executable,
105
+ "-m",
106
+ "pytest",
107
+ test_path,
108
+ "-v",
109
+ "--tb=short",
110
+ "--no-header",
111
+ "-p",
112
+ "no:spec_test", # Disable our plugin to avoid recursion
113
+ ],
114
+ capture_output=True,
115
+ text=True,
116
+ cwd=Path.cwd(),
117
+ env=_get_env_with_pythonpath(),
118
+ )
119
+
120
+ passed = result.returncode == 0
121
+ error_message = None if passed else result.stdout + result.stderr
122
+
123
+ return passed, error_message
124
+
125
+
126
+ def run_tests_by_spec_id(spec_id: str, tests_dir: Path) -> tuple[bool, Optional[str]]:
127
+ """Run all tests for a given spec ID."""
128
+ result = subprocess.run(
129
+ [
130
+ sys.executable,
131
+ "-m",
132
+ "pytest",
133
+ str(tests_dir),
134
+ "-v",
135
+ "-m",
136
+ f"spec_id({spec_id})",
137
+ "--tb=short",
138
+ "-p",
139
+ "no:spec_test", # Disable our plugin to avoid recursion
140
+ ],
141
+ capture_output=True,
142
+ text=True,
143
+ cwd=Path.cwd(),
144
+ env=_get_env_with_pythonpath(),
145
+ )
146
+
147
+ passed = result.returncode == 0
148
+ error_message = None if passed else result.stdout + result.stderr
149
+
150
+ return passed, error_message
@@ -0,0 +1,78 @@
1
+ """Type definitions for spec-test."""
2
+
3
+ from dataclasses import dataclass, field
4
+ from enum import Enum
5
+ from typing import Optional
6
+ from pathlib import Path
7
+
8
+
9
+ class SpecStatus(Enum):
10
+ """Status of a specification requirement."""
11
+ PENDING = "pending" # No test written yet
12
+ PASSING = "passing" # Test exists and passes
13
+ FAILING = "failing" # Test exists but fails
14
+ SKIPPED = "skipped" # Explicitly skipped
15
+
16
+
17
+ class VerificationType(Enum):
18
+ """How a spec should be verified."""
19
+ TEST = "test" # Standard pytest test
20
+ MANUAL = "manual" # Requires human verification
21
+
22
+
23
+ @dataclass
24
+ class SpecRequirement:
25
+ """A single specification requirement parsed from markdown."""
26
+ id: str
27
+ description: str
28
+ source_file: Path
29
+ source_line: int
30
+ verification_type: VerificationType = VerificationType.TEST
31
+
32
+ def __hash__(self):
33
+ return hash(self.id)
34
+
35
+
36
+ @dataclass
37
+ class SpecTest:
38
+ """A test linked to a specification."""
39
+ spec_id: str
40
+ description: str
41
+ test_path: str # module::function format
42
+ test_file: Path
43
+ test_line: int
44
+
45
+
46
+ @dataclass
47
+ class SpecResult:
48
+ """Result of verifying a single spec."""
49
+ spec: SpecRequirement
50
+ status: SpecStatus
51
+ test: Optional[SpecTest] = None
52
+ error_message: Optional[str] = None
53
+
54
+
55
+ @dataclass
56
+ class VerificationReport:
57
+ """Complete verification report."""
58
+ results: list[SpecResult]
59
+ total_specs: int = 0
60
+ passing: int = 0
61
+ failing: int = 0
62
+ missing: int = 0
63
+
64
+ def __post_init__(self):
65
+ self.total_specs = len(self.results)
66
+ self.passing = sum(1 for r in self.results if r.status == SpecStatus.PASSING)
67
+ self.failing = sum(1 for r in self.results if r.status == SpecStatus.FAILING)
68
+ self.missing = sum(1 for r in self.results if r.status == SpecStatus.PENDING)
69
+
70
+ @property
71
+ def coverage_percent(self) -> float:
72
+ if self.total_specs == 0:
73
+ return 100.0
74
+ return (self.passing / self.total_specs) * 100
75
+
76
+ @property
77
+ def is_passing(self) -> bool:
78
+ return self.failing == 0 and self.missing == 0
@@ -0,0 +1,112 @@
1
+ """Main verification logic."""
2
+
3
+ from pathlib import Path
4
+ from typing import Optional
5
+
6
+ from rich.console import Console
7
+ from rich.progress import Progress, SpinnerColumn, TextColumn
8
+
9
+ from .collector import collect_specs
10
+ from .runner import discover_spec_tests, run_test
11
+ from .types import (
12
+ SpecRequirement,
13
+ SpecResult,
14
+ SpecStatus,
15
+ SpecTest,
16
+ VerificationReport,
17
+ VerificationType,
18
+ )
19
+
20
+
21
+ class SpecVerifier:
22
+ """Main class for verifying specifications against tests."""
23
+
24
+ def __init__(
25
+ self,
26
+ specs_dir: str | Path = "docs/specs",
27
+ tests_dir: str | Path = "tests",
28
+ project_root: Optional[Path] = None,
29
+ ):
30
+ self.specs_dir = Path(specs_dir)
31
+ self.tests_dir = Path(tests_dir)
32
+ self.project_root = project_root or Path.cwd()
33
+ self.console = Console()
34
+
35
+ def verify(self, verbose: bool = False) -> VerificationReport:
36
+ """
37
+ Run full verification of all specs.
38
+
39
+ Returns:
40
+ VerificationReport with all results
41
+ """
42
+ # Collect specs from markdown
43
+ specs = collect_specs(self.specs_dir)
44
+
45
+ if not specs:
46
+ self.console.print("[yellow]No specifications found[/yellow]")
47
+ return VerificationReport(results=[])
48
+
49
+ # Discover tests
50
+ spec_tests = discover_spec_tests(self.tests_dir)
51
+
52
+ results: list[SpecResult] = []
53
+
54
+ with Progress(
55
+ SpinnerColumn(),
56
+ TextColumn("[progress.description]{task.description}"),
57
+ console=self.console,
58
+ transient=True,
59
+ ) as progress:
60
+ task = progress.add_task("Verifying specs...", total=len(specs))
61
+
62
+ for spec in specs:
63
+ result = self._verify_spec(spec, spec_tests, verbose)
64
+ results.append(result)
65
+ progress.advance(task)
66
+
67
+ return VerificationReport(results=results)
68
+
69
+ def _verify_spec(
70
+ self,
71
+ spec: SpecRequirement,
72
+ spec_tests: dict[str, SpecTest],
73
+ verbose: bool,
74
+ ) -> SpecResult:
75
+ """Verify a single specification."""
76
+
77
+ # Handle manual verification type
78
+ if spec.verification_type == VerificationType.MANUAL:
79
+ return SpecResult(
80
+ spec=spec,
81
+ status=SpecStatus.SKIPPED,
82
+ error_message="Manual verification required",
83
+ )
84
+
85
+ # Standard test verification
86
+ if spec.id not in spec_tests:
87
+ return SpecResult(
88
+ spec=spec,
89
+ status=SpecStatus.PENDING,
90
+ error_message=f"No test found for {spec.id}",
91
+ )
92
+
93
+ test = spec_tests[spec.id]
94
+ passed, error = run_test(test.test_path, self.tests_dir)
95
+
96
+ return SpecResult(
97
+ spec=spec,
98
+ status=SpecStatus.PASSING if passed else SpecStatus.FAILING,
99
+ test=test,
100
+ error_message=error,
101
+ )
102
+
103
+ def verify_single(self, spec_id: str) -> Optional[SpecResult]:
104
+ """Verify a single spec by ID."""
105
+ specs = collect_specs(self.specs_dir)
106
+ spec = next((s for s in specs if s.id == spec_id), None)
107
+
108
+ if not spec:
109
+ return None
110
+
111
+ spec_tests = discover_spec_tests(self.tests_dir)
112
+ return self._verify_spec(spec, spec_tests, verbose=True)