···1616.JML. YM `Ybmd9' `Mbmo`Mbmmd'.JMML.`Mbmmd' `Moo9^Yo..JMML.
1717```
18181919-A note, task & time management CLI built with Golang & Charm.sh libs. Inspired by TaskWarrior & todo.txt CLI applications.
1919+Noteleaf is a unified personal productivity CLI that combines task management, note-taking, and media tracking in one place.
2020+It provides TaskWarrior-inspired task management with additional support for notes, articles, books, movies, and TV shows - all built with Golang & Charm.sh libs. Inspired by TaskWarrior & todo.txt CLI applications.
2121+2222+## Why?
2323+2424+- **Fragmented productivity tools**: Instead of juggling multiple apps for tasks, notes, reading lists, and media queues, Noteleaf provides a single CLI interface
2525+- **Terminal-native workflow**: For developers and power users who prefer staying in the terminal, Noteleaf offers rich TUIs without leaving your command line
2626+ - **Lightweight and fast**: No desktop apps or web interfaces - just a fast, focused CLI tool
2727+- **Unified data model**: Tasks, notes, and media items can reference each other, creating a connected knowledge and productivity system
2828+2929+## Getting started
3030+3131+### Prerequisites
3232+3333+Go v1.24+
3434+3535+### Installation
3636+3737+```sh
3838+git clone https://github.com/stormlightlabs/noteleaf
3939+cd noteleaf
4040+go build -o ./tmp/noteleaf ./cmd
4141+go install
4242+```
4343+4444+### Basic usage
4545+4646+```sh
4747+# Initialize the application
4848+noteleaf setup
4949+5050+# Add sample data for exploration
5151+noteleaf setup seed
5252+5353+# Create your first task
5454+noteleaf task add "Learn Noteleaf CLI"
5555+5656+# View tasks
5757+noteleaf task list
5858+5959+# Create a note
6060+noteleaf note add "My first note"
6161+6262+# Add a book to your reading list
6363+noteleaf media book add "The Name of the Wind"
6464+```
6565+6666+## Status
6767+6868+**Status**: Work in Progress (MVP completed)
6969+7070+### Completed
20712121-## Development
7272+Core functionality is complete and stable:
22732323-Requires Go v1.24+
7474+- Task management with projects and tags
7575+- Note-taking system
7676+- Article parsing from URLs
7777+- Media tracking (books, movies, TV shows)
7878+7979+### Planned
8080+8181+- Time tracking integration
8282+- Advanced search and filtering
8383+- Export/import functionality
8484+- Plugin system
-58
docs/cli.md
···11-# CLI Docs
22-33-## CommandGroup Interface Pattern
44-55-This section outlines the CommandGroup interface pattern for implementing CLI commands in the noteleaf application.
66-77-### Core Concepts
88-99-Each major command group implements the CommandGroup interface with a `Create() *cobra.Command` method. Command groups receive handlers as constructor dependencies, enabling dependency injection for testing. Handler initialization occurs centrally in main.go with `log.Fatalf` error handling to fail fast during application startup.
1010-1111-### CommandGroup Interface
1212-1313-interface `CommandGroup` provides a consistent contract for all command groups. Each implementation encapsulates related commands and the shared handler dependency. The Create method returns a fully configured cobra command tree.
1414-1515-#### Implementations
1616-1717-TaskCommands handles todo and task-related operations using TaskHandler. MovieCommand manages movie queue operations via MovieHandler.
1818-TVCommand handles TV show queue operations through TVHandler. NoteCommand manages note operations using NoteHandler.
1919-2020-### Handler Lifecycle
2121-2222-Handlers are created once in `main.go` during application startup. Initialization errors prevent application launch rather than causing runtime failures.
2323-Handlers persist for the application lifetime without requiring cleanup. Commands access handlers through struct fields rather than creating new instances.
2424-2525-### Testing
2626-2727-`CommandGroup` structs accept handlers as constructor parameters, enabling easy dependency injection of mock handlers for testing.
2828-Command logic can be tested independently of handler implementations. The interface allows mocking entire command groups for integration testing.
2929-3030-### Registry
3131-3232-`main.go` uses a registry pattern to organize command groups by category. Core commands include task, note, and media functionality.
3333-Management commands handle configuration, setup, and maintenance operations. The pattern provides clean separation and easy extension for new command groups.
3434-3535-## UI and Styling System
3636-3737-The application uses a structured color palette system located in `internal/ui/colors.go` for consistent terminal output styling.
3838-3939-### Color Architecture
4040-4141-The color system implements a `Key` type with 74 predefined colors from the Charm ecosystem, including warm tones (Cumin, Tang, Paprika), cool tones (Sapphire, Oceania, Zinc), and neutral grays (Pepper through Butter). Each color provides hex values via the `Hex()` method and implements Go's `color.Color` interface through `RGBA()`.
4242-4343-### Predefined Styles
4444-4545-Three core lipgloss styles handle common UI elements:
4646-4747-- `TitleColorStyle` uses color 212 with bold formatting for command titles
4848-- `SelectedColorStyle` provides white-on-212 highlighting for selected items
4949-- `HeaderColorStyle` applies color 240 with bold formatting for section headers
5050-5151-### Color Categories
5252-5353-Colors are organized into primary, secondary, and tertiary categories are accessed through `IsPrimary()`, `IsSecondary()`, and `IsTertiary()` methods on the `Key` type.
5454-5555-### Lipgloss Integration
5656-5757-The styling system integrates with the Charmbracelet lipgloss library for terminal UI rendering.
5858-Colors from the `Key` type convert to lipgloss color values through their `Hex()` method. The predefined `TitleColorStyle`, `SelectedColorStyle`, and `HeaderColorStyle` variables provide lipgloss styles that can be applied to strings with `.Render()`.
+87
docs/dev/ARCHITECTURE.md
···11+# System Architecture
22+33+Noteleaf is a CLI/TUI application for task and content management built on Go with SQLite persistence and terminal-based interfaces.
44+55+## Core Architecture
66+77+### Application Structure
88+99+The application follows a layered architecture with clear separation between presentation, business logic, and data access layers.
1010+1111+**Entry Point** - `cmd/main.go` initializes the application with dependency injection, creates handlers, and configures the Cobra command tree using the CommandGroup pattern.
1212+1313+**CLI Framework** - Built on `spf13/cobra` with `charmbracelet/fang` providing enhanced CLI features including color schemes, versioning, and improved help formatting.
1414+1515+**TUI Components** - Interactive interfaces use `charmbracelet/bubbletea` for state management and `charmbracelet/lipgloss` for styling with a consistent color palette system in `internal/ui/colors.go`.
1616+1717+### Data Layer
1818+1919+**Database** - SQLite with schema migrations in `internal/store/sql/migrations/`. The `internal/store` package manages database connections and configuration.
2020+2121+**Repository Pattern** - Data access abstracts through repository interfaces in `internal/repo/` with validation logic ensuring data integrity at the persistence boundary.
2222+2323+**Models** - Entity definitions in `internal/models/` implement standardized Model interfaces with common fields (ID, Created, Modified).
2424+2525+### Business Logic
2626+2727+**Handlers** - Business logic resides in `internal/handlers/` with one handler per domain (TaskHandler, NoteHandler, ArticleHandler, etc.). Handlers receive repository dependencies through constructor injection.
2828+2929+**Services** - Domain-specific operations in `internal/services/` handle complex business workflows and external integrations.
3030+3131+**Validation** - Schema-based validation at repository level with custom ValidationError types providing detailed field-level error messages.
3232+3333+## Domain Features
3434+3535+### Content Management
3636+3737+**Articles** - Web scraping using `gocolly/colly` with domain-specific extraction rules stored in `internal/articles/rules/`. Articles are parsed to markdown and stored with dual file references (markdown + HTML).
3838+3939+**Tasks** - Todo/task management inspired by TaskWarrior with filtering, status tracking, and interactive TUI views.
4040+4141+**Notes** - Simple note management with markdown support and glamour-based terminal rendering.
4242+4343+**Media Queues** - Separate queues for books, movies, and TV shows with status tracking and metadata management.
4444+4545+### User Interface
4646+4747+**Command Groups** - Commands organized into core functionality (task, note, article, media) and management operations (setup, config, status) using the CommandGroup interface pattern.
4848+4949+**Interactive Views** - Bubbletea-based TUI components for list navigation, item selection, and data entry with consistent styling through the lipgloss color system.
5050+5151+**Terminal Output** - Markdown rendering through `charmbracelet/glamour` for rich text display in terminal environments.
5252+5353+## Dependencies
5454+5555+**CLI/TUI** - Cobra command framework, Bubbletea state management, Lipgloss styling, Fang CLI enhancements.
5656+5757+**Data** - SQLite driver (`mattn/go-sqlite3`), TOML configuration parsing.
5858+5959+**Content Processing** - Colly web scraping, HTML/XML query libraries, Glamour markdown rendering, text processing utilities.
6060+6161+**Utilities** - UUID generation, time handling, logging through `charmbracelet/log`.
6262+6363+## Design Decisions and Tradeoffs
6464+6565+### Technology Choices
6666+6767+**Go over Rust** - Go was selected for its simplicity, excellent CLI ecosystem (Cobra, Charm libraries), and faster development velocity. While Rust + Ratatui would provide better memory safety and potentially superior performance, Go's straightforward concurrency model and mature tooling ecosystem made it the pragmatic choice for rapid prototyping and iteration.
6868+6969+**SQLite over PostgreSQL** - SQLite provides zero-configuration deployment and sufficient performance for single-user CLI applications. The embedded database eliminates setup complexity while supporting full SQL features needed for filtering and querying. PostgreSQL would add deployment overhead without meaningful benefits for this use case.
7070+7171+**Repository Pattern over Active Record** - Repository interfaces enable clean separation between business logic and data access, facilitating testing through dependency injection. This pattern scales better than Active Record for complex domain logic while maintaining clear boundaries between layers.
7272+7373+### Architectural Tradeoffs
7474+7575+**CommandGroup Interface** - Centralizes command registration while enabling modular command organization. The pattern requires additional abstraction but provides consistent dependency injection and testing capabilities across all command groups.
7676+7777+**Handler-based Business Logic** - Business logic in handlers rather than rich domain models keeps the codebase simple and avoids over-engineering. While this approach may not scale to complex business rules, it provides clear separation of concerns for the current feature set.
7878+7979+**Dual Storage for Articles** - Articles store both markdown and HTML versions to balance processing speed with format flexibility. This doubles storage requirements but eliminates runtime conversion overhead and preserves original formatting.
8080+8181+### Component Interactions
8282+8383+**Handler โ Repository โ Database** - Request flow follows a linear path from CLI commands through business logic to data persistence. This pattern ensures consistent validation and error handling while maintaining clear separation of concerns.
8484+8585+**TUI State Management** - Bubbletea's unidirectional data flow provides predictable state updates for interactive components. The model-view-update pattern ensures consistent UI behavior across different terminal environments.
8686+8787+**Configuration and Migration** - Application startup validates configuration and runs database migrations before initializing handlers. This fail-fast approach prevents runtime errors and ensures consistent database schema across deployments.
+263
docs/dev/TESTING.md
···11+# Testing Documentation
22+33+This document outlines the testing patterns and practices used in the `noteleaf` application.
44+55+## Overview
66+77+The codebase follows Go's standard testing practices with specialized testing utilities for complex scenarios. Tests use the standard library along with carefully selected dependencies like faker for data generation and BubbleTea for TUI testing. This approach keeps dependencies minimal while providing robust testing infrastructure for interactive components and complex integrations.
88+99+### Organization
1010+1111+Each package contains its own test files alongside the source code. Test files are organized by functionality and mirror the structure of the source code they test. The codebase includes four main test utility files that provide specialized testing infrastructure:
1212+1313+- `internal/services/test_utilities.go` - HTTP mocking and media service testing
1414+- `internal/repo/test_utilities.go` - Database testing and data generation
1515+- `internal/ui/test_utilities.go` - TUI testing framework and interactive component testing
1616+- `internal/handlers/test_utilities.go` - Handler testing with database isolation and input simulation
1717+1818+## Patterns
1919+2020+### Handler Creation
2121+2222+Tests create real handler instances using temporary databases to ensure test isolation. Factory functions handle both database setup and handler initialization, returning both the handler and a cleanup function.
2323+2424+### Database Isolation
2525+2626+Tests use temporary directories and environment variable manipulation to create isolated database instances. Each test gets its own temporary SQLite database that is automatically cleaned up after the test completes.
2727+2828+The `setupCommandTest` function creates a temporary directory, sets `XDG_CONFIG_HOME` to point to it, and initializes the database schema. This ensures tests don't interfere with each other or with development data.
2929+3030+### Resource Management
3131+3232+Tests properly manage resources using cleanup functions returned by factory methods. The cleanup function handles both handler closure and temporary directory removal. This pattern ensures complete resource cleanup even if tests fail.
3333+3434+### Error Handling
3535+3636+Tests use `t.Fatal` for setup errors that prevent test execution and `t.Error` for test assertion failures. Fatal errors stop test execution while errors allow tests to continue checking other conditions.
3737+3838+### Context Cancellation
3939+4040+Error case testing frequently uses context cancellation to simulate database and network failures. The pattern creates a context, immediately cancels it, then calls the function under test to verify error handling. This provides a reliable way to test error paths without requiring complex mock setups or external failure injection.
4141+4242+### Command Structure
4343+4444+Command group tests verify cobra command structure including use strings, aliases, short descriptions, and subcommand presence. Tests check that commands are properly configured without executing their logic.
4545+4646+### Interface Compliance
4747+4848+Tests verify interface compliance using compile-time checks with blank identifier assignments. This ensures structs implement expected interfaces without runtime overhead.
4949+5050+## Test Infrastructure
5151+5252+### Test Utility Frameworks
5353+5454+The codebase provides comprehensive testing utilities organized by layer and functionality. Each test utility file contains specialized helpers, mocks, and test infrastructure for its respective domain.
5555+5656+#### Database Testing Utilities
5757+5858+`internal/repo/test_utilities.go` provides comprehensive database testing infrastructure:
5959+6060+- **In-Memory Database Creation**: `CreateTestDB` creates isolated SQLite databases with full schema
6161+- **Sample Data Factories**: Functions like `CreateSampleTask`, `CreateSampleBook` generate realistic test data
6262+- **Faker Integration**: Uses jaswdr/faker for generating realistic fake data with `CreateFakeArticle`
6363+- **Test Setup Helpers**: `SetupTestData` creates a full set of sample data across all models
6464+- **Custom Assertions**: Generic assertion helpers like `AssertEqual`, `AssertContains`, `AssertNoError`
6565+6666+#### HTTP Service Testing
6767+6868+`internal/services/test_utilities.go` provides HTTP mocking and media service testing:
6969+7070+- **Mock Configuration**: `MockConfig` structure for configuring service behavior
7171+- **Function Replacement**: `SetupMediaMocks` replaces service functions with controllable mocks
7272+- **Sample Data Access**: Helper functions that use embedded HTML samples for realistic testing
7373+- **Specialized Scenarios**: Pre-configured mock setups for success and failure scenarios
7474+- **Assertion Helpers**: Domain-specific assertions for movies, TV shows, and error conditions
7575+7676+#### TUI Testing Framework
7777+7878+`internal/ui/test_utilities.go` provides a comprehensive BubbleTea testing framework:
7979+8080+- **TUITestSuite**: Complete testing infrastructure for interactive TUI components
8181+- **Controlled I/O**: `ControlledOutput` and `ControlledInput` for deterministic testing
8282+- **Message Simulation**: Key press simulation, message queuing, and timing control
8383+- **State Verification**: Model state checking and view content assertions
8484+- **Timeout Handling**: Configurable timeouts for async operations
8585+- **Mock Repository**: Test doubles for repository interfaces
8686+8787+#### Handler Testing Infrastructure
8888+8989+`internal/handlers/test_utilities.go` provides end-to-end handler testing:
9090+9191+- **Environment Isolation**: `HandlerTestHelper` creates isolated test environments
9292+- **Input Simulation**: `InputSimulator` for testing interactive components that use `fmt.Scanf`
9393+- **HTTP Mocking**: Comprehensive HTTP server mocking for external API testing
9494+- **Database Helpers**: Database corruption and error scenario testing
9595+- **Editor Mocking**: `MockEditor` for testing file editing workflows
9696+- **Assertion Helpers**: Handler-specific assertions and verification functions
9797+9898+### Advanced Testing Patterns
9999+100100+#### Input Simulation for Interactive Components
101101+102102+Interactive handlers that use `fmt.Scanf` require special testing infrastructure with an `io.Reader` implementation.
103103+104104+The `InputSimulator` provides controlled input sequences that prevent tests from hanging while maintaining coverage of interactive code paths.
105105+106106+#### TUI Testing with BubbleTea Framework
107107+108108+The TUI testing framework addresses the fundamental challenge of testing interactive terminal applications in a deterministic, concurrent environment. BubbleTea's message-passing architecture creates unique testing requirements that standard Go testing patterns cannot adequately address.
109109+110110+The framework implements a controlled execution environment that replaces BubbleTea's typical program loop with a deterministic testing harness. Rather than running an actual terminal program, the "testing suite" directly manages model state transitions by simulating the Update/View cycle. This approach eliminates the non-deterministic behavior inherent in real terminal interactions while preserving the exact message flow patterns that production code experiences.
111111+112112+State verification relies on function composition patterns where test conditions are expressed as closures that capture specific model states. The `WaitFor` mechanism uses polling with configurable timeouts, addressing the async nature of BubbleTea model updates without creating race conditions. This pattern bridges imperative test assertions with BubbleTea's declarative update model.
113113+This is inspired by front-end/TS/JS testing patterns.
114114+115115+The framework's I/O abstraction layer replaces terminal input/output with controlled buffers that implement standard Go interfaces.
116116+This design maintains interface compatibility while providing complete control over timing and content. The controlled I/O system captures all output for later verification and injects precise input sequences, enabling complex interaction testing without external dependencies.
117117+118118+Concurrency management uses channels and context propagation to coordinate between the testing framework and the model under test.
119119+The suite manages goroutine lifecycle and ensures proper cleanup, preventing test interference and resource leaks. This architecture supports testing of models that perform background operations or handle async events.
120120+121121+#### HTTP Service Mocking
122122+123123+Service testing uses HTTP mocking with request capture. A `MockServer` is instantiated, and its URL is used in test scoped services.
124124+125125+#### Database Schema Testing
126126+127127+Database tests use comprehensive schema setup with (automatic) cleanup
128128+129129+#### Environment Manipulation
130130+131131+Environment testing utilities provide controlled environment manipulation. Environment variables are restored after instantiation.
132132+133133+## Test Organization Patterns
134134+135135+### Single Root Test
136136+137137+The preferred test organization pattern uses a single root test function with nested subtests using `t.Run`. This provides clear hierarchical organization and allows running specific test sections while maintaining shared setup and context. This pattern offers several advantages: clear test hierarchy with logical grouping, ability to run specific test sections, consistent test structure across the codebase, and shared setup that can be inherited by subtests.
138138+139139+### Integration vs Unit Testing
140140+141141+The codebase emphasizes integration testing over heavy mocking by using real handlers and services to verify actual behavior rather than mocked interactions. The goal is to catch integration issues while maintaining test reliability.
142142+143143+### Static Output
144144+145145+UI components support static output modes for testing. Tests capture output using bytes.Buffer and verify content using string contains checks rather than exact string matching for better test maintainability.
146146+147147+### Standard Output Redirection
148148+149149+For testing functions that write to stdout, tests use a pipe redirection pattern with goroutines to capture output. The pattern saves the original stdout, redirects to a pipe, captures output in a separate goroutine, and restores stdout after the test. This ensures clean output capture without interfering with the testing framework.
150150+151151+## Utilities
152152+153153+### Test Data Generation
154154+155155+The codebase uses sophisticated data generation strategies:
156156+157157+- **Factory Functions**: Each package provides factory functions for creating valid test data
158158+- **Faker Integration**: Uses `jaswdr/faker` for generating realistic fake data with proper randomization
159159+- **Sample Data Creators**: Functions like `CreateSampleTask`, `CreateSampleBook` provide consistent test data
160160+- **Embedded Resources**: Services use embedded HTML samples from real API responses for realistic testing
161161+162162+### Assertion Helpers
163163+164164+Custom assertion functions provide clear error messages and reduce test code duplication:
165165+166166+- **Generic Assertions**: `AssertEqual`, `AssertNoError`, `AssertContains` for common checks
167167+- **Domain-Specific Assertions**: `AssertMovieInResults`, `AssertNoteExists` for specialized verification
168168+- **TUI Assertions**: `AssertViewContains`, `AssertModelState` for BubbleTea model testing
169169+- **HTTP Assertions**: `AssertRequestMade` for verifying HTTP interactions
170170+171171+### Mock Infrastructure
172172+173173+Each layer provides specialized mocking capabilities:
174174+175175+- **Service Mocking**: Function replacement with configurable behavior and embedded test data
176176+- **HTTP Mocking**: `HTTPMockServer` with request capture and response customization
177177+- **Input Mocking**: `InputSimulator` for deterministic interactive component testing
178178+- **Editor Mocking**: `MockEditor` for file editing workflow testing
179179+- **Repository Mocking**: `MockTaskRepository` for TUI component testing
180180+181181+### Environment and Resource Management
182182+183183+Testing utilities provide comprehensive resource management:
184184+185185+- **Environment Isolation**: `EnvironmentTestHelper` for controlled environment variable manipulation
186186+- **Database Isolation**: Temporary SQLite databases with automatic cleanup
187187+- **File System Isolation**: Temporary directories with automatic cleanup
188188+- **Process Isolation**: Handler helpers that create completely isolated test environments
189189+190190+## Testing CLI Commands
191191+192192+Command group tests focus on structure verification rather than execution testing. Tests check command configuration, subcommand presence, and interface compliance. This approach ensures command trees are properly constructed without requiring complex execution mocking.
193193+194194+### CommandGroup Interface Testing
195195+196196+The CommandGroup interface enables testable CLI architecture. Tests verify that command groups implement the interface correctly and return properly configured cobra commands. This pattern separates command structure from command execution.
197197+198198+Interface compliance is tested using compile-time checks within the "Interface Implementations" subtest, ensuring all command structs properly implement the CommandGroup interface without runtime overhead.
199199+200200+## Performance Considerations
201201+202202+Tests avoid expensive operations in setup functions. Handler creation uses real instances but tests focus on structure verification rather than full execution paths. This keeps test suites fast while maintaining coverage of critical functionality.
203203+204204+The single root test pattern allows for efficient resource management where setup costs can be amortized across multiple related test cases.
205205+206206+## Interactive Component Testing
207207+208208+The codebase provides comprehensive testing infrastructure for interactive components, including both terminal UI applications and command-line interfaces that require user input.
209209+210210+### Input Simulation Framework
211211+212212+Interactive handlers that use `fmt.Scanf` require specialized testing infrastructure:
213213+214214+- **InputSimulator**: Provides controlled input sequences that implement `io.Reader`
215215+- **Menu Selection Helpers**: `MenuSelection`, `MenuCancel`, `MenuSequence` for common interaction patterns
216216+- **Handler Integration**: Handlers can accept `io.Reader` for input, enabling deterministic testing
217217+- **Cleanup Management**: Automatic cleanup prevents resource leaks in test environments
218218+219219+### TUI Testing with BubbleTea
220220+221221+The TUI testing framework provides complete testing infrastructure for interactive terminal interfaces:
222222+223223+- **TUITestSuite**: Comprehensive testing framework for BubbleTea models
224224+- **Message Simulation**: Key press simulation, window resize events, and custom message handling
225225+- **State Verification**: Model state checking with custom condition functions
226226+- **View Assertions**: Content verification and output capture
227227+- **Timing Control**: Configurable timeouts and delay handling for async operations
228228+- **Mock Integration**: Repository mocking for isolated component testing
229229+230230+### Interactive Test Scenarios
231231+232232+Interactive handlers should test comprehensive scenarios:
233233+234234+- **Valid user selections** - User chooses valid menu options and inputs
235235+- **Cancellation flows** - User chooses to cancel operations (option 0 or escape keys)
236236+- **Invalid choices** - User selects out-of-range options or provides invalid input
237237+- **Navigation patterns** - Keyboard navigation, scrolling, and multi-step interactions
238238+- **Error handling** - Network errors, service failures, and data validation errors
239239+- **Empty states** - Search returns no results, empty lists, and missing data
240240+- **Edge cases** - Boundary conditions, malformed input, and resource constraints
241241+242242+### TUI Component Testing Patterns
243243+244244+BubbleTea components use specialized testing patterns:
245245+246246+- **Key Sequence Testing**: Simulate complex user interactions with timing
247247+- **State Transition Testing**: Verify model state changes through user actions
248248+- **View Content Testing**: Assert specific content appears in rendered output
249249+- **Async Operation Testing**: Handle loading states and network operations
250250+- **Responsive Design Testing**: Test different terminal sizes and window resize handling
251251+252252+This comprehensive testing approach ensures interactive components work reliably in automated environments while maintaining full coverage of user interaction paths.
253253+254254+## Errors
255255+256256+Error coverage follows a systematic approach to identify and test failure scenarios:
257257+258258+1. **Context Cancellation** - Primary method for testing database and network timeout scenarios
259259+2. **Invalid Input** - Malformed data, empty inputs, boundary conditions
260260+3. **Resource Exhaustion** - Database connection failures, memory limits
261261+4. **Constraint Violations** - Duplicate keys, foreign key failures
262262+5. **State Validation** - Testing functions with invalid system states
263263+6. **Interactive Input** - Invalid user choices, cancellation handling, input simulation errors
-114
docs/testing.md
···11-# Testing Documentation
22-33-This document outlines the testing patterns and practices used in the `noteleaf` application.
44-55-## Overview
66-77-The codebase follows Go's standard testing practices without external libraries. Tests use only the standard library package and avoid mock frameworks or assertion libraries. This is to keep dependencies minimal and tests readable using standard Go patterns.
88-99-### Organization
1010-1111-Each package contains its own test files alongside the source code. Test files are organized by functionality and mirror the structure of the source code they test.
1212-1313-## Patterns
1414-1515-### Handler Creation Pattern
1616-1717-Tests create real handler instances using temporary databases to ensure test isolation. Factory functions handle both database setup and handler initialization, returning both the handler and a cleanup function.
1818-1919-### Database Isolation
2020-2121-Tests use temporary directories and environment variable manipulation to create isolated database instances. Each test gets its own temporary SQLite database that is automatically cleaned up after the test completes.
2222-2323-The `setupCommandTest` function creates a temporary directory, sets `XDG_CONFIG_HOME` to point to it, and initializes the database schema. This ensures tests don't interfere with each other or with development data.
2424-2525-### Resource Management
2626-2727-Tests properly manage resources using cleanup functions returned by factory methods. The cleanup function handles both handler closure and temporary directory removal. This pattern ensures complete resource cleanup even if tests fail.
2828-2929-### Error Handling
3030-3131-Tests use `t.Fatal` for setup errors that prevent test execution and `t.Error` for test assertion failures. Fatal errors stop test execution while errors allow tests to continue checking other conditions.
3232-3333-### Context Cancellation Testing Pattern
3434-3535-Error case testing frequently uses context cancellation to simulate database and network failures. The pattern creates a context, immediately cancels it, then calls the function under test to verify error handling. This provides a reliable way to test error paths without requiring complex mock setups or external failure injection.
3636-3737-### Command Structure Testing
3838-3939-Command group tests verify cobra command structure including use strings, aliases, short descriptions, and subcommand presence. Tests check that commands are properly configured without executing their logic.
4040-4141-### Interface Compliance Testing
4242-4343-Tests verify interface compliance using compile-time checks with blank identifier assignments. This ensures structs implement expected interfaces without runtime overhead.
4444-4545-## Test Organization Patterns
4646-4747-### Single Root Test
4848-4949-The preferred test organization pattern uses a single root test function with nested subtests using `t.Run`. This provides clear hierarchical organization and allows running specific test sections while maintaining shared setup and context. This pattern offers several advantages: clear test hierarchy with logical grouping, ability to run specific test sections, consistent test structure across the codebase, and shared setup that can be inherited by subtests.
5050-5151-### Integration vs Unit Testing
5252-5353-The codebase emphasizes integration testing over heavy mocking by using real handlers and services to verify actual behavior rather than mocked interactions. The goal is to catch integration issues while maintaining test reliability.
5454-5555-### Static Output
5656-5757-UI components support static output modes for testing. Tests capture output using bytes.Buffer and verify content using string contains checks rather than exact string matching for better test maintainability.
5858-5959-### Standard Output Redirection
6060-6161-For testing functions that write to stdout, tests use a pipe redirection pattern with goroutines to capture output. The pattern saves the original stdout, redirects to a pipe, captures output in a separate goroutine, and restores stdout after the test. This ensures clean output capture without interfering with the testing framework.
6262-6363-## Utilities
6464-6565-### Helpers
6666-6767-Test files include helper functions for creating test data and finding elements in collections. These utilities reduce code duplication and improve test readability.
6868-6969-### Mock Data
7070-7171-Tests create realistic mock data using factory functions (powered by faker) that return properly initialized structs with sensible defaults.
7272-7373-## Testing CLI Commands
7474-7575-Command group tests focus on structure verification rather than execution testing. Tests check command configuration, subcommand presence, and interface compliance. This approach ensures command trees are properly constructed without requiring complex execution mocking.
7676-7777-### CommandGroup Interface Testing
7878-7979-The CommandGroup interface enables testable CLI architecture. Tests verify that command groups implement the interface correctly and return properly configured cobra commands. This pattern separates command structure from command execution.
8080-8181-Interface compliance is tested using compile-time checks within the "Interface Implementations" subtest, ensuring all command structs properly implement the CommandGroup interface without runtime overhead.
8282-8383-## Performance Considerations
8484-8585-Tests avoid expensive operations in setup functions. Handler creation uses real instances but tests focus on structure verification rather than full execution paths. This keeps test suites fast while maintaining coverage of critical functionality.
8686-8787-The single root test pattern allows for efficient resource management where setup costs can be amortized across multiple related test cases.
8888-8989-## Interactive Component Testing
9090-9191-Interactive components that use `fmt.Scanf` for user input require special testing infrastructure to prevent tests from hanging while waiting for stdin.
9292-9393-### Testing Success Scenarios
9494-9595-Interactive handlers should test both success and error paths:
9696-9797-- **Valid user selections** - User chooses valid menu options
9898-- **Cancellation** - User chooses to cancel (option 0)
9999-- **Invalid choices** - User selects out-of-range options
100100-- **Empty results** - Search returns no results
101101-- **Network errors** - Service calls fail
102102-103103-This ensures tests run reliably in automated environments while maintaining coverage of the non-interactive code paths.
104104-105105-## Errors
106106-107107-Error coverage follows a systematic approach to identify and test failure scenarios:
108108-109109-1. **Context Cancellation** - Primary method for testing database and network timeout scenarios
110110-2. **Invalid Input** - Malformed data, empty inputs, boundary conditions
111111-3. **Resource Exhaustion** - Database connection failures, memory limits
112112-4. **Constraint Violations** - Duplicate keys, foreign key failures
113113-5. **State Validation** - Testing functions with invalid system states
114114-6. **Interactive Input** - Invalid user choices, cancellation handling, input simulation errors