SKILL.md
Generating CLI Tests
Patterns for generating tests for Typer CLI commands.
Workflow
- Identify command type (Create/Read/Update/Delete/Bulk)
- Ensure fixtures exist in
conftest.py - Write tests using scenarios below
- Run tests to verify
Fixtures (conftest.py)
import json
import pytest
from typer.testing import CliRunner
@pytest.fixture
def runner():
"""CLI test runner."""
return CliRunner()
@pytest.fixture
def temp_storage(tmp_path, monkeypatch):
"""Empty storage for testing."""
storage_dir = tmp_path / ".task"
storage_dir.mkdir()
storage_file = storage_dir / "tasks.json"
storage_file.write_text(json.dumps({"version": 1, "tasks": []}))
monkeypatch.setenv("TASK_STORAGE_PATH", str(storage_file))
return storage_file
@pytest.fixture
def sample_data(temp_storage):
"""Pre-populated storage."""
data = {
"version": 1,
"tasks": [
{"title": "First task", "done": False, "priority": "low", "created_at": "2025-01-01T10:00:00", "due_date": None},
{"title": "Second task", "done": True, "priority": "high", "created_at": "2025-01-01T11:00:00", "due_date": None},
]
}
temp_storage.write_text(json.dumps(data))
return data
Test Structure (AAA)
def test_<command>_<scenario>(runner, temp_storage):
# Arrange - via fixtures
# Act
result = runner.invoke(app, ["<command>", "<args>"])
# Assert
assert result.exit_code == 0
assert "<expected>" in result.output
CliRunner Usage
from typer.testing import CliRunner
from task.main import app
runner = CliRunner()
# Basic
result = runner.invoke(app, ["add", "New task"])
# With options
result = runner.invoke(app, ["add", "Task", "--priority", "high"])
# With confirmation
result = runner.invoke(app, ["clear", "1"], input="y\n") # Accept
result = runner.invoke(app, ["clear", "1"], input="n\n") # Decline
# Skip confirmation
result = runner.invoke(app, ["clear", "1", "--force"])
