Files
thechart/docs/DEVELOPMENT.md
William Valentin 33d7ae8d9f feat: Remove outdated testing documentation and add comprehensive development and feature guides
- Deleted `TESTING_SETUP.md` and `TEST_UPDATES_SUMMARY.md` as they were outdated.
- Introduced `CHANGELOG.md` to document notable changes and version history.
- Added `DEVELOPMENT.md` for detailed development setup, testing framework, and debugging guidance.
- Created `FEATURES.md` to outline core features and functionalities of TheChart.
- Established `README.md` as a centralized documentation index for users and developers.
2025-07-31 11:39:12 -07:00

341 lines
9.9 KiB
Markdown

# TheChart - Development Documentation
## Development Environment Setup
### Prerequisites
- **Python 3.13+**: Required for the application
- **uv**: Fast Python package manager (10-100x faster than pip/Poetry)
- **Git**: Version control
### Quick Setup
```bash
# Clone and setup
git clone <repository-url>
cd thechart
# Install with uv (recommended)
make install
# Or manual setup
uv venv --python 3.13
uv sync
uv run pre-commit install --install-hooks --overwrite
```
### Environment Activation
```bash
# fish shell (default)
source .venv/bin/activate.fish
# or
make shell
# bash/zsh
source .venv/bin/activate
# Using uv run (recommended)
uv run python src/main.py
```
## Testing Framework
### Test Infrastructure
Professional testing setup with comprehensive coverage and automation.
#### Testing Tools
- **pytest**: Modern Python testing framework
- **pytest-cov**: Coverage reporting (HTML, XML, terminal)
- **pytest-mock**: Mocking support for isolated testing
- **coverage**: Detailed coverage analysis
#### Test Statistics
- **93% Overall Code Coverage** (482 total statements, 33 missed)
- **112 Total Tests** across 6 test modules
- **80 Tests Passing** (71.4% pass rate)
#### Coverage by Module
| Module | Coverage | Status |
|--------|----------|--------|
| constants.py | 100% | ✅ Complete |
| logger.py | 100% | ✅ Complete |
| graph_manager.py | 97% | ✅ Excellent |
| init.py | 95% | ✅ Excellent |
| ui_manager.py | 93% | ✅ Very Good |
| main.py | 91% | ✅ Very Good |
| data_manager.py | 87% | ✅ Good |
### Test Structure
#### Test Files
- **`tests/test_data_manager.py`** (16 tests): CSV operations, validation, error handling
- **`tests/test_graph_manager.py`** (14 tests): Matplotlib integration, dose calculations
- **`tests/test_ui_manager.py`** (21 tests): Tkinter UI components, user interactions
- **`tests/test_main.py`** (18 tests): Application integration, workflow testing
- **`tests/test_constants.py`** (12 tests): Configuration validation
- **`tests/test_logger.py`** (8 tests): Logging functionality
- **`tests/test_init.py`** (23 tests): Initialization and setup
#### Test Fixtures (`tests/conftest.py`)
- **Temporary Files**: Safe testing without affecting real data
- **Sample Data**: Comprehensive test datasets with realistic dose information
- **Mock Loggers**: Isolated logging for testing
- **Environment Mocking**: Controlled test environments
### Running Tests
#### Basic Testing
```bash
# Run all tests
make test
# or
uv run pytest
# Run specific test file
uv run pytest tests/test_graph_manager.py -v
# Run tests with specific pattern
uv run pytest -k "dose_calculation" -v
```
#### Coverage Testing
```bash
# Generate coverage report
uv run pytest --cov=src --cov-report=html
# Coverage with specific module
uv run pytest tests/test_graph_manager.py --cov=src.graph_manager --cov-report=term-missing
```
#### Continuous Testing
```bash
# Watch for changes and re-run tests
uv run pytest --watch
# Quick test runner script
./scripts/run_tests.py
```
### Pre-commit Testing
Automated testing prevents commits when core functionality is broken.
#### Configuration
Located in `.pre-commit-config.yaml`:
- **Core Tests**: 3 essential tests run before each commit
- **Fast Execution**: Only critical functionality tested
- **Commit Blocking**: Prevents commits when tests fail
#### Core Tests
1. **`test_init`**: DataManager initialization
2. **`test_initialize_csv_creates_file_with_headers`**: CSV file creation
3. **`test_load_data_with_valid_data`**: Data loading functionality
#### Usage
```bash
# Automatic on commit
git commit -m "Your changes"
# Manual pre-commit check
pre-commit run --all-files
# Run just test check
pre-commit run pytest-check --all-files
```
### Dose Calculation Testing
Comprehensive testing for the complex dose parsing and calculation system.
#### Test Categories
- **Standard Format**: `2025-07-28 18:59:45:150mg` → 150.0mg
- **Multiple Doses**: `2025-07-28 18:59:45:150mg|2025-07-28 19:34:19:75mg` → 225.0mg
- **With Symbols**: `• • • • 2025-07-30 07:50:00:300` → 300.0mg
- **Decimal Values**: `2025-07-28 18:59:45:12.5mg|2025-07-28 19:34:19:7.5mg` → 20.0mg
- **No Timestamps**: `100mg|50mg` → 150.0mg
- **Mixed Formats**: `• 2025-07-30 22:50:00:10|75mg` → 85.0mg
- **Edge Cases**: Empty strings, NaN values, malformed data → 0.0mg
#### Test Implementation
```python
# Example test case
def test_calculate_daily_dose_standard_format(self, graph_manager):
dose_str = "2025-07-28 18:59:45:150mg|2025-07-28 19:34:19:75mg"
result = graph_manager._calculate_daily_dose(dose_str)
assert result == 225.0
```
### Medicine Plotting Tests
Testing for the enhanced graph functionality with medicine dose visualization.
#### Test Areas
- **Toggle Functionality**: Medicine show/hide controls
- **Dose Plotting**: Bar chart generation for medicine doses
- **Color Coding**: Proper color assignment and consistency
- **Legend Enhancement**: Multi-column layout and average calculations
- **Data Integration**: Proper data flow from CSV to visualization
### UI Testing Strategy
Testing user interface components with mock frameworks to avoid GUI dependencies.
#### UI Test Coverage
- **Component Creation**: Widget creation and configuration
- **Event Handling**: User interactions and callbacks
- **Data Binding**: Variable synchronization and updates
- **Layout Management**: Grid and frame arrangements
- **Error Handling**: User input validation and error messages
#### Mocking Strategy
```python
# Example UI test with mocking
@patch('tkinter.Tk')
def test_create_input_frame(self, mock_tk, ui_manager):
parent = Mock()
result = ui_manager.create_input_frame(parent, {}, {})
assert result is not None
assert isinstance(result, dict)
```
## Code Quality
### Tools and Standards
- **ruff**: Fast Python linter and formatter (Rust-based)
- **pre-commit**: Git hook management for code quality
- **Type Hints**: Comprehensive type annotations
- **Docstrings**: Detailed function and class documentation
### Code Formatting
```bash
# Format code
make format
# or
uv run ruff format .
# Check formatting
make lint
# or
uv run ruff check .
```
### Pre-commit Hooks
Automatically installed hooks ensure code quality:
- **Code Formatting**: ruff formatting
- **Linting Checks**: Code quality validation
- **Import Sorting**: Consistent import organization
- **Basic File Checks**: Trailing whitespace, file endings
## Development Workflow
### Feature Development
1. **Create Feature Branch**: `git checkout -b feature/new-feature`
2. **Implement Changes**: Follow existing patterns and architecture
3. **Add Tests**: Ensure new functionality is tested
4. **Run Tests**: `make test` to verify functionality
5. **Code Quality**: `make format && make lint`
6. **Commit Changes**: Pre-commit hooks run automatically
7. **Create Pull Request**: For code review
### Medicine System Development
Adding new medicines or modifying the medicine system:
```python
# Example: Adding a new medicine programmatically
from medicine_manager import MedicineManager, Medicine
medicine_manager = MedicineManager()
new_medicine = Medicine(
key="sertraline",
display_name="Sertraline",
dosage_info="50mg",
quick_doses=["25", "50", "100"],
color="#9B59B6",
default_enabled=False
)
medicine_manager.add_medicine(new_medicine)
```
### Testing New Features
1. **Unit Tests**: Add tests for new functionality
2. **Integration Tests**: Test feature integration with existing system
3. **UI Tests**: Test user interface changes
4. **Dose Calculation Tests**: If affecting dose calculations
5. **Regression Tests**: Ensure existing functionality still works
## Debugging and Troubleshooting
### Logging
Application logs are stored in `logs/` directory:
- **`app.log`**: General application logs
- **`app.error.log`**: Error messages only
- **`app.warning.log`**: Warning messages only
### Debug Mode
Enable debug logging by modifying `src/logger.py` configuration.
### Common Issues
#### Test Failures
- **Matplotlib Mocking**: Ensure proper matplotlib component mocking
- **Tkinter Dependencies**: Use headless testing for UI components
- **File Path Issues**: Use absolute paths in tests
- **Mock Configuration**: Proper mock setup for external dependencies
#### Development Environment
- **Python Version**: Ensure Python 3.13+ is used
- **Virtual Environment**: Always work within the virtual environment
- **Dependencies**: Keep dependencies up to date with `uv sync --upgrade`
### Performance Testing
- **Dose Calculation Performance**: Test with large datasets
- **UI Responsiveness**: Test with extensive medicine lists
- **Memory Usage**: Monitor memory consumption with large CSV files
- **Graph Rendering**: Test graph performance with large datasets
## Architecture Documentation
### Core Components
- **MedTrackerApp**: Main application class
- **MedicineManager**: Medicine CRUD operations
- **PathologyManager**: Pathology/symptom management
- **GraphManager**: Visualization and plotting
- **UIManager**: User interface creation
- **DataManager**: Data persistence and CSV operations
### Data Flow
1. **User Input** → UIManager → DataManager → CSV
2. **Data Loading** → DataManager → pandas DataFrame → GraphManager
3. **Visualization** → GraphManager → matplotlib → UI Display
### Extension Points
- **Medicine System**: Add new medicine properties
- **Graph Types**: Add new visualization types
- **Export Formats**: Add new data export options
- **UI Components**: Add new interface elements
## Deployment Testing
### Standalone Executable
```bash
# Build executable
make deploy
# Test deployment
./dist/thechart
```
### Docker Testing
```bash
# Build container
make build
# Test container
make start
make attach
```
### Cross-platform Testing
- **Linux**: Primary development and testing platform
- **macOS**: Planned support (testing needed)
- **Windows**: Planned support (testing needed)
---
For user documentation, see [README.md](../README.md).
For feature details, see [docs/FEATURES.md](FEATURES.md).