Add quick test runner and enhance run_tests script
Build and Push Docker Image / build-and-push (push) Has been cancelled

- Introduced `quick_test.py` for running specific test categories (unit, integration, theme, all).
- Updated `run_tests.py` to improve test execution and reporting, including coverage.
- Removed outdated test scripts for keyboard shortcuts, menu theming, note saving, and entry updating.
- Added new test script `test_theme_changing.py` to verify theme changing functionality.
- Consolidated integration tests into `test_integration.py` for comprehensive testing of TheChart application.
- Updated theme manager to ensure color retrieval works correctly.
- Modified test constants to import from the correct module path.
This commit is contained in:
William Valentin
2025-08-05 15:09:13 -07:00
parent df9738ab17
commit a521ed6e9a
46 changed files with 8325 additions and 1131 deletions
+162 -96
View File
@@ -1,110 +1,176 @@
# TheChart Scripts Directory
This directory contains interactive demonstrations and utility scripts for TheChart application.
This directory contains utility scripts and the **new consolidated test suite** for TheChart application.
## Scripts Overview
## 🚀 Quick Start
### Testing Scripts
#### `run_tests.py`
Main test runner for the application.
### Run All Tests
```bash
cd /home/will/Code/thechart
.venv/bin/python scripts/run_tests.py
```
#### `integration_test.py`
Comprehensive integration test for the export system.
- Tests all export formats (JSON, XML, PDF)
- Validates data integrity and file creation
- No GUI dependencies - safe for automated testing
### Run Specific Test Categories
```bash
cd /home/will/Code/thechart
# Unit tests only
.venv/bin/python scripts/quick_test.py unit
# Integration tests only
.venv/bin/python scripts/quick_test.py integration
# Theme-related tests only
.venv/bin/python scripts/quick_test.py theme
```
## 📁 Current Structure
### Active Scripts
#### `run_tests.py` 🎯
**Main test runner** - executes the complete test suite with coverage reporting.
- Runs unit tests with coverage
- Runs integration tests
- Runs legacy integration tests for backwards compatibility
- Provides comprehensive test summary
#### `quick_test.py` ⚡
**Quick test runner** - for specific test categories during development.
- `unit` - Fast unit tests only
- `integration` - Integration tests only
- `theme` - Theme-related functionality tests
- `all` - Complete test suite
#### `integration_test.py` 🔄
**Legacy integration test** - maintained for backwards compatibility.
- Tests export system functionality
- No GUI dependencies
- Called automatically by the main test runner
### Test Organization
#### Unit Tests (`/tests/`)
- `test_*.py` - Individual module tests
- Uses pytest framework
- Fast execution, isolated tests
- Coverage reporting enabled
#### Integration Tests (`tests/test_integration.py`)
- **Consolidated integration test suite**
- Tests complete workflows and interactions
- Includes functionality from old standalone scripts:
- Note saving and retrieval
- Entry updates and validation
- Theme changing functionality
- Keyboard shortcuts binding
- Menu theming integration
- Export system testing
- Data validation and error handling
## 🔄 Migration from Old Structure
The old individual test scripts have been **consolidated** into the unified test suite:
| Old Script | New Location | How to Run |
|------------|--------------|------------|
| `test_note_saving.py` | `tests/test_integration.py::test_note_saving_functionality` | `quick_test.py integration` |
| `test_update_entry.py` | `tests/test_integration.py::test_entry_update_functionality` | `quick_test.py integration` |
| `test_keyboard_shortcuts.py` | `tests/test_integration.py::test_keyboard_shortcuts_binding` | `quick_test.py integration` |
| `test_theme_changing.py` | `tests/test_integration.py::test_theme_changing_functionality` | `quick_test.py theme` |
| `test_menu_theming.py` | `tests/test_integration.py::test_menu_theming_integration` | `quick_test.py theme` |
### Benefits of New Structure
1. **Unified Framework**: All tests use pytest
2. **Better Organization**: Related tests grouped logically
3. **Improved Performance**: Optimized setup/teardown
4. **Coverage Reporting**: Integrated coverage analysis
5. **CI/CD Ready**: Easier automation and integration
## 🛠️ Development Workflow
### During Development
```bash
# Quick unit tests (fastest feedback)
.venv/bin/python scripts/quick_test.py unit
# Test specific functionality
.venv/bin/python scripts/quick_test.py theme
```
### Before Commits
```bash
# Full test suite with coverage
.venv/bin/python scripts/run_tests.py
```
### Individual Test Debugging
```bash
# Run specific test with output
.venv/bin/python -m pytest tests/test_integration.py::TestIntegrationSuite::test_theme_changing_functionality -v -s
# Run with debugger
.venv/bin/python -m pytest tests/test_integration.py::TestIntegrationSuite::test_note_saving_functionality -v -s --pdb
```
## 📋 Available Test Categories
### Unit Tests
- Fast, isolated component tests
- Mock external dependencies
- Test individual functions and classes
### Integration Tests
- Test component interactions
- Test complete workflows
- Validate data persistence
- Test UI functionality (without GUI display)
### Theme Tests
- Theme switching functionality
- Color scheme validation
- Menu theming consistency
- Error handling in theme system
### System Health Checks
- Configuration file validation
- Manager initialization tests
- Logging system verification
## 🏃‍♂️ Performance Tips
- Use `quick_test.py unit` for fastest feedback during development
- Use `quick_test.py integration` to test workflow changes
- Use `quick_test.py theme` when working on UI/theming
- Use `run_tests.py` for comprehensive testing before commits
## 🔧 Debugging Tests
### Common Commands
```bash
# Run with verbose output
.venv/bin/python -m pytest tests/ -v
# Stop on first failure
.venv/bin/python -m pytest tests/ -x
# Show local variables on failure
.venv/bin/python -m pytest tests/ -l
# Run with debugger on failure
.venv/bin/python -m pytest tests/ --pdb
```
### Debugging Specific Issues
```bash
# Debug theme issues
.venv/bin/python -m pytest tests/test_integration.py::TestIntegrationSuite::test_theme_changing_functionality -v -s
# Debug data management
.venv/bin/python -m pytest tests/test_data_manager.py -v -s
# Debug export functionality
.venv/bin/python scripts/integration_test.py
```
### Feature Testing Scripts
---
#### `test_note_saving.py`
Tests note saving and retrieval functionality.
- Validates note persistence in CSV files
- Tests special characters and formatting
#### `test_update_entry.py`
Tests entry update functionality.
- Validates data modification operations
- Tests date validation and duplicate handling
#### `test_keyboard_shortcuts.py`
Tests keyboard shortcut functionality.
- Validates keyboard event handling
- Tests shortcut combinations and responses
### Interactive Demonstrations
#### `test_menu_theming.py`
Interactive demonstration of menu theming functionality.
- Live theme switching demonstration
- Visual display of theme colors
- Real-time menu color updates
```bash
cd /home/will/Code/thechart
.venv/bin/python scripts/test_menu_theming.py
```
## Usage
All scripts should be run from the project root directory using the virtual environment:
```bash
cd /home/will/Code/thechart
source .venv/bin/activate.fish # For fish shell
# OR
source .venv/bin/activate # For bash/zsh
python scripts/<script_name>.py
```
## Test Organization
### Unit Tests
Located in `/tests/` directory:
- `test_theme_manager.py` - Theme manager functionality tests
- `test_data_manager.py` - Data management tests
- `test_ui_manager.py` - UI component tests
- `test_graph_manager.py` - Graph functionality tests
- And more...
Run unit tests with:
```bash
cd /home/will/Code/thechart
.venv/bin/python -m pytest tests/
```
### Integration Tests
Located in `/scripts/` directory:
- `integration_test.py` - Export system integration test
- Feature-specific test scripts
### Interactive Demos
Located in `/scripts/` directory:
- `test_menu_theming.py` - Menu theming demonstration
## Test Data
- Integration tests create temporary export files in `integration_test_exports/` (auto-cleaned)
- Test scripts use the main `thechart_data.csv` file unless specified otherwise
- No test data is committed to the repository
## Development
When adding new scripts:
1. Place them in this directory
2. Use the standard shebang: `#!/usr/bin/env python3`
3. Add proper docstrings and error handling
4. Update this README with script documentation
5. Follow the project's linting and formatting standards
6. For unit tests, place them in `/tests/` directory
7. For integration tests or demos, place them in `/scripts/` directory
📖 **See Also**: `TESTING_MIGRATION.md` for detailed migration information.
+110
View File
@@ -0,0 +1,110 @@
# TheChart Scripts Directory
This directory contains interactive demonstrations and utility scripts for TheChart application.
## Scripts Overview
### Testing Scripts
#### `run_tests.py`
Main test runner for the application.
```bash
cd /home/will/Code/thechart
.venv/bin/python scripts/run_tests.py
```
#### `integration_test.py`
Comprehensive integration test for the export system.
- Tests all export formats (JSON, XML, PDF)
- Validates data integrity and file creation
- No GUI dependencies - safe for automated testing
```bash
cd /home/will/Code/thechart
.venv/bin/python scripts/integration_test.py
```
### Feature Testing Scripts
#### `test_note_saving.py`
Tests note saving and retrieval functionality.
- Validates note persistence in CSV files
- Tests special characters and formatting
#### `test_update_entry.py`
Tests entry update functionality.
- Validates data modification operations
- Tests date validation and duplicate handling
#### `test_keyboard_shortcuts.py`
Tests keyboard shortcut functionality.
- Validates keyboard event handling
- Tests shortcut combinations and responses
### Interactive Demonstrations
#### `test_menu_theming.py`
Interactive demonstration of menu theming functionality.
- Live theme switching demonstration
- Visual display of theme colors
- Real-time menu color updates
```bash
cd /home/will/Code/thechart
.venv/bin/python scripts/test_menu_theming.py
```
## Usage
All scripts should be run from the project root directory using the virtual environment:
```bash
cd /home/will/Code/thechart
source .venv/bin/activate.fish # For fish shell
# OR
source .venv/bin/activate # For bash/zsh
python scripts/<script_name>.py
```
## Test Organization
### Unit Tests
Located in `/tests/` directory:
- `test_theme_manager.py` - Theme manager functionality tests
- `test_data_manager.py` - Data management tests
- `test_ui_manager.py` - UI component tests
- `test_graph_manager.py` - Graph functionality tests
- And more...
Run unit tests with:
```bash
cd /home/will/Code/thechart
.venv/bin/python -m pytest tests/
```
### Integration Tests
Located in `/scripts/` directory:
- `integration_test.py` - Export system integration test
- Feature-specific test scripts
### Interactive Demos
Located in `/scripts/` directory:
- `test_menu_theming.py` - Menu theming demonstration
## Test Data
- Integration tests create temporary export files in `integration_test_exports/` (auto-cleaned)
- Test scripts use the main `thechart_data.csv` file unless specified otherwise
- No test data is committed to the repository
## Development
When adding new scripts:
1. Place them in this directory
2. Use the standard shebang: `#!/usr/bin/env python3`
3. Add proper docstrings and error handling
4. Update this README with script documentation
5. Follow the project's linting and formatting standards
6. For unit tests, place them in `/tests/` directory
7. For integration tests or demos, place them in `/scripts/` directory
+58
View File
@@ -0,0 +1,58 @@
# Test Scripts Migration Notice
## ⚠️ Important: Test Structure Changed
The individual test scripts in this directory have been **consolidated** into a unified test suite.
### Old Structure (Deprecated)
- `test_note_saving.py`
- `test_update_entry.py`
- `test_keyboard_shortcuts.py`
- `test_theme_changing.py`
- `test_menu_theming.py`
### New Structure (Current)
All functionality is now in:
- `tests/test_integration.py` - Comprehensive integration tests
- `tests/test_*.py` - Unit tests for specific modules
- `scripts/run_tests.py` - Main test runner
- `scripts/quick_test.py` - Quick test runner for specific categories
### How to Run Tests
#### Run All Tests
```bash
cd /home/will/Code/thechart
.venv/bin/python scripts/run_tests.py
```
#### Run Specific Test Categories
```bash
# Unit tests only
.venv/bin/python scripts/quick_test.py unit
# Integration tests only
.venv/bin/python scripts/quick_test.py integration
# Theme-related tests only
.venv/bin/python scripts/quick_test.py theme
```
#### Run Individual Test Classes
```bash
# Run specific integration test
.venv/bin/python -m pytest tests/test_integration.py::TestIntegrationSuite::test_theme_changing_functionality -v
# Run all theme manager tests
.venv/bin/python -m pytest tests/test_theme_manager.py -v
```
### Migration Benefits
1. **Unified Structure**: All tests use the same pytest framework
2. **Better Organization**: Related tests grouped together
3. **Improved Coverage**: Integrated coverage reporting
4. **Faster Execution**: Optimized test setup and teardown
5. **Better CI/CD**: Easier to integrate with automated testing
### Backwards Compatibility
The old `integration_test.py` script is still available and called by the new test runner for backwards compatibility.
@@ -0,0 +1,27 @@
#!/usr/bin/env python3
"""
⚠️ DEPRECATED SCRIPT ⚠️
This script has been consolidated into the new unified test suite.
Please use the new testing structure instead:
For theme testing:
.venv/bin/python scripts/quick_test.py theme
For integration testing:
.venv/bin/python scripts/quick_test.py integration
For all tests:
.venv/bin/python scripts/run_tests.py
See TESTING_MIGRATION.md for full details.
"""
import sys
print("⚠️ This script is deprecated. Please use the new test structure.")
print("See TESTING_MIGRATION.md for migration instructions.")
sys.exit(1)
# Original script content below (preserved for reference):
# """ + content[content.find('"""'):] if '"""' in content else content + """
+27
View File
@@ -0,0 +1,27 @@
#!/usr/bin/env python3
"""
⚠️ DEPRECATED SCRIPT ⚠️
This script has been consolidated into the new unified test suite.
Please use the new testing structure instead:
For theme testing:
.venv/bin/python scripts/quick_test.py theme
For integration testing:
.venv/bin/python scripts/quick_test.py integration
For all tests:
.venv/bin/python scripts/run_tests.py
See TESTING_MIGRATION.md for full details.
"""
import sys
print("⚠️ This script is deprecated. Please use the new test structure.")
print("See TESTING_MIGRATION.md for migration instructions.")
sys.exit(1)
# Original script content below (preserved for reference):
# """ + content[content.find('"""'):] if '"""' in content else content + """
+27
View File
@@ -0,0 +1,27 @@
#!/usr/bin/env python3
"""
⚠️ DEPRECATED SCRIPT ⚠️
This script has been consolidated into the new unified test suite.
Please use the new testing structure instead:
For theme testing:
.venv/bin/python scripts/quick_test.py theme
For integration testing:
.venv/bin/python scripts/quick_test.py integration
For all tests:
.venv/bin/python scripts/run_tests.py
See TESTING_MIGRATION.md for full details.
"""
import sys
print("⚠️ This script is deprecated. Please use the new test structure.")
print("See TESTING_MIGRATION.md for migration instructions.")
sys.exit(1)
# Original script content below (preserved for reference):
# """ + content[content.find('"""'):] if '"""' in content else content + """
+27
View File
@@ -0,0 +1,27 @@
#!/usr/bin/env python3
"""
⚠️ DEPRECATED SCRIPT ⚠️
This script has been consolidated into the new unified test suite.
Please use the new testing structure instead:
For theme testing:
.venv/bin/python scripts/quick_test.py theme
For integration testing:
.venv/bin/python scripts/quick_test.py integration
For all tests:
.venv/bin/python scripts/run_tests.py
See TESTING_MIGRATION.md for full details.
"""
import sys
print("⚠️ This script is deprecated. Please use the new test structure.")
print("See TESTING_MIGRATION.md for migration instructions.")
sys.exit(1)
# Original script content below (preserved for reference):
# """ + content[content.find('"""'):] if '"""' in content else content + """
+371
View File
@@ -0,0 +1,371 @@
#!/usr/bin/env python3
"""
Test migration script - consolidates old standalone test scripts.
This script helps migrate from the old testing structure to the new consolidated one.
"""
import os
from pathlib import Path
def create_deprecated_notice():
"""Create a notice file about the test migration."""
notice = """# Test Scripts Migration Notice
## ⚠️ Important: Test Structure Changed
The individual test scripts in this directory have been **consolidated** into a unified
test suite.
### Old Structure (Deprecated)
- `test_note_saving.py`
- `test_update_entry.py`
- `test_keyboard_shortcuts.py`
- `test_theme_changing.py`
- `test_menu_theming.py`
### New Structure (Current)
All functionality is now in:
- `tests/test_integration.py` - Comprehensive integration tests
- `tests/test_*.py` - Unit tests for specific modules
- `scripts/run_tests.py` - Main test runner
- `scripts/quick_test.py` - Quick test runner for specific categories
### How to Run Tests
#### Run All Tests
```bash
cd /home/will/Code/thechart
.venv/bin/python scripts/run_tests.py
```
#### Run Specific Test Categories
```bash
# Unit tests only
.venv/bin/python scripts/quick_test.py unit
# Integration tests only
.venv/bin/python scripts/quick_test.py integration
# Theme-related tests only
.venv/bin/python scripts/quick_test.py theme
```
#### Run Individual Test Classes
```bash
# Run specific integration test
.venv/bin/python -m pytest tests/test_integration.py::TestIntegrationSuite::
test_theme_changing_functionality -v
# Run all theme manager tests
.venv/bin/python -m pytest tests/test_theme_manager.py -v
```
### Migration Benefits
1. **Unified Structure**: All tests use the same pytest framework
2. **Better Organization**: Related tests grouped together
3. **Improved Coverage**: Integrated coverage reporting
4. **Faster Execution**: Optimized test setup and teardown
5. **Better CI/CD**: Easier to integrate with automated testing
### Backwards Compatibility
The old `integration_test.py` script is still available and called by the new test
runner for backwards compatibility.
"""
notice_path = Path(__file__).parent / "TESTING_MIGRATION.md"
with open(notice_path, "w") as f:
f.write(notice)
print(f"Created migration notice: {notice_path}")
def rename_old_scripts():
"""Rename old test scripts to indicate they're deprecated."""
old_scripts = [
"test_note_saving.py",
"test_update_entry.py",
"test_keyboard_shortcuts.py",
"test_menu_theming.py",
]
scripts_dir = Path(__file__).parent
for script in old_scripts:
old_path = scripts_dir / script
if old_path.exists():
new_path = scripts_dir / f"deprecated_{script}"
old_path.rename(new_path)
print(f"Renamed {script} -> deprecated_{script}")
# Add deprecation notice to the file
with open(new_path) as f:
_content = f.read()
deprecation_notice = '''#!/usr/bin/env python3
"""
⚠️ DEPRECATED SCRIPT ⚠️
This script has been consolidated into the new unified test suite.
Please use the new testing structure instead:
For theme testing:
.venv/bin/python scripts/quick_test.py theme
For integration testing:
.venv/bin/python scripts/quick_test.py integration
For all tests:
.venv/bin/python scripts/run_tests.py
See TESTING_MIGRATION.md for full details.
"""
import sys
print("⚠️ This script is deprecated. Please use the new test structure.")
print("See TESTING_MIGRATION.md for migration instructions.")
sys.exit(1)
# Original script content below (preserved for reference):
# """ + content[content.find('"""'):] if '"""' in content else content + """
"""
'''
with open(new_path, "w") as f:
f.write(deprecation_notice)
def update_readme():
"""Update the scripts README to reflect the new structure."""
readme_path = Path(__file__).parent / "README.md"
if readme_path.exists():
# Backup original
backup_path = Path(__file__).parent / "README.md.backup"
readme_path.rename(backup_path)
print(f"Backed up original README to {backup_path}")
new_readme = """# TheChart Scripts Directory
This directory contains utility scripts and the **new consolidated test suite** for
TheChart application.
## 🚀 Quick Start
### Run All Tests
```bash
cd /home/will/Code/thechart
.venv/bin/python scripts/run_tests.py
```
### Run Specific Test Categories
```bash
# Unit tests only
.venv/bin/python scripts/quick_test.py unit
# Integration tests only
.venv/bin/python scripts/quick_test.py integration
# Theme-related tests only
.venv/bin/python scripts/quick_test.py theme
```
## 📁 Current Structure
### Active Scripts
#### `run_tests.py` 🎯
**Main test runner** - executes the complete test suite with coverage reporting.
- Runs unit tests with coverage
- Runs integration tests
- Runs legacy integration tests for backwards compatibility
- Provides comprehensive test summary
#### `quick_test.py` ⚡
**Quick test runner** - for specific test categories during development.
- `unit` - Fast unit tests only
- `integration` - Integration tests only
- `theme` - Theme-related functionality tests
- `all` - Complete test suite
#### `integration_test.py` 🔄
**Legacy integration test** - maintained for backwards compatibility.
- Tests export system functionality
- No GUI dependencies
- Called automatically by the main test runner
### Test Organization
#### Unit Tests (`/tests/`)
- `test_*.py` - Individual module tests
- Uses pytest framework
- Fast execution, isolated tests
- Coverage reporting enabled
#### Integration Tests (`tests/test_integration.py`)
- **Consolidated integration test suite**
- Tests complete workflows and interactions
- Includes functionality from old standalone scripts:
- Note saving and retrieval
- Entry updates and validation
- Theme changing functionality
- Keyboard shortcuts binding
- Menu theming integration
- Export system testing
- Data validation and error handling
## 🔄 Migration from Old Structure
The old individual test scripts have been **consolidated** into the unified test suite:
| Old Script | New Location | How to Run |
|------------|--------------|------------|
| `test_note_saving.py` | `tests/test_integration.py::test_note_saving_functionality` |
`quick_test.py integration` |
| `test_update_entry.py` | `tests/test_integration.py::test_entry_update_functionality`
| `quick_test.py integration` |
| `test_keyboard_shortcuts.py` | `tests/test_integration.py::
test_keyboard_shortcuts_binding` | `quick_test.py integration` |
| `test_theme_changing.py` | `tests/test_integration.py::
test_theme_changing_functionality` | `quick_test.py theme` |
| `test_menu_theming.py` | `tests/test_integration.py::test_menu_theming_integration` |
`quick_test.py theme` |
### Benefits of New Structure
1. **Unified Framework**: All tests use pytest
2. **Better Organization**: Related tests grouped logically
3. **Improved Performance**: Optimized setup/teardown
4. **Coverage Reporting**: Integrated coverage analysis
5. **CI/CD Ready**: Easier automation and integration
## 🛠️ Development Workflow
### During Development
```bash
# Quick unit tests (fastest feedback)
.venv/bin/python scripts/quick_test.py unit
# Test specific functionality
.venv/bin/python scripts/quick_test.py theme
```
### Before Commits
```bash
# Full test suite with coverage
.venv/bin/python scripts/run_tests.py
```
### Individual Test Debugging
```bash
# Run specific test with output
.venv/bin/python -m pytest tests/test_integration.py::TestIntegrationSuite::
test_theme_changing_functionality -v -s
# Run with debugger
.venv/bin/python -m pytest tests/test_integration.py::TestIntegrationSuite::
test_note_saving_functionality -v -s --pdb
```
## 📋 Available Test Categories
### Unit Tests
- Fast, isolated component tests
- Mock external dependencies
- Test individual functions and classes
### Integration Tests
- Test component interactions
- Test complete workflows
- Validate data persistence
- Test UI functionality (without GUI display)
### Theme Tests
- Theme switching functionality
- Color scheme validation
- Menu theming consistency
- Error handling in theme system
### System Health Checks
- Configuration file validation
- Manager initialization tests
- Logging system verification
## 🏃‍♂️ Performance Tips
- Use `quick_test.py unit` for fastest feedback during development
- Use `quick_test.py integration` to test workflow changes
- Use `quick_test.py theme` when working on UI/theming
- Use `run_tests.py` for comprehensive testing before commits
## 🔧 Debugging Tests
### Common Commands
```bash
# Run with verbose output
.venv/bin/python -m pytest tests/ -v
# Stop on first failure
.venv/bin/python -m pytest tests/ -x
# Show local variables on failure
.venv/bin/python -m pytest tests/ -l
# Run with debugger on failure
.venv/bin/python -m pytest tests/ --pdb
```
### Debugging Specific Issues
```bash
# Debug theme issues
.venv/bin/python -m pytest tests/test_integration.py::TestIntegrationSuite::
test_theme_changing_functionality -v -s
# Debug data management
.venv/bin/python -m pytest tests/test_data_manager.py -v -s
# Debug export functionality
.venv/bin/python scripts/integration_test.py
```
---
📖 **See Also**: `TESTING_MIGRATION.md` for detailed migration information.
"""
with open(readme_path, "w") as f:
f.write(new_readme)
print("Updated README.md with new test structure documentation")
def main():
"""Main migration function."""
print("TheChart Test Migration Script")
print("=" * 30)
# Change to scripts directory
scripts_dir = Path(__file__).parent
os.chdir(scripts_dir)
print("1. Creating migration notice...")
create_deprecated_notice()
print("2. Renaming old test scripts...")
rename_old_scripts()
print("3. Updating README...")
update_readme()
print("\n✅ Migration completed!")
print("\n📋 Summary:")
print(" • Created TESTING_MIGRATION.md with detailed instructions")
print(" • Renamed old test scripts to deprecated_*")
print(" • Updated README.md with new test structure")
print("\n🚀 Next steps:")
print(" • Run: .venv/bin/python scripts/run_tests.py")
print(" • Check: .venv/bin/python scripts/quick_test.py unit")
if __name__ == "__main__":
main()
+89
View File
@@ -0,0 +1,89 @@
#!/usr/bin/env python3
"""
Quick test runner for individual test categories.
Usage:
python scripts/quick_test.py unit # Run only unit tests
python scripts/quick_test.py integration # Run only integration tests
python scripts/quick_test.py theme # Test theme functionality
python scripts/quick_test.py all # Run all tests (default)
"""
import subprocess
import sys
from pathlib import Path
def run_unit_tests():
"""Run unit tests only."""
cmd = [sys.executable, "-m", "pytest", "tests/", "--verbose", "-x", "--tb=short"]
return subprocess.run(cmd).returncode == 0
def run_integration_tests():
"""Run integration tests only."""
cmd = [
sys.executable,
"-m",
"pytest",
"tests/test_integration.py",
"--verbose",
"-s",
]
return subprocess.run(cmd).returncode == 0
def run_theme_tests():
"""Run theme-related tests only."""
cmd = [
sys.executable,
"-m",
"pytest",
"tests/test_integration.py::TestIntegrationSuite::test_theme_changing_functionality",
"tests/test_integration.py::TestIntegrationSuite::test_menu_theming_integration",
"tests/test_theme_manager.py",
"--verbose",
"-s",
]
return subprocess.run(cmd).returncode == 0
def run_all_tests():
"""Run the full test suite."""
return subprocess.run([sys.executable, "scripts/run_tests.py"]).returncode == 0
def main():
"""Main test runner."""
# Change to project root
project_root = Path(__file__).parent.parent
import os
os.chdir(project_root)
test_type = sys.argv[1] if len(sys.argv) > 1 else "all"
runners = {
"unit": run_unit_tests,
"integration": run_integration_tests,
"theme": run_theme_tests,
"all": run_all_tests,
}
if test_type not in runners:
print(f"Unknown test type: {test_type}")
print("Available options: unit, integration, theme, all")
sys.exit(1)
print(f"Running {test_type} tests...")
success = runners[test_type]()
if success:
print(f"{test_type.title()} tests passed!")
sys.exit(0)
else:
print(f"{test_type.title()} tests failed!")
sys.exit(1)
if __name__ == "__main__":
main()
+98 -14
View File
@@ -1,25 +1,19 @@
#!/usr/bin/env python3
"""
Test runner script for TheChart application.
Consolidated test runner script for TheChart application.
Run this script to execute all tests with coverage reporting.
"""
import os
import subprocess
import sys
from pathlib import Path
def run_tests():
"""Run all tests with coverage reporting."""
def run_unit_tests():
"""Run unit tests with coverage reporting."""
print("Running unit tests with coverage...")
# Change to project root directory
project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
os.chdir(project_root)
print("Running TheChart tests with coverage...")
print(f"Project root: {project_root}")
# Run pytest with coverage
cmd = [
sys.executable,
"-m",
@@ -30,16 +24,106 @@ def run_tests():
"--cov-report=term-missing",
"--cov-report=html:htmlcov",
"--cov-report=xml",
"-x", # Stop on first failure for faster feedback
]
try:
result = subprocess.run(cmd, check=False)
return result.returncode
return result.returncode == 0
except Exception as e:
print(f"Error running tests: {e}")
print(f"Error running unit tests: {e}")
return False
def run_integration_tests():
"""Run integration tests."""
print("Running integration tests...")
cmd = [
sys.executable,
"-m",
"pytest",
"tests/test_integration.py",
"--verbose",
"-s", # Don't capture output so we can see print statements
]
try:
result = subprocess.run(cmd, check=False)
return result.returncode == 0
except Exception as e:
print(f"Error running integration tests: {e}")
return False
def run_legacy_integration_test():
"""Run the legacy integration test for backwards compatibility."""
print("Running legacy export integration test...")
try:
# Import and run the integration test directly
sys.path.insert(0, "scripts")
from integration_test import test_integration
success = test_integration()
return success
except Exception as e:
print(f"Error running legacy integration test: {e}")
return False
def run_all_tests():
"""Run all tests in sequence."""
project_root = Path(__file__).parent.parent
os.chdir(project_root)
print("TheChart Consolidated Test Suite")
print("=" * 40)
print(f"Project root: {project_root}")
print()
results = []
# Run unit tests
print("1. Unit Tests")
print("-" * 20)
unit_success = run_unit_tests()
results.append(("Unit Tests", unit_success))
print()
# Run integration tests
print("2. Integration Tests")
print("-" * 20)
integration_success = run_integration_tests()
results.append(("Integration Tests", integration_success))
print()
# Run legacy integration test
print("3. Legacy Export Integration Test")
print("-" * 35)
legacy_success = run_legacy_integration_test()
results.append(("Legacy Integration", legacy_success))
print()
# Summary
print("Test Results Summary")
print("=" * 20)
all_passed = True
for test_name, success in results:
status = "✓ PASS" if success else "✗ FAIL"
print(f"{test_name:.<25} {status}")
if not success:
all_passed = False
print()
if all_passed:
print("🎉 All tests passed!")
return 0
else:
print("❌ Some tests failed!")
return 1
if __name__ == "__main__":
exit_code = run_tests()
exit_code = run_all_tests()
sys.exit(exit_code)
-93
View File
@@ -1,93 +0,0 @@
#!/usr/bin/env python3
"""
Test script for keyboard shortcuts functionality.
This script tests that the keyboard shortcuts are properly bound.
"""
import os
import sys
import tkinter as tk
# Add the src directory to the path so we can import the main module
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src"))
from main import MedTrackerApp
def test_keyboard_shortcuts():
"""Test that keyboard shortcuts are properly bound."""
print("Testing keyboard shortcuts...")
# Create a test window
root = tk.Tk()
root.withdraw() # Hide the window for testing
try:
# Create the app instance
app = MedTrackerApp(root)
# Test that the shortcuts are bound
expected_shortcuts = [
"<Control-s>",
"<Control-S>",
"<Control-q>",
"<Control-Q>",
"<Control-e>",
"<Control-E>",
"<Control-n>",
"<Control-N>",
"<Control-r>",
"<Control-R>",
"<F5>",
"<Control-m>",
"<Control-M>",
"<Control-p>",
"<Control-P>",
"<Delete>",
"<Escape>",
"<F1>",
]
# Check if shortcuts are bound
bound_shortcuts = []
for shortcut in expected_shortcuts:
if root.bind(shortcut):
bound_shortcuts.append(shortcut)
print(f"Successfully bound {len(bound_shortcuts)} keyboard shortcuts:")
for shortcut in bound_shortcuts:
print(f"{shortcut}")
# Test that methods exist
methods_to_test = [
"add_new_entry",
"handle_window_closing",
"_open_export_window",
"_clear_entries",
"refresh_data_display",
"_open_medicine_manager",
"_open_pathology_manager",
"_delete_selected_entry",
"_clear_selection",
"_show_keyboard_shortcuts",
]
for method_name in methods_to_test:
if hasattr(app, method_name):
print(f" ✓ Method {method_name} exists")
else:
print(f" ✗ Method {method_name} missing")
print("\n✅ Keyboard shortcuts test completed successfully!")
return True
except Exception as e:
print(f"❌ Error during testing: {e}")
return False
finally:
root.destroy()
if __name__ == "__main__":
success = test_keyboard_shortcuts()
sys.exit(0 if success else 1)
-153
View File
@@ -1,153 +0,0 @@
#!/usr/bin/env python3
"""Interactive demonstration of menu theming functionality."""
import logging
import os
import sys
import tkinter as tk
# Add the src directory to the path so we can import the modules
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "../src"))
from theme_manager import ThemeManager
def demo_menu_theming():
"""Interactive demonstration of menu theming with different themes."""
# Set up logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
print("Menu Theming Interactive Demo")
print("=============================")
# Create root window
root = tk.Tk()
root.title("Menu Theming Demo - TheChart")
root.geometry("500x400")
# Initialize theme manager
theme_manager = ThemeManager(root, logger)
# Create demo menubar using the new convenience method
menubar = theme_manager.create_themed_menu(root)
root.config(menu=menubar)
# Create submenus
file_menu = theme_manager.create_themed_menu(menubar, tearoff=0)
theme_menu = theme_manager.create_themed_menu(menubar, tearoff=0)
help_menu = theme_manager.create_themed_menu(menubar, tearoff=0)
menubar.add_cascade(label="File", menu=file_menu)
menubar.add_cascade(label="Theme", menu=theme_menu)
menubar.add_cascade(label="Help", menu=help_menu)
# Populate file menu
file_menu.add_command(label="Demo Item 1")
file_menu.add_command(label="Demo Item 2")
file_menu.add_separator()
file_menu.add_command(label="Exit Demo", command=root.quit)
# Populate help menu
help_menu.add_command(
label="About Demo",
command=lambda: tk.messagebox.showinfo(
"About", "Interactive menu theming demonstration for TheChart"
),
)
# Theme information display
theme_info_frame = tk.Frame(root, relief="ridge", bd=2)
theme_info_frame.pack(fill="x", padx=20, pady=10)
current_theme_label = tk.Label(
theme_info_frame,
text=f"Current Theme: {theme_manager.get_current_theme().title()}",
font=("Arial", 12, "bold"),
)
current_theme_label.pack(pady=5)
colors_display = tk.Text(theme_info_frame, height=6, wrap="word")
colors_display.pack(fill="x", padx=10, pady=5)
def update_theme_display():
"""Update the theme information display."""
current_theme_label.config(
text=f"Current Theme: {theme_manager.get_current_theme().title()}"
)
menu_colors = theme_manager.get_menu_colors()
colors_text = "Current Menu Colors:\n"
for key, value in menu_colors.items():
colors_text += f" {key}: {value}\n"
colors_display.delete(1.0, tk.END)
colors_display.insert(1.0, colors_text)
# Function to apply theme and update displays
def apply_theme_and_update(theme_name):
"""Apply theme and update all displays."""
print(f"Switching to theme: {theme_name}")
if theme_manager.apply_theme(theme_name):
# Re-theme all menus
theme_manager.configure_menu(menubar)
theme_manager.configure_menu(file_menu)
theme_manager.configure_menu(theme_menu)
theme_manager.configure_menu(help_menu)
# Update display
update_theme_display()
print(f" ✓ Successfully applied {theme_name} theme")
else:
print(f" ✗ Failed to apply {theme_name} theme")
# Create theme selection menu
available_themes = theme_manager.get_available_themes()
current_theme = theme_manager.get_current_theme()
for theme in available_themes:
theme_menu.add_radiobutton(
label=theme.title(),
command=lambda t=theme: apply_theme_and_update(t),
value=theme == current_theme,
)
# Instructions
instructions_frame = tk.Frame(root)
instructions_frame.pack(fill="both", expand=True, padx=20, pady=10)
tk.Label(
instructions_frame,
text="Menu Theming Demonstration",
font=("Arial", 16, "bold"),
).pack(pady=10)
instructions_text = """
Instructions:
1. Use the Theme menu to switch between different themes
2. Observe how menu colors change to match each theme
3. Try the File and Help menus to see the color effects
4. Menu backgrounds, text, and hover effects all update automatically
Available themes: """ + ", ".join([t.title() for t in available_themes])
tk.Label(
instructions_frame,
text=instructions_text,
justify="left",
wraplength=450,
).pack(pady=10)
# Initialize display
update_theme_display()
print(f"Demo window opened with {len(available_themes)} available themes.")
print("Try the Theme menu to see different color schemes!")
# Show the window
root.mainloop()
if __name__ == "__main__":
demo_menu_theming()
-69
View File
@@ -1,69 +0,0 @@
#!/usr/bin/env python3
"""
Test script to verify note field saving functionality
"""
import logging
import os
import sys
import pandas as pd
# Add src directory to path to import modules
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src"))
from data_manager import DataManager
from medicine_manager import MedicineManager
from pathology_manager import PathologyManager
def test_note_saving():
"""Test note saving functionality by checking current data"""
print("Testing note saving functionality...")
# Initialize logger
logger = logging.getLogger("test")
logger.setLevel(logging.INFO)
# Initialize managers
medicine_manager = MedicineManager("medicines.json")
pathology_manager = PathologyManager("pathologies.json")
data_manager = DataManager(
"thechart_data.csv", logger, medicine_manager, pathology_manager
)
# Load current data
df = data_manager.load_data()
if df.empty:
print("No data found in CSV file")
return
print(f"Found {len(df)} entries in the data file")
# Check if we have any entries with notes
entries_with_notes = df[df["note"].notna() & (df["note"] != "")].copy()
print(f"Entries with notes: {len(entries_with_notes)}")
if len(entries_with_notes) > 0:
print("\nEntries with notes:")
for _, row in entries_with_notes.iterrows():
note_preview = (
row["note"][:50] + "..." if len(str(row["note"])) > 50 else row["note"]
)
print(f" Date: {row['date']}, Note: {note_preview}")
# Show the most recent entry
if len(df) > 0:
latest_entry = df.iloc[-1]
print("\nMost recent entry:")
print(f" Date: {latest_entry['date']}")
print(f" Note: '{latest_entry['note']}'")
print(f" Note length: {len(str(latest_entry['note']))}")
is_empty = pd.isna(latest_entry["note"]) or latest_entry["note"] == ""
print(f" Note is empty/null: {is_empty}")
if __name__ == "__main__":
test_note_saving()
+57
View File
@@ -0,0 +1,57 @@
#!/usr/bin/env python3
"""Test script to verify theme changing functionality works without errors."""
import sys
import tkinter as tk
from pathlib import Path
from init import logger
from theme_manager import ThemeManager
# Add src directory to Python path
src_path = Path(__file__).parent.parent / "src"
sys.path.insert(0, str(src_path))
def test_theme_changes():
"""Test changing between different themes to ensure no errors occur."""
print("Testing theme changing functionality...")
# Create a test tkinter window
root = tk.Tk()
root.withdraw() # Hide the window
# Initialize theme manager
theme_manager = ThemeManager(root, logger)
# Test all available themes
available_themes = theme_manager.get_available_themes()
print(f"Available themes: {available_themes}")
for theme in available_themes:
print(f"Testing theme: {theme}")
try:
success = theme_manager.apply_theme(theme)
if success:
print(f"{theme} applied successfully")
# Test getting theme colors (this is where the error was occurring)
colors = theme_manager.get_theme_colors()
print(f" ✓ Theme colors retrieved: {list(colors.keys())}")
# Test getting menu colors
menu_colors = theme_manager.get_menu_colors()
print(f" ✓ Menu colors retrieved: {list(menu_colors.keys())}")
else:
print(f" ✗ Failed to apply {theme}")
except Exception as e:
print(f" ✗ Error with {theme}: {e}")
# Clean up
root.destroy()
print("Theme testing completed!")
if __name__ == "__main__":
test_theme_changes()
-102
View File
@@ -1,102 +0,0 @@
#!/usr/bin/env python3
"""
Test the update_entry functionality with notes
"""
import logging
import os
import sys
# Add src directory to path to import modules
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src"))
from data_manager import DataManager
from medicine_manager import MedicineManager
from pathology_manager import PathologyManager
def test_update_entry_with_note():
"""Test updating an entry with a note"""
print("Testing update_entry functionality with notes...")
# Initialize logger
logger = logging.getLogger("test")
logger.setLevel(logging.DEBUG)
# Add console handler to see debug output
handler = logging.StreamHandler()
handler.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(levelname)s - %(message)s")
handler.setFormatter(formatter)
logger.addHandler(handler)
# Initialize managers
medicine_manager = MedicineManager("medicines.json")
pathology_manager = PathologyManager("pathologies.json")
data_manager = DataManager(
"thechart_data.csv", logger, medicine_manager, pathology_manager
)
# Load current data
df = data_manager.load_data()
if df.empty:
print("No data found in CSV file")
return
print(f"Found {len(df)} entries in the data file")
# Find the most recent entry to test with
latest_entry = df.iloc[-1].copy()
original_date = latest_entry["date"]
print(f"Testing with entry: {original_date}")
print(f"Current note: '{latest_entry['note']}'")
# Create test values - keep everything the same but change the note
test_note = "This is a test note to verify saving functionality!"
# Build values list (same format as the UI would send)
values = [original_date] # date
# Add pathology values
pathology_keys = pathology_manager.get_pathology_keys()
for key in pathology_keys:
values.append(latest_entry.get(key, 0))
# Add medicine values and doses
medicine_keys = medicine_manager.get_medicine_keys()
for key in medicine_keys:
values.append(latest_entry.get(key, 0)) # medicine checkbox
values.append(latest_entry.get(f"{key}_doses", "")) # medicine doses
# Add the test note
values.append(test_note)
print(f"Values to save: {values}")
print(f"Note in values: '{values[-1]}'")
# Test the update
success = data_manager.update_entry(original_date, values)
if success:
print("Update successful!")
# Reload and verify
df_after = data_manager.load_data()
updated_entry = df_after[df_after["date"] == original_date].iloc[0]
print(f"Note after update: '{updated_entry['note']}'")
print(f"Note correctly saved: {updated_entry['note'] == test_note}")
# Reset the note back to original
values[-1] = latest_entry["note"]
data_manager.update_entry(original_date, values)
print("Reverted note back to original")
else:
print("Update failed!")
if __name__ == "__main__":
test_update_entry_with_note()