chore: Remove obsolete test scripts and unused methods from the data manager
- Deleted test scripts for dose tracking, UI functionality, dynamic data, edit functionality, and final workflow. - Removed the `add_medicine_dose` method from the DataManager class as it is no longer needed.
This commit is contained in:
@@ -1,66 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Example script showing how to add a new medicine programmatically.
|
||||
This demonstrates the modular medicine system.
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
|
||||
# Add src to path
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "src"))
|
||||
|
||||
from init import logger
|
||||
from medicine_manager import Medicine, MedicineManager
|
||||
|
||||
|
||||
def add_example_medicine():
|
||||
"""Add an example medicine to demonstrate the system."""
|
||||
print("🔧 Adding a new medicine example...")
|
||||
|
||||
# Initialize medicine manager
|
||||
medicine_manager = MedicineManager(logger=logger)
|
||||
|
||||
# Display current medicines
|
||||
print("\nCurrent medicines:")
|
||||
for _, medicine in medicine_manager.get_all_medicines().items():
|
||||
print(f" - {medicine.display_name} ({medicine.dosage_info})")
|
||||
|
||||
# Add a new medicine
|
||||
new_medicine = Medicine(
|
||||
key="lorazepam",
|
||||
display_name="Lorazepam",
|
||||
dosage_info="0.5mg",
|
||||
quick_doses=["0.5", "1", "2"],
|
||||
color="#8E44AD",
|
||||
default_enabled=False,
|
||||
)
|
||||
|
||||
if medicine_manager.add_medicine(new_medicine):
|
||||
print(f"\n✅ Successfully added {new_medicine.display_name}!")
|
||||
|
||||
print("\nUpdated medicines:")
|
||||
for _, medicine in medicine_manager.get_all_medicines().items():
|
||||
status = "🟢" if medicine.default_enabled else "⚫"
|
||||
print(f" {status} {medicine.display_name} ({medicine.dosage_info})")
|
||||
|
||||
print("\n📋 The medicine configuration has been saved to medicines.json")
|
||||
print("📱 Restart the application to see the new medicine in the UI")
|
||||
print("🎨 The new medicine will appear in:")
|
||||
print(" - Input form checkboxes")
|
||||
print(" - Data table columns")
|
||||
print(" - Graph toggle controls")
|
||||
print(" - CSV file headers")
|
||||
|
||||
# Optionally remove it for demo purposes
|
||||
response = input("\nRemove the example medicine? (y/n): ").lower().strip()
|
||||
if response == "y":
|
||||
medicine_manager.remove_medicine("lorazepam")
|
||||
print("🗑️ Example medicine removed.")
|
||||
|
||||
else:
|
||||
print("❌ Failed to add medicine (it may already exist)")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
add_example_medicine()
|
||||
@@ -1,124 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Debug test to see what happens to dose data during save."""
|
||||
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
import tkinter as tk
|
||||
|
||||
sys.path.append(os.path.join(os.path.dirname(__file__), "src"))
|
||||
|
||||
from medicine_manager import MedicineManager
|
||||
from pathology_manager import PathologyManager
|
||||
from ui_manager import UIManager
|
||||
|
||||
|
||||
def debug_dose_save():
|
||||
"""Debug test to track dose data through the save process."""
|
||||
|
||||
# Setup logging
|
||||
logging.basicConfig(level=logging.DEBUG)
|
||||
logger = logging.getLogger("test")
|
||||
|
||||
# Initialize managers
|
||||
medicine_manager = MedicineManager()
|
||||
pathology_manager = PathologyManager()
|
||||
|
||||
# Create root window
|
||||
root = tk.Tk()
|
||||
root.withdraw()
|
||||
|
||||
# Initialize UI manager
|
||||
ui_manager = UIManager(
|
||||
root=root,
|
||||
logger=logger,
|
||||
medicine_manager=medicine_manager,
|
||||
pathology_manager=pathology_manager,
|
||||
)
|
||||
|
||||
# Create test data with different medicines having different dose states
|
||||
test_values = ["2025-07-31"] # date
|
||||
|
||||
# Add pathology values
|
||||
pathologies = pathology_manager.get_all_pathologies()
|
||||
for _ in pathologies:
|
||||
test_values.append(3) # pathology value
|
||||
|
||||
# Add medicine values and doses - simulate one with history, others empty
|
||||
medicines = medicine_manager.get_all_medicines()
|
||||
medicine_keys = list(medicines.keys())
|
||||
|
||||
for i, _ in enumerate(medicines):
|
||||
test_values.append(1) # medicine checkbox value
|
||||
if i == 0: # First medicine has dose history
|
||||
test_values.append(
|
||||
"2025-07-31 08:00:00:150mg|2025-07-31 14:00:00:25mg"
|
||||
) # existing doses in storage format
|
||||
else: # Other medicines have no dose history
|
||||
test_values.append("")
|
||||
|
||||
test_values.append("Test note") # note
|
||||
|
||||
print("Test setup:")
|
||||
print(f" Medicine keys: {medicine_keys}")
|
||||
print(f" First medicine ({medicine_keys[0]}) has dose history")
|
||||
print(" Other medicines have no dose history")
|
||||
print(f"Test values: {test_values}")
|
||||
|
||||
# Track what gets saved
|
||||
saved_data = None
|
||||
|
||||
def mock_save_callback(*args):
|
||||
nonlocal saved_data
|
||||
saved_data = args
|
||||
print("\n=== SAVE CALLBACK ===")
|
||||
print(f"Save callback called with {len(args)} arguments")
|
||||
|
||||
if len(args) >= 2:
|
||||
dose_data = args[-1] # Last argument should be dose data
|
||||
print(f"Dose data type: {type(dose_data)}")
|
||||
print("Dose data contents:")
|
||||
|
||||
if isinstance(dose_data, dict):
|
||||
for med_key, dose_str in dose_data.items():
|
||||
print(f" {med_key}: '{dose_str}' (length: {len(dose_str)})")
|
||||
if dose_str:
|
||||
doses = dose_str.split("|") if "|" in dose_str else [dose_str]
|
||||
print(f" -> {len(doses)} dose(s): {doses}")
|
||||
|
||||
# Don't destroy window, just close it
|
||||
root.quit()
|
||||
|
||||
def mock_delete_callback(win):
|
||||
print("Delete callback called")
|
||||
win.destroy()
|
||||
root.quit()
|
||||
|
||||
callbacks = {"save": mock_save_callback, "delete": mock_delete_callback}
|
||||
|
||||
# Create edit window
|
||||
edit_window = ui_manager.create_edit_window(tuple(test_values), callbacks)
|
||||
print("\nEdit window created.")
|
||||
print("Instructions:")
|
||||
print("1. The first medicine tab should show existing dose history")
|
||||
print("2. Add a new dose to a DIFFERENT medicine tab")
|
||||
print("3. Click Save and observe the output")
|
||||
|
||||
# Show the window so user can interact
|
||||
root.deiconify()
|
||||
edit_window.lift()
|
||||
edit_window.focus_force()
|
||||
|
||||
# Run main loop
|
||||
root.mainloop()
|
||||
|
||||
if saved_data:
|
||||
print("✅ Test completed - data was saved")
|
||||
return True
|
||||
else:
|
||||
print("❌ Test failed - no data saved")
|
||||
return False
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
debug_dose_save()
|
||||
@@ -1,67 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Migration script to add dose tracking columns to existing CSV data.
|
||||
"""
|
||||
|
||||
import shutil
|
||||
from datetime import datetime
|
||||
|
||||
import pandas as pd
|
||||
|
||||
|
||||
def migrate_csv(filename: str = "thechart_data.csv") -> None:
|
||||
"""Migrate existing CSV to new format with dose tracking columns."""
|
||||
|
||||
# Create backup
|
||||
backup_name = f"{filename}.backup_{datetime.now().strftime('%Y%m%d_%H%M%S')}"
|
||||
shutil.copy2(filename, backup_name)
|
||||
print(f"Created backup: {backup_name}")
|
||||
|
||||
try:
|
||||
# Read existing data
|
||||
df = pd.read_csv(filename)
|
||||
print(f"Read {len(df)} existing entries")
|
||||
|
||||
# Add new dose tracking columns
|
||||
df["bupropion_doses"] = ""
|
||||
df["hydroxyzine_doses"] = ""
|
||||
df["gabapentin_doses"] = ""
|
||||
df["propranolol_doses"] = ""
|
||||
|
||||
# Reorder columns to match new format
|
||||
new_column_order = [
|
||||
"date",
|
||||
"depression",
|
||||
"anxiety",
|
||||
"sleep",
|
||||
"appetite",
|
||||
"bupropion",
|
||||
"bupropion_doses",
|
||||
"hydroxyzine",
|
||||
"hydroxyzine_doses",
|
||||
"gabapentin",
|
||||
"gabapentin_doses",
|
||||
"propranolol",
|
||||
"propranolol_doses",
|
||||
"note",
|
||||
]
|
||||
|
||||
df = df[new_column_order]
|
||||
|
||||
# Save migrated data
|
||||
df.to_csv(filename, index=False)
|
||||
print(f"Successfully migrated {filename}")
|
||||
print(
|
||||
"New columns added: bupropion_doses, hydroxyzine_doses, "
|
||||
"gabapentin_doses, propranolol_doses"
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error during migration: {e}")
|
||||
print(f"Restoring from backup: {backup_name}")
|
||||
shutil.copy2(backup_name, filename)
|
||||
raise
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
migrate_csv()
|
||||
@@ -1,61 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Migration script to add quetiapine columns to existing CSV data.
|
||||
This script will backup the existing CSV and add the new columns.
|
||||
"""
|
||||
|
||||
import os
|
||||
import shutil
|
||||
from datetime import datetime
|
||||
|
||||
import pandas as pd
|
||||
|
||||
|
||||
def migrate_csv_add_quetiapine(csv_file: str = "thechart_data.csv"):
|
||||
"""Add quetiapine and quetiapine_doses columns to existing CSV."""
|
||||
|
||||
if not os.path.exists(csv_file):
|
||||
print(f"CSV file {csv_file} not found. No migration needed.")
|
||||
return
|
||||
|
||||
# Create backup
|
||||
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
||||
backup_file = f"{csv_file}.backup_quetiapine_{timestamp}"
|
||||
shutil.copy2(csv_file, backup_file)
|
||||
print(f"Backup created: {backup_file}")
|
||||
|
||||
# Load existing data
|
||||
try:
|
||||
df = pd.read_csv(csv_file)
|
||||
print(f"Loaded {len(df)} rows from {csv_file}")
|
||||
|
||||
# Check if quetiapine columns already exist
|
||||
if "quetiapine" in df.columns:
|
||||
print("Quetiapine columns already exist. No migration needed.")
|
||||
return
|
||||
|
||||
# Add new columns
|
||||
# Insert quetiapine columns before the note column
|
||||
note_col_index = (
|
||||
df.columns.get_loc("note") if "note" in df.columns else len(df.columns)
|
||||
)
|
||||
|
||||
# Insert quetiapine column
|
||||
df.insert(note_col_index, "quetiapine", 0)
|
||||
df.insert(note_col_index + 1, "quetiapine_doses", "")
|
||||
|
||||
# Save updated CSV
|
||||
df.to_csv(csv_file, index=False)
|
||||
print(f"Successfully added quetiapine columns to {csv_file}")
|
||||
print(f"New column order: {list(df.columns)}")
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error during migration: {e}")
|
||||
# Restore backup on error
|
||||
if os.path.exists(backup_file):
|
||||
shutil.copy2(backup_file, csv_file)
|
||||
print("Restored backup due to error")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
migrate_csv_add_quetiapine()
|
||||
@@ -1,51 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Quick test runner for TheChart application.
|
||||
This script provides a simple way to run the test suite.
|
||||
"""
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
|
||||
def main():
|
||||
"""Run the test suite."""
|
||||
print("🧪 Running TheChart Test Suite")
|
||||
print("=" * 50)
|
||||
|
||||
# Change to project directory
|
||||
os.chdir(os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
# Run tests with coverage
|
||||
cmd = [
|
||||
"uv",
|
||||
"run",
|
||||
"pytest",
|
||||
"tests/",
|
||||
"--cov=src",
|
||||
"--cov-report=term-missing",
|
||||
"--cov-report=html:htmlcov",
|
||||
"-v",
|
||||
]
|
||||
|
||||
try:
|
||||
result = subprocess.run(cmd, check=False)
|
||||
if result.returncode == 0:
|
||||
print("\n✅ All tests passed!")
|
||||
else:
|
||||
print(f"\n❌ Some tests failed (exit code: {result.returncode})")
|
||||
|
||||
print("\n📊 Coverage report generated in htmlcov/index.html")
|
||||
return result.returncode
|
||||
|
||||
except KeyboardInterrupt:
|
||||
print("\n⚠️ Tests interrupted by user")
|
||||
return 1
|
||||
except Exception as e:
|
||||
print(f"\n💥 Error running tests: {e}")
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -1,91 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Test script to verify date uniqueness functionality in TheChart app.
|
||||
"""
|
||||
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
|
||||
# Add the src directory to the Python path
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "src"))
|
||||
|
||||
from src.data_manager import DataManager
|
||||
|
||||
# Set up simple logging
|
||||
logging.basicConfig(level=logging.DEBUG)
|
||||
logger = logging.getLogger("test")
|
||||
|
||||
|
||||
def test_date_uniqueness():
|
||||
"""Test the date uniqueness validation."""
|
||||
print("Testing date uniqueness functionality...")
|
||||
|
||||
# Create a test data manager with a test file
|
||||
test_filename = "test_data.csv"
|
||||
dm = DataManager(test_filename, logger)
|
||||
|
||||
# Test 1: Add first entry (should succeed)
|
||||
print("\n1. Adding first entry...")
|
||||
entry1 = ["2025-07-28", 5, 5, 5, 5, 0, 0, 0, 0, "First entry"]
|
||||
result1 = dm.add_entry(entry1)
|
||||
print(f"Result: {result1} (Expected: True)")
|
||||
|
||||
# Test 2: Try to add duplicate date (should fail)
|
||||
print("\n2. Trying to add duplicate date...")
|
||||
entry2 = ["2025-07-28", 3, 3, 3, 3, 1, 1, 1, 1, "Duplicate entry"]
|
||||
result2 = dm.add_entry(entry2)
|
||||
print(f"Result: {result2} (Expected: False)")
|
||||
|
||||
# Test 3: Add different date (should succeed)
|
||||
print("\n3. Adding different date...")
|
||||
entry3 = ["2025-07-29", 4, 4, 4, 4, 0, 0, 0, 0, "Second entry"]
|
||||
result3 = dm.add_entry(entry3)
|
||||
print(f"Result: {result3} (Expected: True)")
|
||||
|
||||
# Test 4: Update entry with same date (should succeed)
|
||||
print("\n4. Updating entry with same date...")
|
||||
updated_entry = ["2025-07-28", 6, 6, 6, 6, 1, 1, 1, 1, "Updated entry"]
|
||||
result4 = dm.update_entry("2025-07-28", updated_entry)
|
||||
print(f"Result: {result4} (Expected: True)")
|
||||
|
||||
# Test 5: Try to update entry to existing date (should fail)
|
||||
print("\n5. Trying to update entry to existing date...")
|
||||
conflicting_entry = ["2025-07-29", 7, 7, 7, 7, 1, 1, 1, 1, "Conflicting entry"]
|
||||
result5 = dm.update_entry("2025-07-28", conflicting_entry)
|
||||
print(f"Result: {result5} (Expected: False)")
|
||||
|
||||
# Test 6: Update entry to new date (should succeed)
|
||||
print("\n6. Updating entry to new date...")
|
||||
new_date_entry = ["2025-07-30", 8, 8, 8, 8, 1, 1, 1, 1, "New date entry"]
|
||||
result6 = dm.update_entry("2025-07-28", new_date_entry)
|
||||
print(f"Result: {result6} (Expected: True)")
|
||||
|
||||
# Cleanup
|
||||
if os.path.exists(test_filename):
|
||||
os.remove(test_filename)
|
||||
|
||||
# Summary
|
||||
expected_results = [True, False, True, True, False, True]
|
||||
actual_results = [result1, result2, result3, result4, result5, result6]
|
||||
|
||||
print("\n" + "=" * 50)
|
||||
print("TEST SUMMARY:")
|
||||
print("=" * 50)
|
||||
|
||||
all_passed = True
|
||||
for i, (expected, actual) in enumerate(
|
||||
zip(expected_results, actual_results, strict=True), 1
|
||||
):
|
||||
status = "PASS" if expected == actual else "FAIL"
|
||||
if expected != actual:
|
||||
all_passed = False
|
||||
print(f"Test {i}: {status} (Expected: {expected}, Got: {actual})")
|
||||
|
||||
overall_result = "ALL TESTS PASSED" if all_passed else "SOME TESTS FAILED"
|
||||
print(f"\nOverall result: {overall_result}")
|
||||
return all_passed
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_date_uniqueness()
|
||||
@@ -1,95 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Test script to verify delete functionality after dose tracking implementation.
|
||||
"""
|
||||
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
|
||||
# Add the src directory to the path so we can import our modules
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "src"))
|
||||
|
||||
from src.data_manager import DataManager
|
||||
|
||||
|
||||
def test_delete_functionality():
|
||||
"""Test the delete functionality with the new CSV format."""
|
||||
print("Testing delete functionality...")
|
||||
|
||||
# Create a backup of the current CSV
|
||||
import shutil
|
||||
|
||||
try:
|
||||
shutil.copy("thechart_data.csv", "thechart_data_backup.csv")
|
||||
print("✓ Created backup of current CSV")
|
||||
except Exception as e:
|
||||
print(f"✗ Failed to create backup: {e}")
|
||||
return False
|
||||
|
||||
try:
|
||||
# Create a logger for the DataManager
|
||||
logger = logging.getLogger("test_logger")
|
||||
logger.setLevel(logging.DEBUG)
|
||||
|
||||
# Initialize data manager
|
||||
data_manager = DataManager("thechart_data.csv", logger)
|
||||
|
||||
# Load current data
|
||||
df = data_manager.load_data()
|
||||
print(f"✓ Loaded {len(df)} entries from CSV")
|
||||
|
||||
if df.empty:
|
||||
print("✗ No data to test delete functionality")
|
||||
return False
|
||||
|
||||
# Show first few entries
|
||||
print("\nFirst few entries:")
|
||||
for _idx, row in df.head(3).iterrows():
|
||||
print(f" {row['date']}: {row['note']}")
|
||||
|
||||
# Test deleting the last entry
|
||||
last_entry_date = df.iloc[-1]["date"]
|
||||
print(f"\nAttempting to delete entry with date: {last_entry_date}")
|
||||
|
||||
# Perform the delete
|
||||
success = data_manager.delete_entry(last_entry_date)
|
||||
|
||||
if success:
|
||||
print("✓ Delete operation reported success")
|
||||
|
||||
# Reload data to verify deletion
|
||||
df_after = data_manager.load_data()
|
||||
print(f"✓ Data reloaded: {len(df_after)} entries (was {len(df)})")
|
||||
|
||||
# Check if the entry was actually deleted
|
||||
deleted_entry_exists = last_entry_date in df_after["date"].values
|
||||
if not deleted_entry_exists:
|
||||
print("✓ Entry successfully deleted from CSV")
|
||||
print("✓ Delete functionality is working correctly")
|
||||
return True
|
||||
else:
|
||||
print("✗ Entry still exists in CSV after delete operation")
|
||||
return False
|
||||
else:
|
||||
print("✗ Delete operation failed")
|
||||
return False
|
||||
|
||||
except Exception as e:
|
||||
print(f"✗ Error during delete test: {e}")
|
||||
import traceback
|
||||
|
||||
traceback.print_exc()
|
||||
return False
|
||||
|
||||
finally:
|
||||
# Restore the backup
|
||||
try:
|
||||
shutil.move("thechart_data_backup.csv", "thechart_data.csv")
|
||||
print("✓ Restored original CSV from backup")
|
||||
except Exception as e:
|
||||
print(f"✗ Failed to restore backup: {e}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_delete_functionality()
|
||||
@@ -1,114 +0,0 @@
|
||||
"""
|
||||
Direct test of dose calculation functionality.
|
||||
"""
|
||||
|
||||
import pandas as pd
|
||||
import pytest
|
||||
|
||||
|
||||
def calculate_daily_dose(dose_str: str) -> float:
|
||||
"""Calculate total daily dose from dose string format - copied from GraphManager."""
|
||||
if not dose_str or pd.isna(dose_str) or str(dose_str).lower() == "nan":
|
||||
return 0.0
|
||||
|
||||
total_dose = 0.0
|
||||
# Handle different separators and clean the string
|
||||
dose_str = str(dose_str).replace("•", "").strip()
|
||||
|
||||
# Split by | or by spaces if no | present
|
||||
dose_entries = dose_str.split("|") if "|" in dose_str else [dose_str]
|
||||
|
||||
for entry in dose_entries:
|
||||
entry = entry.strip()
|
||||
if not entry:
|
||||
continue
|
||||
|
||||
try:
|
||||
# Extract dose part after the last colon (timestamp:dose format)
|
||||
dose_part = entry.split(":")[-1] if ":" in entry else entry
|
||||
|
||||
# Extract numeric part from dose (e.g., "150mg" -> 150)
|
||||
dose_value = ""
|
||||
for char in dose_part:
|
||||
if char.isdigit() or char == ".":
|
||||
dose_value += char
|
||||
elif dose_value: # Stop at first non-digit after finding digits
|
||||
break
|
||||
|
||||
if dose_value:
|
||||
total_dose += float(dose_value)
|
||||
except (ValueError, IndexError):
|
||||
continue
|
||||
|
||||
return total_dose
|
||||
|
||||
|
||||
class TestDoseCalculation:
|
||||
"""Test dose calculation functionality."""
|
||||
|
||||
def test_standard_format(self):
|
||||
"""Test dose calculation with standard timestamp:dose format."""
|
||||
# Single dose
|
||||
dose_str = "2025-07-28 18:59:45:150mg"
|
||||
assert calculate_daily_dose(dose_str) == 150.0
|
||||
|
||||
# Multiple doses
|
||||
dose_str = "2025-07-28 18:59:45:150mg|2025-07-28 19:34:19:75mg"
|
||||
assert calculate_daily_dose(dose_str) == 225.0
|
||||
|
||||
def test_with_symbols(self):
|
||||
"""Test dose calculation with bullet symbols."""
|
||||
# With bullet symbols
|
||||
dose_str = "• • • • 2025-07-30 07:50:00:300"
|
||||
assert calculate_daily_dose(dose_str) == 300.0
|
||||
|
||||
def test_decimal_values(self):
|
||||
"""Test dose calculation with decimal values."""
|
||||
# Decimal dose
|
||||
dose_str = "2025-07-28 18:59:45:12.5mg"
|
||||
assert calculate_daily_dose(dose_str) == 12.5
|
||||
|
||||
# Multiple decimal doses
|
||||
dose_str = "2025-07-28 18:59:45:12.5mg|2025-07-28 19:34:19:7.5mg"
|
||||
assert calculate_daily_dose(dose_str) == 20.0
|
||||
|
||||
def test_no_timestamp_format(self):
|
||||
"""Test dose calculation without timestamps."""
|
||||
# Simple dose without timestamp
|
||||
dose_str = "100mg|50mg"
|
||||
assert calculate_daily_dose(dose_str) == 150.0
|
||||
|
||||
def test_mixed_format(self):
|
||||
"""Test dose calculation with mixed formats."""
|
||||
# Mixed format
|
||||
dose_str = "• 2025-07-30 22:50:00:10|75mg"
|
||||
assert calculate_daily_dose(dose_str) == 85.0
|
||||
|
||||
def test_edge_cases(self):
|
||||
"""Test dose calculation with edge cases."""
|
||||
# Empty string
|
||||
assert calculate_daily_dose("") == 0.0
|
||||
|
||||
# NaN value
|
||||
assert calculate_daily_dose("nan") == 0.0
|
||||
|
||||
# No units
|
||||
dose_str = "2025-07-28 18:59:45:10|2025-07-28 19:34:19:5"
|
||||
assert calculate_daily_dose(dose_str) == 15.0
|
||||
|
||||
def test_malformed_data(self):
|
||||
"""Test dose calculation with malformed data."""
|
||||
# Malformed data
|
||||
assert calculate_daily_dose("malformed:data") == 0.0
|
||||
assert calculate_daily_dose("::::") == 0.0
|
||||
assert calculate_daily_dose("2025-07-28:") == 0.0
|
||||
assert calculate_daily_dose("2025-07-28::mg") == 0.0
|
||||
|
||||
def test_partial_data(self):
|
||||
"""Test dose calculation with partial data."""
|
||||
# No units but valid dose
|
||||
assert calculate_daily_dose("2025-07-28 18:59:45:150") == 150.0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
pytest.main([__file__, "-v"])
|
||||
@@ -1,80 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Simple test of the dose parsing workflow."""
|
||||
|
||||
import sys
|
||||
|
||||
sys.path.append("src")
|
||||
|
||||
|
||||
# Test the fixed parsing workflow
|
||||
def test_dose_parsing():
|
||||
print("Testing dose parsing workflow...\n")
|
||||
|
||||
# Import UIManager after path setup
|
||||
import logging
|
||||
import tkinter as tk
|
||||
from unittest.mock import Mock
|
||||
|
||||
from ui_manager import UIManager
|
||||
|
||||
# Create minimal mocks
|
||||
root = tk.Tk()
|
||||
root.withdraw()
|
||||
logger = logging.getLogger("test")
|
||||
mock_medicine_manager = Mock()
|
||||
mock_pathology_manager = Mock()
|
||||
|
||||
# Create UIManager
|
||||
ui_manager = UIManager(root, logger, mock_medicine_manager, mock_pathology_manager)
|
||||
|
||||
# Test case 1: Simulate what happens in the UI
|
||||
print("1. Testing _populate_dose_history...")
|
||||
|
||||
# Mock text widget
|
||||
class MockText:
|
||||
def __init__(self):
|
||||
self.content = ""
|
||||
|
||||
def configure(self, state):
|
||||
pass
|
||||
|
||||
def delete(self, start, end):
|
||||
self.content = ""
|
||||
|
||||
def insert(self, pos, text):
|
||||
self.content = text
|
||||
|
||||
def get(self, start, end):
|
||||
return self.content
|
||||
|
||||
mock_text = MockText()
|
||||
saved_doses = "2025-01-30 08:00:00:150mg|2025-01-30 14:00:00:25mg"
|
||||
|
||||
ui_manager._populate_dose_history(mock_text, saved_doses)
|
||||
print(f"Populated display: '{mock_text.content}'")
|
||||
|
||||
# Test case 2: User adds a new dose
|
||||
print("\n2. Testing user editing...")
|
||||
user_edited = mock_text.content + "\n• 06:00 PM - 50mg"
|
||||
print(f"User edited content: '{user_edited}'")
|
||||
|
||||
# Test case 3: Parse back for saving
|
||||
print("\n3. Testing _parse_dose_history_for_saving...")
|
||||
parsed_result = ui_manager._parse_dose_history_for_saving(user_edited, "2025-01-30")
|
||||
print(f"Parsed for saving: '{parsed_result}'")
|
||||
|
||||
# Count doses
|
||||
dose_count = len([d for d in parsed_result.split("|") if d.strip()])
|
||||
print(f"Final dose count: {dose_count}")
|
||||
|
||||
if dose_count == 3:
|
||||
print("\n✅ SUCCESS: All 3 doses preserved!")
|
||||
return True
|
||||
else:
|
||||
print(f"\n❌ FAILURE: Expected 3 doses, got {dose_count}")
|
||||
return False
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
success = test_dose_parsing()
|
||||
sys.exit(0 if success else 1)
|
||||
@@ -1,110 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Quick test to verify dose tracking save functionality.
|
||||
"""
|
||||
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
import tkinter as tk
|
||||
|
||||
sys.path.append(os.path.join(os.path.dirname(__file__), "src"))
|
||||
|
||||
from medicine_manager import MedicineManager
|
||||
from pathology_manager import PathologyManager
|
||||
from ui_manager import UIManager
|
||||
|
||||
|
||||
def test_dose_save():
|
||||
"""Test that dose data is properly saved."""
|
||||
|
||||
# Setup logging
|
||||
logging.basicConfig(level=logging.DEBUG)
|
||||
logger = logging.getLogger("test")
|
||||
|
||||
# Initialize managers
|
||||
medicine_manager = MedicineManager()
|
||||
pathology_manager = PathologyManager()
|
||||
|
||||
# Create root window
|
||||
root = tk.Tk()
|
||||
root.withdraw()
|
||||
|
||||
# Initialize UI manager
|
||||
ui_manager = UIManager(
|
||||
root=root,
|
||||
logger=logger,
|
||||
medicine_manager=medicine_manager,
|
||||
pathology_manager=pathology_manager,
|
||||
)
|
||||
|
||||
# Create test data
|
||||
test_values = ["2025-07-31"] # date
|
||||
|
||||
# Add pathology values
|
||||
pathologies = pathology_manager.get_all_pathologies()
|
||||
for _ in pathologies:
|
||||
test_values.append(3) # pathology value
|
||||
|
||||
# Add medicine values and doses
|
||||
medicines = medicine_manager.get_all_medicines()
|
||||
for _ in medicines:
|
||||
test_values.append(1) # medicine checkbox value
|
||||
test_values.append(
|
||||
"2025-07-31 08:00:00:150mg|2025-07-31 14:00:00:25mg"
|
||||
) # existing doses in storage format
|
||||
|
||||
test_values.append("Test note") # note
|
||||
|
||||
print(f"Test values: {test_values}")
|
||||
|
||||
# Track what gets saved
|
||||
saved_data = None
|
||||
|
||||
def mock_save_callback(*args):
|
||||
nonlocal saved_data
|
||||
saved_data = args
|
||||
print(f"Save callback called with {len(args)} arguments")
|
||||
print(f"Arguments: {args}")
|
||||
|
||||
if len(args) >= 2:
|
||||
dose_data = args[-1] # Last argument should be dose data
|
||||
print(f"Dose data type: {type(dose_data)}")
|
||||
print(f"Dose data: {dose_data}")
|
||||
|
||||
if isinstance(dose_data, dict):
|
||||
for med_key, dose_str in dose_data.items():
|
||||
print(f" {med_key}: '{dose_str}'")
|
||||
|
||||
# Don't destroy window, just close it
|
||||
root.quit()
|
||||
|
||||
def mock_delete_callback(win):
|
||||
print("Delete callback called")
|
||||
win.destroy()
|
||||
root.quit()
|
||||
|
||||
callbacks = {"save": mock_save_callback, "delete": mock_delete_callback}
|
||||
|
||||
# Create edit window
|
||||
edit_window = ui_manager.create_edit_window(tuple(test_values), callbacks)
|
||||
print("Edit window created, please test dose tracking and save...")
|
||||
|
||||
# Show the window so user can interact
|
||||
root.deiconify()
|
||||
edit_window.lift()
|
||||
edit_window.focus_force()
|
||||
|
||||
# Run main loop
|
||||
root.mainloop()
|
||||
|
||||
if saved_data:
|
||||
print("✅ Test completed - data was saved")
|
||||
return True
|
||||
else:
|
||||
print("❌ Test failed - no data saved")
|
||||
return False
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_dose_save()
|
||||
@@ -1,135 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Test dose tracking functionality programmatically.
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
import tkinter as tk
|
||||
|
||||
sys.path.append(os.path.join(os.path.dirname(__file__), "src"))
|
||||
|
||||
import logging
|
||||
|
||||
from data_manager import DataManager
|
||||
from medicine_manager import MedicineManager
|
||||
from pathology_manager import PathologyManager
|
||||
from ui_manager import UIManager
|
||||
|
||||
|
||||
def test_dose_save_programmatically():
|
||||
"""Test dose saving functionality without UI interaction."""
|
||||
|
||||
# Setup logging
|
||||
logging.basicConfig(level=logging.DEBUG)
|
||||
logger = logging.getLogger("test")
|
||||
|
||||
# Initialize managers
|
||||
medicine_manager = MedicineManager()
|
||||
pathology_manager = PathologyManager()
|
||||
|
||||
# Create temporary CSV file
|
||||
with tempfile.NamedTemporaryFile(mode="w", suffix=".csv", delete=False) as f:
|
||||
temp_csv = f.name
|
||||
|
||||
try:
|
||||
# Create data manager
|
||||
data_manager = DataManager(
|
||||
temp_csv, logger, medicine_manager, pathology_manager
|
||||
)
|
||||
|
||||
# Create root window (hidden)
|
||||
root = tk.Tk()
|
||||
root.withdraw()
|
||||
|
||||
# Initialize UI manager
|
||||
ui_manager = UIManager(
|
||||
root=root,
|
||||
logger=logger,
|
||||
medicine_manager=medicine_manager,
|
||||
pathology_manager=pathology_manager,
|
||||
)
|
||||
|
||||
# Test the parsing directly
|
||||
test_dose_text = "• 08:00 AM - 150mg\n• 02:00 PM - 25mg"
|
||||
date_str = "2025-07-31"
|
||||
|
||||
print("Testing dose parsing...")
|
||||
parsed_result = ui_manager._parse_dose_history_for_saving(
|
||||
test_dose_text, date_str
|
||||
)
|
||||
print(f"Input: {test_dose_text}")
|
||||
print(f"Date: {date_str}")
|
||||
print(f"Parsed result: {parsed_result}")
|
||||
|
||||
# Verify the format is correct
|
||||
if "|" in parsed_result:
|
||||
doses = parsed_result.split("|")
|
||||
print(f"Number of parsed doses: {len(doses)}")
|
||||
for i, dose in enumerate(doses):
|
||||
print(f" Dose {i + 1}: {dose}")
|
||||
# Should be in format: YYYY-MM-DD HH:MM:SS:dose
|
||||
if ":" in dose and len(dose.split(":")) >= 4:
|
||||
print(" ✅ Dose format looks correct")
|
||||
else:
|
||||
print(" ❌ Dose format looks incorrect")
|
||||
|
||||
# Test with simple format
|
||||
print("\nTesting simple format...")
|
||||
simple_test = "08:00: 150mg\n14:00: 25mg"
|
||||
simple_result = ui_manager._parse_dose_history_for_saving(simple_test, date_str)
|
||||
print(f"Input: {simple_test}")
|
||||
print(f"Parsed result: {simple_result}")
|
||||
|
||||
# Test saving to data manager
|
||||
print("\nTesting data save...")
|
||||
|
||||
# Create entry data in the expected format
|
||||
entry_data = ["2025-07-31"] # date
|
||||
|
||||
# Add pathology values
|
||||
pathologies = pathology_manager.get_all_pathologies()
|
||||
for _ in pathologies:
|
||||
entry_data.append(3) # pathology value
|
||||
|
||||
# Add medicine values and doses
|
||||
medicines = medicine_manager.get_all_medicines()
|
||||
for med_key in medicines:
|
||||
entry_data.append(1) # medicine checkbox value
|
||||
# Use the parsed result for the dose
|
||||
if med_key == "bupropion": # Test with first medicine
|
||||
entry_data.append(parsed_result)
|
||||
else:
|
||||
entry_data.append("") # Empty doses for other medicines
|
||||
|
||||
entry_data.append("Test note") # note
|
||||
|
||||
print(f"Entry data length: {len(entry_data)}")
|
||||
print(f"Entry data: {entry_data}")
|
||||
|
||||
# Try to add the entry
|
||||
success = data_manager.add_entry(entry_data)
|
||||
print(f"Data manager add_entry result: {success}")
|
||||
|
||||
if success:
|
||||
# Load data back and check
|
||||
df = data_manager.load_data()
|
||||
print(f"Data loaded back, shape: {df.shape}")
|
||||
if len(df) > 0:
|
||||
bupropion_doses = df.iloc[0]["bupropion_doses"]
|
||||
print(f"Saved bupropion doses: '{bupropion_doses}'")
|
||||
print("✅ Dose data was successfully saved and retrieved!")
|
||||
else:
|
||||
print("❌ No data found after saving")
|
||||
else:
|
||||
print("❌ Failed to save entry to data manager")
|
||||
|
||||
finally:
|
||||
# Clean up
|
||||
os.unlink(temp_csv)
|
||||
root.destroy()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_dose_save_programmatically()
|
||||
@@ -1,55 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Test script to demonstrate the dose tracking functionality.
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
from datetime import datetime
|
||||
|
||||
sys.path.append(os.path.join(os.path.dirname(__file__), "src"))
|
||||
|
||||
from src.data_manager import DataManager
|
||||
from src.init import logger
|
||||
|
||||
|
||||
def test_dose_tracking():
|
||||
"""Test the dose tracking functionality."""
|
||||
|
||||
# Initialize data manager
|
||||
data_manager = DataManager("thechart_data.csv", logger)
|
||||
|
||||
# Test adding a dose
|
||||
today = datetime.now().strftime("%m/%d/%Y")
|
||||
print(f"Testing dose tracking for date: {today}")
|
||||
|
||||
# Add some test doses
|
||||
test_doses = [
|
||||
("bupropion", "150mg"),
|
||||
("propranolol", "10mg"),
|
||||
("bupropion", "150mg"), # Second dose of same medicine
|
||||
]
|
||||
|
||||
for medicine, dose in test_doses:
|
||||
success = data_manager.add_medicine_dose(today, medicine, dose)
|
||||
if success:
|
||||
print(f"✓ Added {medicine} dose: {dose}")
|
||||
else:
|
||||
print(f"✗ Failed to add {medicine} dose: {dose}")
|
||||
|
||||
# Retrieve and display doses
|
||||
print(f"\nDoses recorded for {today}:")
|
||||
medicines = ["bupropion", "hydroxyzine", "gabapentin", "propranolol"]
|
||||
|
||||
for medicine in medicines:
|
||||
doses = data_manager.get_today_medicine_doses(today, medicine)
|
||||
if doses:
|
||||
print(f"{medicine.title()}:")
|
||||
for timestamp, dose in doses:
|
||||
print(f" - {timestamp}: {dose}")
|
||||
else:
|
||||
print(f"{medicine.title()}: No doses recorded")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_dose_tracking()
|
||||
@@ -1,157 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Test the dose tracking functionality of the edit window.
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import tkinter as tk
|
||||
|
||||
sys.path.append(os.path.join(os.path.dirname(__file__), "..", "src"))
|
||||
|
||||
from medicine_manager import MedicineManager
|
||||
from pathology_manager import PathologyManager
|
||||
from ui_manager import UIManager
|
||||
|
||||
|
||||
def test_dose_tracking_ui():
|
||||
"""Test that the dose tracking UI functionality works."""
|
||||
print("Testing dose tracking UI functionality...")
|
||||
|
||||
# Initialize managers
|
||||
medicine_manager = MedicineManager()
|
||||
pathology_manager = PathologyManager()
|
||||
|
||||
# Create a simple logger
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger("test")
|
||||
logger.setLevel(logging.INFO)
|
||||
|
||||
# Create root window
|
||||
root = tk.Tk()
|
||||
root.withdraw()
|
||||
|
||||
# Initialize UI manager
|
||||
ui_manager = UIManager(
|
||||
root=root,
|
||||
logger=logger,
|
||||
medicine_manager=medicine_manager,
|
||||
pathology_manager=pathology_manager,
|
||||
)
|
||||
|
||||
# Test data with existing doses
|
||||
test_values = ["2025-07-31"] # date
|
||||
|
||||
# Add pathology values
|
||||
pathologies = pathology_manager.get_all_pathologies()
|
||||
for _pathology_key, _pathology in pathologies.items():
|
||||
test_values.append(5) # pathology value
|
||||
|
||||
# Add medicine values and doses with some existing data
|
||||
medicines = medicine_manager.get_all_medicines()
|
||||
for _medicine_key in medicines:
|
||||
test_values.append(1) # medicine checkbox value
|
||||
test_values.append("08:00: 150mg\n14:00: 25mg") # existing doses
|
||||
|
||||
test_values.append("Test dose tracking") # note
|
||||
|
||||
print(f"Created test data with {len(test_values)} values")
|
||||
|
||||
# Mock callbacks that will check the dose data
|
||||
dose_tracking_working = False
|
||||
saved_dose_data = None
|
||||
|
||||
def mock_save_callback(*args):
|
||||
nonlocal dose_tracking_working, saved_dose_data
|
||||
if len(args) >= 2:
|
||||
saved_dose_data = args[-1] # dose_data should be last argument
|
||||
print(f"✅ Save called with dose data: {saved_dose_data}")
|
||||
|
||||
# Check if dose data contains all expected medicines
|
||||
expected_medicines = set(medicines.keys())
|
||||
actual_medicines = (
|
||||
set(saved_dose_data.keys())
|
||||
if isinstance(saved_dose_data, dict)
|
||||
else set()
|
||||
)
|
||||
|
||||
if expected_medicines == actual_medicines:
|
||||
dose_tracking_working = True
|
||||
print("✅ All medicines present in dose data")
|
||||
else:
|
||||
print(
|
||||
f"❌ Medicine mismatch. Expected: {expected_medicines}, "
|
||||
f"Got: {actual_medicines}"
|
||||
)
|
||||
else:
|
||||
print("❌ Save callback called with insufficient arguments")
|
||||
|
||||
def mock_delete_callback(win):
|
||||
print("✅ Delete callback called")
|
||||
win.destroy()
|
||||
|
||||
callbacks = {"save": mock_save_callback, "delete": mock_delete_callback}
|
||||
|
||||
try:
|
||||
# Create edit window
|
||||
edit_window = ui_manager.create_edit_window(tuple(test_values), callbacks)
|
||||
print("✅ Edit window with dose tracking created successfully")
|
||||
|
||||
# Test the mock save to check dose data structure
|
||||
print("\nTesting dose data extraction...")
|
||||
mock_save_callback(
|
||||
edit_window, # window
|
||||
"2025-07-31", # date
|
||||
*[5] * len(pathologies), # pathology values
|
||||
*[1] * len(medicines), # medicine values
|
||||
"Test note", # note
|
||||
{med: "08:00: 150mg\n14:00: 25mg" for med in medicines}, # dose_data
|
||||
)
|
||||
|
||||
# Check that dose tracking variables are properly created
|
||||
print("\nChecking dose tracking UI elements...")
|
||||
|
||||
medicine_count = len(medicines)
|
||||
|
||||
print(f"✅ Should have dose tracking for {medicine_count} medicines:")
|
||||
for medicine_key, medicine in medicines.items():
|
||||
print(f" - {medicine_key}: {medicine.display_name}")
|
||||
|
||||
print(f"✅ Expected dose entry fields: {medicine_count}")
|
||||
print(f"✅ Expected dose history areas: {medicine_count}")
|
||||
print(f"✅ Expected punch buttons: {medicine_count}")
|
||||
|
||||
if dose_tracking_working and saved_dose_data:
|
||||
print("✅ Dose tracking data structure is correct")
|
||||
|
||||
# Verify each medicine has dose data
|
||||
for medicine_key in medicines:
|
||||
if medicine_key in saved_dose_data:
|
||||
dose_value = saved_dose_data[medicine_key]
|
||||
print(f"✅ {medicine_key} dose data: '{dose_value}'")
|
||||
else:
|
||||
print(f"❌ Missing dose data for {medicine_key}")
|
||||
return False
|
||||
|
||||
edit_window.destroy()
|
||||
root.quit()
|
||||
|
||||
return dose_tracking_working
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ Error testing dose tracking: {e}")
|
||||
import traceback
|
||||
|
||||
traceback.print_exc()
|
||||
return False
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
success = test_dose_tracking_ui()
|
||||
if success:
|
||||
print("\n🎉 Dose tracking UI functionality test passed!")
|
||||
print("Dose tracking is working with the dynamic system!")
|
||||
else:
|
||||
print("\n💥 Dose tracking UI functionality test failed!")
|
||||
sys.exit(1)
|
||||
@@ -1,70 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Simple test for dynamic edit window creation without GUI display.
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
|
||||
sys.path.append(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_dynamic_edit_data():
|
||||
"""Test that we can create dynamic edit data structures."""
|
||||
print("Testing dynamic edit data creation...")
|
||||
|
||||
# Initialize managers
|
||||
medicine_manager = MedicineManager()
|
||||
pathology_manager = PathologyManager()
|
||||
|
||||
# Load configurations
|
||||
pathologies = pathology_manager.get_all_pathologies()
|
||||
medicines = medicine_manager.get_all_medicines()
|
||||
|
||||
print(f"✅ Loaded {len(pathologies)} pathologies:")
|
||||
for key, pathology in pathologies.items():
|
||||
print(f" - {key}: {pathology.display_name} ({pathology.scale_info})")
|
||||
|
||||
print(f"✅ Loaded {len(medicines)} medicines:")
|
||||
for key, medicine in medicines.items():
|
||||
print(f" - {key}: {medicine.display_name} ({medicine.dosage_info})")
|
||||
|
||||
# Test data creation
|
||||
test_data = {"Date": "2025-07-31", "Note": "Test entry"}
|
||||
|
||||
# Add pathology values
|
||||
for pathology_key in pathologies:
|
||||
test_data[pathology_key] = 3
|
||||
|
||||
# Add medicine values
|
||||
for medicine_key in medicines:
|
||||
test_data[medicine_key] = 1
|
||||
test_data[f"{medicine_key}_doses"] = "08:00: 25mg"
|
||||
|
||||
print(f"✅ Created test data with {len(test_data)} fields")
|
||||
|
||||
# Test data manager
|
||||
data_manager = DataManager(
|
||||
csv_file="thechart_data.csv",
|
||||
medicine_manager=medicine_manager,
|
||||
pathology_manager=pathology_manager,
|
||||
)
|
||||
|
||||
# Check dynamic columns
|
||||
expected_columns = data_manager.get_expected_columns()
|
||||
print(f"✅ Data manager expects {len(expected_columns)} columns:")
|
||||
for col in expected_columns:
|
||||
print(f" - {col}")
|
||||
|
||||
print("\n🎉 All dynamic data tests passed!")
|
||||
print("The pathology system is fully dynamic and integrated!")
|
||||
|
||||
return True
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_dynamic_edit_data()
|
||||
@@ -1,87 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Test script to verify the enhanced edit functionality with dose tracking.
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
|
||||
# Add src to path
|
||||
sys.path.append(os.path.join(os.path.dirname(__file__), "src"))
|
||||
|
||||
from src.data_manager import DataManager
|
||||
from src.init import logger
|
||||
|
||||
|
||||
def test_edit_functionality():
|
||||
"""Test the edit functionality with dose tracking."""
|
||||
|
||||
# Initialize data manager
|
||||
data_manager = DataManager("thechart_data.csv", logger)
|
||||
|
||||
print("Testing edit functionality with dose tracking...")
|
||||
|
||||
# Test date
|
||||
test_date = "07/28/2025"
|
||||
|
||||
# First, add some test doses to the date
|
||||
test_doses = [
|
||||
("bupropion", "150mg"),
|
||||
("propranolol", "10mg"),
|
||||
]
|
||||
|
||||
print(f"\n1. Adding test doses for {test_date}:")
|
||||
for medicine, dose in test_doses:
|
||||
success = data_manager.add_medicine_dose(test_date, medicine, dose)
|
||||
if success:
|
||||
print(f" ✓ Added {medicine}: {dose}")
|
||||
else:
|
||||
print(f" ✗ Failed to add {medicine}: {dose}")
|
||||
|
||||
# Test retrieving dose data (simulating edit window opening)
|
||||
print("\n2. Retrieving dose data for edit window:")
|
||||
medicines = ["bupropion", "hydroxyzine", "gabapentin", "propranolol"]
|
||||
|
||||
dose_data = {}
|
||||
for medicine in medicines:
|
||||
doses = data_manager.get_today_medicine_doses(test_date, medicine)
|
||||
dose_str = "|".join([f"{ts}:{dose}" for ts, dose in doses])
|
||||
dose_data[medicine] = dose_str
|
||||
|
||||
if dose_str:
|
||||
print(f" {medicine}: {dose_str}")
|
||||
else:
|
||||
print(f" {medicine}: No doses")
|
||||
|
||||
# Test CSV structure compatibility
|
||||
print("\n3. Testing CSV structure:")
|
||||
df = data_manager.load_data()
|
||||
if not df.empty:
|
||||
# Get a row with dose data
|
||||
test_row = df[df["date"] == test_date]
|
||||
if not test_row.empty:
|
||||
values = test_row.iloc[0].tolist()
|
||||
print(f" CSV columns: {len(df.columns)}")
|
||||
print(
|
||||
" Expected: 14 columns (date, dep, anx, slp, app, bup, "
|
||||
"bup_doses, ...)"
|
||||
)
|
||||
print(f" Values for {test_date}: {len(values)} values")
|
||||
|
||||
# Test unpacking like the edit window would
|
||||
if len(values) == 14:
|
||||
print(" ✓ CSV structure compatible with edit functionality")
|
||||
else:
|
||||
print(f" ⚠ Unexpected number of values: {len(values)}")
|
||||
else:
|
||||
print(f" No data found for {test_date}")
|
||||
|
||||
print("\n4. Edit functionality test summary:")
|
||||
print(" ✓ Dose data retrieval working")
|
||||
print(" ✓ CSV structure supports edit operations")
|
||||
print(" ✓ Dose preservation logic implemented")
|
||||
print("\nEdit functionality is ready for testing in the GUI!")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_edit_functionality()
|
||||
@@ -1,175 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Test script for the dynamic edit window functionality.
|
||||
Tests that the edit window properly handles dynamic pathologies and medicines.
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import tkinter as tk
|
||||
|
||||
sys.path.append(os.path.join(os.path.dirname(__file__), "..", "src"))
|
||||
|
||||
from data_manager import DataManager
|
||||
from medicine_manager import MedicineManager
|
||||
from pathology_manager import PathologyManager
|
||||
from ui_manager import UIManager
|
||||
|
||||
|
||||
def test_edit_window():
|
||||
"""Test the edit window with dynamic pathologies and medicines."""
|
||||
print("Testing edit window with dynamic pathologies and medicines...")
|
||||
|
||||
# Initialize managers
|
||||
medicine_manager = MedicineManager()
|
||||
pathology_manager = PathologyManager()
|
||||
data_manager = DataManager(
|
||||
csv_file="thechart_data.csv",
|
||||
medicine_manager=medicine_manager,
|
||||
pathology_manager=pathology_manager,
|
||||
)
|
||||
|
||||
# Create root window
|
||||
root = tk.Tk()
|
||||
root.withdraw() # Hide main window for testing
|
||||
|
||||
# Initialize UI manager
|
||||
ui_manager = UIManager(
|
||||
root=root,
|
||||
data_manager=data_manager,
|
||||
medicine_manager=medicine_manager,
|
||||
pathology_manager=pathology_manager,
|
||||
)
|
||||
|
||||
# Test data - create a sample row
|
||||
test_data = {"Date": "2025-07-31", "Note": "Test entry for edit window"}
|
||||
|
||||
# Add pathology values dynamically
|
||||
pathologies = pathology_manager.get_all_pathologies()
|
||||
for pathology_key, _pathology in pathologies.items():
|
||||
test_data[pathology_key] = 3 # Mid-range value
|
||||
|
||||
# Add medicine values dynamically
|
||||
medicines = medicine_manager.get_all_medicines()
|
||||
for medicine_key in medicines:
|
||||
test_data[medicine_key] = 1 # Taken
|
||||
test_data[f"{medicine_key}_doses"] = "08:00: 25mg\n14:00: 25mg"
|
||||
|
||||
print(
|
||||
f"Test data created with {len(pathologies)} pathologies "
|
||||
f"and {len(medicines)} medicines"
|
||||
)
|
||||
|
||||
# Create edit window
|
||||
try:
|
||||
edit_window = ui_manager.create_edit_window(0, test_data)
|
||||
print("✅ Edit window created successfully!")
|
||||
|
||||
# Check that the window has the expected pathology controls
|
||||
pathology_count = len(pathologies)
|
||||
medicine_count = len(medicines)
|
||||
|
||||
print(f"✅ Edit window should contain {pathology_count} pathology scales")
|
||||
print(f"✅ Edit window should contain {medicine_count} medicine checkboxes")
|
||||
print(
|
||||
f"✅ Edit window should contain dose tracking for "
|
||||
f"{medicine_count} medicines"
|
||||
)
|
||||
|
||||
# Show the window briefly to verify it renders
|
||||
edit_window.deiconify()
|
||||
# Close after 2 seconds
|
||||
root.after(2000, lambda: (edit_window.destroy(), root.quit()))
|
||||
root.mainloop()
|
||||
|
||||
print("✅ Edit window displayed and closed without errors!")
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ Error creating edit window: {e}")
|
||||
import traceback
|
||||
|
||||
traceback.print_exc()
|
||||
return False
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
success = test_edit_window()
|
||||
if success:
|
||||
print("All edit window tests passed!")
|
||||
print(
|
||||
"The edit window is now fully dynamic and supports "
|
||||
"user-managed pathologies!"
|
||||
)
|
||||
else:
|
||||
print("💥 Edit window test failed!")
|
||||
sys.exit(1)
|
||||
|
||||
root = tk.Tk()
|
||||
root.withdraw() # Hide main window for testing
|
||||
|
||||
# Initialize managers for this block
|
||||
medicine_manager = MedicineManager()
|
||||
pathology_manager = PathologyManager()
|
||||
data_manager = DataManager(
|
||||
csv_file="thechart_data.csv",
|
||||
medicine_manager=medicine_manager,
|
||||
pathology_manager=pathology_manager,
|
||||
)
|
||||
|
||||
# You may need to define or import 'logger' as well, or remove it if not needed.
|
||||
# For now, let's assume logger is not required and remove it from the UIManager
|
||||
# call.
|
||||
ui_manager = UIManager(
|
||||
root=root,
|
||||
data_manager=data_manager,
|
||||
medicine_manager=medicine_manager,
|
||||
pathology_manager=pathology_manager,
|
||||
)
|
||||
|
||||
# Sample data for testing (16 fields format)
|
||||
test_values = (
|
||||
"12/25/2024", # date
|
||||
7, # depression
|
||||
5, # anxiety
|
||||
6, # sleep
|
||||
4, # appetite
|
||||
1, # bupropion
|
||||
"09:00:00:150|18:00:00:150", # bupropion_doses
|
||||
1, # hydroxyzine
|
||||
"21:30:00:25", # hydroxyzine_doses
|
||||
0, # gabapentin
|
||||
"", # gabapentin_doses
|
||||
1, # propranolol
|
||||
"07:00:00:10|14:00:00:10", # propranolol_doses
|
||||
0, # quetiapine
|
||||
"", # quetiapine_doses
|
||||
# Had a good day overall, feeling better with new medication routine
|
||||
"Had a good day overall, feeling better with the new medication routine.",
|
||||
)
|
||||
|
||||
# Mock callbacks
|
||||
def save_callback(win, *args):
|
||||
print("Save called with args:", args)
|
||||
win.destroy()
|
||||
|
||||
def delete_callback(win):
|
||||
print("Delete called")
|
||||
win.destroy()
|
||||
|
||||
callbacks = {"save": save_callback, "delete": delete_callback}
|
||||
|
||||
# Create the improved edit window
|
||||
edit_win = ui_manager.create_edit_window(test_values, callbacks)
|
||||
|
||||
# Center the edit window
|
||||
edit_win.update_idletasks()
|
||||
x = (edit_win.winfo_screenwidth() // 2) - (edit_win.winfo_width() // 2)
|
||||
y = (edit_win.winfo_screenheight() // 2) - (edit_win.winfo_height() // 2)
|
||||
edit_win.geometry(f"+{x}+{y}")
|
||||
|
||||
root.mainloop()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_edit_window()
|
||||
@@ -1,106 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Test script for the dynamic edit window functionality.
|
||||
Tests that the edit window properly handles dynamic pathologies and medicines.
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import tkinter as tk
|
||||
|
||||
sys.path.append(os.path.join(os.path.dirname(__file__), "..", "src"))
|
||||
|
||||
from data_manager import DataManager
|
||||
from medicine_manager import MedicineManager
|
||||
from pathology_manager import PathologyManager
|
||||
from ui_manager import UIManager
|
||||
|
||||
|
||||
def test_edit_window():
|
||||
"""Test the edit window with dynamic pathologies and medicines."""
|
||||
print("Testing edit window with dynamic pathologies and medicines...")
|
||||
|
||||
# Initialize managers
|
||||
medicine_manager = MedicineManager()
|
||||
pathology_manager = PathologyManager()
|
||||
data_manager = DataManager(
|
||||
csv_file="thechart_data.csv",
|
||||
medicine_manager=medicine_manager,
|
||||
pathology_manager=pathology_manager,
|
||||
)
|
||||
|
||||
# Create root window
|
||||
root = tk.Tk()
|
||||
root.withdraw() # Hide main window for testing
|
||||
|
||||
# Initialize UI manager
|
||||
ui_manager = UIManager(
|
||||
root=root,
|
||||
data_manager=data_manager,
|
||||
medicine_manager=medicine_manager,
|
||||
pathology_manager=pathology_manager,
|
||||
)
|
||||
|
||||
# Test data - create a sample row
|
||||
test_data = {"Date": "2025-07-31", "Note": "Test entry for edit window"}
|
||||
|
||||
# Add pathology values dynamically
|
||||
pathologies = pathology_manager.get_all_pathologies()
|
||||
for pathology_key, _pathology in pathologies.items():
|
||||
test_data[pathology_key] = 3 # Mid-range value
|
||||
|
||||
# Add medicine values dynamically
|
||||
medicines = medicine_manager.get_all_medicines()
|
||||
for medicine_key in medicines:
|
||||
test_data[medicine_key] = 1 # Taken
|
||||
test_data[f"{medicine_key}_doses"] = "08:00: 25mg"
|
||||
|
||||
print(
|
||||
f"Test data created with {len(pathologies)} pathologies "
|
||||
f"and {len(medicines)} medicines"
|
||||
)
|
||||
|
||||
# Create edit window
|
||||
try:
|
||||
edit_window = ui_manager.create_edit_window(0, test_data)
|
||||
print("✅ Edit window created successfully!")
|
||||
|
||||
# Check that the window has the expected pathology controls
|
||||
pathology_count = len(pathologies)
|
||||
medicine_count = len(medicines)
|
||||
|
||||
print(f"✅ Edit window should contain {pathology_count} pathology scales")
|
||||
print(f"✅ Edit window should contain {medicine_count} medicine checkboxes")
|
||||
print(
|
||||
f"✅ Edit window should contain dose tracking for "
|
||||
f"{medicine_count} medicines"
|
||||
)
|
||||
|
||||
# Show the window briefly to verify it renders
|
||||
edit_window.deiconify()
|
||||
# Close after 2 seconds
|
||||
root.after(2000, lambda: (edit_window.destroy(), root.quit()))
|
||||
root.mainloop()
|
||||
|
||||
print("✅ Edit window displayed and closed without errors!")
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ Error creating edit window: {e}")
|
||||
import traceback
|
||||
|
||||
traceback.print_exc()
|
||||
return False
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
success = test_edit_window()
|
||||
if success:
|
||||
print("\n🎉 All edit window tests passed!")
|
||||
print(
|
||||
"The edit window is now fully dynamic and supports "
|
||||
"user-managed pathologies!"
|
||||
)
|
||||
else:
|
||||
print("\n💥 Edit window test failed!")
|
||||
sys.exit(1)
|
||||
@@ -1,146 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Test the complete dose tracking workflow after fixing the parsing issues."""
|
||||
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
from unittest.mock import Mock
|
||||
|
||||
import pandas as pd
|
||||
|
||||
sys.path.append("src")
|
||||
from data_manager import DataManager
|
||||
from ui_manager import UIManager
|
||||
|
||||
|
||||
def test_dose_workflow():
|
||||
"""Test that doses are preserved when editing through the UI."""
|
||||
|
||||
# Create temporary directory and CSV file
|
||||
temp_dir = tempfile.mkdtemp()
|
||||
csv_file = os.path.join(temp_dir, "test.csv")
|
||||
print(f"Using temporary CSV: {csv_file}")
|
||||
|
||||
try:
|
||||
# Create mock managers with known configurations
|
||||
mock_medicine_manager = Mock()
|
||||
mock_medicine_manager.get_dynamic_columns.return_value = [
|
||||
"Medicine A",
|
||||
"Medicine B",
|
||||
]
|
||||
mock_medicine_manager.get_medicines.return_value = {
|
||||
"med1": {"name": "Medicine A"},
|
||||
"med2": {"name": "Medicine B"},
|
||||
}
|
||||
mock_medicine_manager.get_medicine_keys.return_value = ["med1", "med2"]
|
||||
|
||||
mock_pathology_manager = Mock()
|
||||
mock_pathology_manager.get_dynamic_columns.return_value = [
|
||||
"Pathology X",
|
||||
"Pathology Y",
|
||||
]
|
||||
mock_pathology_manager.get_pathology_keys.return_value = ["path1", "path2"]
|
||||
|
||||
# Create DataManager and UIManager
|
||||
import logging
|
||||
import tkinter as tk
|
||||
|
||||
logger = logging.getLogger("test")
|
||||
root = tk.Tk()
|
||||
root.withdraw() # Hide the window during testing
|
||||
|
||||
data_manager = DataManager(
|
||||
csv_file, logger, mock_medicine_manager, mock_pathology_manager
|
||||
)
|
||||
ui_manager = UIManager(
|
||||
root, logger, mock_medicine_manager, mock_pathology_manager
|
||||
)
|
||||
|
||||
# Add initial entry with some doses
|
||||
print("\n1. Adding initial entry with two doses...")
|
||||
initial_data = {
|
||||
"Date": "2025-01-30",
|
||||
"Depression": 3,
|
||||
"Anxiety": 4,
|
||||
"Sleep": 7,
|
||||
"Appetite": 6,
|
||||
"Medicine A": "2025-01-30 08:00:00:150mg|2025-01-30 14:00:00:25mg",
|
||||
"Medicine B": "",
|
||||
"Pathology X": 2,
|
||||
"Pathology Y": 1,
|
||||
"Notes": "Initial entry",
|
||||
}
|
||||
data_manager.add_entry(initial_data)
|
||||
|
||||
# Check what was saved
|
||||
df = pd.read_csv(csv_file)
|
||||
print(f'Medicine A after initial save: "{df.iloc[0]["Medicine A"]}"')
|
||||
|
||||
# Now simulate the UI editing workflow
|
||||
print("\n2. Simulating UI edit workflow...")
|
||||
|
||||
# Get the saved data (as it would appear in edit window)
|
||||
saved_medicine_a = df.iloc[0]["Medicine A"]
|
||||
print(f'Saved Medicine A doses: "{saved_medicine_a}"')
|
||||
|
||||
# Create mock text widget to simulate _populate_dose_history
|
||||
class MockText:
|
||||
def __init__(self):
|
||||
self.content = ""
|
||||
|
||||
def configure(self, state):
|
||||
pass
|
||||
|
||||
def delete(self, start, end):
|
||||
self.content = ""
|
||||
|
||||
def insert(self, pos, text):
|
||||
self.content = text
|
||||
|
||||
def get(self, start, end):
|
||||
return self.content
|
||||
|
||||
mock_text = MockText()
|
||||
ui_manager._populate_dose_history(mock_text, saved_medicine_a)
|
||||
print(f'UI display after _populate_dose_history: "{mock_text.content}"')
|
||||
|
||||
# Simulate user adding a new dose to the text widget
|
||||
user_edited_content = mock_text.content + "\n• 06:00 PM - 50mg"
|
||||
print(f'User adds new dose, text widget now contains: "{user_edited_content}"')
|
||||
|
||||
# Parse this back for saving
|
||||
parsed_doses = ui_manager._parse_dose_history_for_saving(
|
||||
user_edited_content, "2025-01-30"
|
||||
)
|
||||
print(f'Parsed for saving: "{parsed_doses}"')
|
||||
|
||||
# Update the entry
|
||||
update_data = initial_data.copy()
|
||||
update_data["Medicine A"] = parsed_doses
|
||||
data_manager.update_entry("2025-01-30", update_data)
|
||||
|
||||
# Check final result
|
||||
df = pd.read_csv(csv_file)
|
||||
final_medicine_a = df.iloc[0]["Medicine A"]
|
||||
print(f'\n3. Final Medicine A after update: "{final_medicine_a}"')
|
||||
|
||||
# Count doses
|
||||
dose_count = len([d for d in final_medicine_a.split("|") if d.strip()])
|
||||
print(f"Final dose count: {dose_count}")
|
||||
|
||||
if dose_count == 3:
|
||||
print("✅ SUCCESS: All doses preserved!")
|
||||
return True
|
||||
else:
|
||||
print("❌ FAILURE: Doses were lost!")
|
||||
return False
|
||||
|
||||
finally:
|
||||
# Clean up
|
||||
shutil.rmtree(temp_dir)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
success = test_dose_workflow()
|
||||
sys.exit(0 if success else 1)
|
||||
@@ -1,42 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Simple test to check if the medicine manager works correctly.
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
|
||||
# Add src to path
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "src"))
|
||||
|
||||
from init import logger
|
||||
from medicine_manager import MedicineManager
|
||||
|
||||
|
||||
def test_medicine_manager():
|
||||
"""Test the medicine manager functionality."""
|
||||
print("Testing MedicineManager...")
|
||||
|
||||
# Create medicine manager
|
||||
medicine_manager = MedicineManager(logger=logger)
|
||||
|
||||
# Test getting all medicines
|
||||
medicines = medicine_manager.get_all_medicines()
|
||||
print(f"Found {len(medicines)} medicines:")
|
||||
for key, medicine in medicines.items():
|
||||
print(f" - {key}: {medicine.display_name} ({medicine.dosage_info})")
|
||||
|
||||
# Test getting medicine keys
|
||||
keys = medicine_manager.get_medicine_keys()
|
||||
print(f"Medicine keys: {keys}")
|
||||
|
||||
# Test getting quick doses
|
||||
for key in keys:
|
||||
doses = medicine_manager.get_quick_doses(key)
|
||||
print(f"Quick doses for {key}: {doses}")
|
||||
|
||||
print("Medicine manager test completed successfully!")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_medicine_manager()
|
||||
@@ -1,88 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Test script to validate the modular medicine system.
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
|
||||
# Add src to path
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "src"))
|
||||
|
||||
from init import logger
|
||||
from medicine_manager import Medicine, MedicineManager
|
||||
|
||||
|
||||
def test_medicine_system():
|
||||
"""Test the complete medicine system."""
|
||||
print("🧪 Testing Medicine System...")
|
||||
|
||||
# Test 1: Initialize medicine manager
|
||||
print("\n1. Testing MedicineManager initialization...")
|
||||
medicine_manager = MedicineManager(logger=logger)
|
||||
medicines = medicine_manager.get_all_medicines()
|
||||
print(f" ✅ Loaded {len(medicines)} medicines")
|
||||
|
||||
# Test 2: List current medicines
|
||||
print("\n2. Current medicines:")
|
||||
for key, medicine in medicines.items():
|
||||
status = "🟢" if medicine.default_enabled else "⚫"
|
||||
print(f" {status} {key}: {medicine.display_name} ({medicine.dosage_info})")
|
||||
print(f" Quick doses: {medicine.quick_doses}")
|
||||
print(f" Color: {medicine.color}")
|
||||
|
||||
# Test 3: Add a new medicine
|
||||
print("\n3. Testing adding new medicine...")
|
||||
new_medicine = Medicine(
|
||||
key="sertraline",
|
||||
display_name="Sertraline",
|
||||
dosage_info="50mg",
|
||||
quick_doses=["25", "50", "100"],
|
||||
color="#9B59B6",
|
||||
default_enabled=False,
|
||||
)
|
||||
|
||||
if medicine_manager.add_medicine(new_medicine):
|
||||
print(" ✅ Successfully added Sertraline")
|
||||
updated_medicines = medicine_manager.get_all_medicines()
|
||||
print(f" Now have {len(updated_medicines)} medicines")
|
||||
else:
|
||||
print(" ❌ Failed to add Sertraline")
|
||||
|
||||
# Test 4: Test CSV headers
|
||||
print("\n4. Testing CSV headers generation...")
|
||||
from data_manager import DataManager
|
||||
|
||||
DataManager("test_medicines.csv", logger, medicine_manager)
|
||||
|
||||
if os.path.exists("test_medicines.csv"):
|
||||
with open("test_medicines.csv") as f:
|
||||
headers = f.readline().strip()
|
||||
print(f" CSV headers: {headers}")
|
||||
os.remove("test_medicines.csv") # Clean up
|
||||
print(" ✅ CSV headers generated successfully")
|
||||
|
||||
# Test 5: Test graph colors
|
||||
print("\n5. Testing graph colors...")
|
||||
colors = medicine_manager.get_graph_colors()
|
||||
for key, color in colors.items():
|
||||
print(f" {key}: {color}")
|
||||
print(" ✅ Graph colors retrieved successfully")
|
||||
|
||||
# Clean up - remove test medicine
|
||||
print("\n6. Cleaning up...")
|
||||
if medicine_manager.remove_medicine("sertraline"):
|
||||
print(" ✅ Test medicine removed successfully")
|
||||
|
||||
print("\n🎉 All tests passed! Medicine system is working correctly.")
|
||||
return True
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
test_medicine_system()
|
||||
except Exception as e:
|
||||
print(f"❌ Test failed with error: {e}")
|
||||
import traceback
|
||||
|
||||
traceback.print_exc()
|
||||
@@ -1,94 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Test script to validate the pathology management system.
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
|
||||
# Add src to path
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src"))
|
||||
|
||||
from init import logger
|
||||
from pathology_manager import Pathology, PathologyManager
|
||||
|
||||
|
||||
def test_pathology_system():
|
||||
"""Test the complete pathology system."""
|
||||
print("🧪 Testing Pathology Management System...")
|
||||
|
||||
# Test 1: Initialize PathologyManager
|
||||
print("\n1. Testing PathologyManager initialization...")
|
||||
pathology_manager = PathologyManager("test_pathologies.json", logger)
|
||||
pathologies = pathology_manager.get_all_pathologies()
|
||||
print(f" ✅ Successfully loaded {len(pathologies)} pathologies")
|
||||
|
||||
for key, pathology in pathologies.items():
|
||||
print(f" - {key}: {pathology.display_name} ({pathology.scale_info})")
|
||||
|
||||
# Test 2: Add a new pathology
|
||||
print("\n2. Testing pathology addition...")
|
||||
new_pathology = Pathology(
|
||||
key="stress",
|
||||
display_name="Stress Level",
|
||||
scale_info="0:calm, 10:overwhelmed",
|
||||
color="#9B59B6",
|
||||
default_enabled=True,
|
||||
scale_min=0,
|
||||
scale_max=10,
|
||||
scale_orientation="normal",
|
||||
)
|
||||
|
||||
if pathology_manager.add_pathology(new_pathology):
|
||||
print(" ✅ Successfully added Stress Level pathology")
|
||||
updated_pathologies = pathology_manager.get_all_pathologies()
|
||||
print(f" Now have {len(updated_pathologies)} pathologies")
|
||||
else:
|
||||
print(" ❌ Failed to add Stress Level pathology")
|
||||
|
||||
# Test 3: Test CSV headers with DataManager
|
||||
print("\n3. Testing CSV headers generation...")
|
||||
from data_manager import DataManager
|
||||
from medicine_manager import MedicineManager
|
||||
|
||||
medicine_manager = MedicineManager("medicines.json", logger)
|
||||
DataManager(
|
||||
"test_pathologies_data.csv", logger, medicine_manager, pathology_manager
|
||||
)
|
||||
|
||||
if os.path.exists("test_pathologies_data.csv"):
|
||||
with open("test_pathologies_data.csv") as f:
|
||||
headers = f.readline().strip()
|
||||
print(f" CSV headers: {headers}")
|
||||
os.remove("test_pathologies_data.csv") # Clean up
|
||||
print(" ✅ CSV headers generated successfully")
|
||||
|
||||
# Test 4: Test pathology configuration methods
|
||||
print("\n4. Testing pathology configuration methods...")
|
||||
keys = pathology_manager.get_pathology_keys()
|
||||
display_names = pathology_manager.get_display_names()
|
||||
colors = pathology_manager.get_graph_colors()
|
||||
enabled = pathology_manager.get_default_enabled_pathologies()
|
||||
|
||||
print(f" Keys: {keys}")
|
||||
print(f" Display names: {display_names}")
|
||||
print(f" Colors: {colors}")
|
||||
print(f" Default enabled: {enabled}")
|
||||
print(" ✅ All configuration methods working")
|
||||
|
||||
# Clean up test file
|
||||
if os.path.exists("test_pathologies.json"):
|
||||
os.remove("test_pathologies.json")
|
||||
print("\n🧹 Cleaned up test files")
|
||||
|
||||
print("\n✅ All pathology system tests passed!")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
test_pathology_system()
|
||||
except Exception as e:
|
||||
print(f"❌ Test failed with error: {e}")
|
||||
import traceback
|
||||
|
||||
traceback.print_exc()
|
||||
@@ -1,146 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Test the save functionality of the edit window.
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import tkinter as tk
|
||||
|
||||
sys.path.append(os.path.join(os.path.dirname(__file__), "..", "src"))
|
||||
|
||||
from medicine_manager import MedicineManager
|
||||
from pathology_manager import PathologyManager
|
||||
from ui_manager import UIManager
|
||||
|
||||
|
||||
def test_save_functionality():
|
||||
"""Test that the save functionality works with dynamic data."""
|
||||
print("Testing edit window save functionality...")
|
||||
|
||||
# Initialize managers
|
||||
medicine_manager = MedicineManager()
|
||||
pathology_manager = PathologyManager()
|
||||
|
||||
# Create a simple logger
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger("test")
|
||||
logger.setLevel(logging.INFO)
|
||||
|
||||
# Create root window
|
||||
root = tk.Tk()
|
||||
root.withdraw()
|
||||
|
||||
# Initialize UI manager
|
||||
ui_manager = UIManager(
|
||||
root=root,
|
||||
logger=logger,
|
||||
medicine_manager=medicine_manager,
|
||||
pathology_manager=pathology_manager,
|
||||
)
|
||||
|
||||
# Create mock callback to test save
|
||||
save_called = False
|
||||
save_args = None
|
||||
|
||||
def mock_save_callback(*args):
|
||||
nonlocal save_called, save_args
|
||||
save_called = True
|
||||
save_args = args
|
||||
print(f"✅ Save callback called with {len(args)} arguments")
|
||||
for i, arg in enumerate(args):
|
||||
print(f" arg[{i}]: {arg} ({type(arg)})")
|
||||
|
||||
def mock_delete_callback(win):
|
||||
print("✅ Delete callback called")
|
||||
win.destroy()
|
||||
|
||||
callbacks = {"save": mock_save_callback, "delete": mock_delete_callback}
|
||||
|
||||
# Test data - prepare in correct format for edit window
|
||||
# Format: date, pathology1, pathology2, ..., medicine1, medicine1_doses,
|
||||
# medicine2, medicine2_doses, ..., note
|
||||
|
||||
test_values = ["2025-07-31"] # date
|
||||
|
||||
# Add pathology values
|
||||
pathologies = pathology_manager.get_all_pathologies()
|
||||
for _pathology_key, _pathology in pathologies.items():
|
||||
test_values.append(5) # pathology value
|
||||
|
||||
# Add medicine values and doses
|
||||
medicines = medicine_manager.get_all_medicines()
|
||||
for _medicine_key in medicines:
|
||||
test_values.append(1) # medicine checkbox value
|
||||
test_values.append("10:00: 25mg") # medicine doses
|
||||
|
||||
test_values.append("Test save functionality") # note
|
||||
|
||||
print(f"Created test data with {len(test_values)} values")
|
||||
print(
|
||||
f"Expected format: date + {len(pathologies)} pathologies + "
|
||||
f"{len(medicines)} medicines (each with doses) + note"
|
||||
)
|
||||
|
||||
try:
|
||||
# Create edit window
|
||||
edit_window = ui_manager.create_edit_window(tuple(test_values), callbacks)
|
||||
|
||||
print("✅ Edit window created successfully")
|
||||
|
||||
# We can't easily simulate button clicks without GUI interaction,
|
||||
# but we can verify the callback structure works
|
||||
expected_arg_count = (
|
||||
1 # edit_win
|
||||
+ 1 # date
|
||||
+ len(pathologies) # pathology values
|
||||
+ len(medicines) # medicine values
|
||||
+ 1 # note
|
||||
+ 1 # dose_data dict
|
||||
)
|
||||
|
||||
print(f"✅ Expected callback args: {expected_arg_count}")
|
||||
print(f"✅ Pathologies: {len(pathologies)}")
|
||||
print(f"✅ Medicines: {len(medicines)}")
|
||||
|
||||
# Test mock callback directly
|
||||
test_args = [
|
||||
edit_window, # window
|
||||
"2025-07-31", # date
|
||||
*[5] * len(pathologies), # pathology values
|
||||
*[1] * len(medicines), # medicine values
|
||||
"Test note", # note
|
||||
{med: "10:00: 25mg" for med in medicines}, # dose_data
|
||||
]
|
||||
|
||||
mock_save_callback(*test_args)
|
||||
|
||||
if save_called:
|
||||
print("✅ Save callback mechanism working!")
|
||||
print("✅ Save functionality is now dynamic and working")
|
||||
else:
|
||||
print("❌ Save callback not called")
|
||||
return False
|
||||
|
||||
edit_window.destroy()
|
||||
root.quit()
|
||||
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ Error testing save functionality: {e}")
|
||||
import traceback
|
||||
|
||||
traceback.print_exc()
|
||||
return False
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
success = test_save_functionality()
|
||||
if success:
|
||||
print("\n🎉 Save functionality test passed!")
|
||||
print("The edit window save is now fully dynamic!")
|
||||
else:
|
||||
print("\n💥 Save functionality test failed!")
|
||||
sys.exit(1)
|
||||
@@ -1,63 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Test script to verify the scrollable input frame functionality.
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import tkinter as tk
|
||||
from tkinter import ttk
|
||||
|
||||
# Add src to path
|
||||
sys.path.append(os.path.join(os.path.dirname(__file__), "src"))
|
||||
|
||||
|
||||
def test_scrollable_input():
|
||||
"""Test the scrollable input frame."""
|
||||
from src.init import logger
|
||||
from src.ui_manager import UIManager
|
||||
|
||||
# Create a test window
|
||||
root = tk.Tk()
|
||||
root.title("Scrollable Input Frame Test")
|
||||
root.geometry("400x600") # Smaller window to test scrolling
|
||||
|
||||
# Create UI manager
|
||||
ui_manager = UIManager(root, logger)
|
||||
|
||||
# Create main frame
|
||||
main_frame = ttk.Frame(root, padding="10")
|
||||
main_frame.grid(row=0, column=0, sticky="nsew")
|
||||
root.grid_rowconfigure(0, weight=1)
|
||||
root.grid_columnconfigure(0, weight=1)
|
||||
main_frame.grid_rowconfigure(1, weight=1)
|
||||
main_frame.grid_columnconfigure(0, weight=1)
|
||||
|
||||
# Create the scrollable input frame
|
||||
_input_ui = ui_manager.create_input_frame(main_frame)
|
||||
|
||||
# Add instructions
|
||||
instructions = ttk.Label(
|
||||
root,
|
||||
text="Test the scrolling functionality:\n"
|
||||
"1. Try mouse wheel scrolling over the input area\n"
|
||||
"2. Use the scrollbar on the right\n"
|
||||
"3. Test dose tracking buttons\n"
|
||||
"4. Resize the window to test responsiveness",
|
||||
justify="left",
|
||||
)
|
||||
instructions.grid(row=1, column=0, padx=10, pady=10, sticky="ew")
|
||||
|
||||
# Print success message
|
||||
print("✓ Scrollable input frame created successfully!")
|
||||
print("✓ Medicine dose tracking UI elements loaded")
|
||||
print("✓ Scrollbar functionality active")
|
||||
print("✓ Mouse wheel scrolling enabled")
|
||||
print("\nTest window opened. Close the window when done testing.")
|
||||
|
||||
# Start the test GUI
|
||||
root.mainloop()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_scrollable_input()
|
||||
@@ -1,34 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Simple test of the dynamic pathology system."""
|
||||
|
||||
import os
|
||||
import sys
|
||||
|
||||
sys.path.append(os.path.join(os.path.dirname(__file__), "..", "src"))
|
||||
|
||||
from medicine_manager import MedicineManager
|
||||
from pathology_manager import PathologyManager
|
||||
|
||||
|
||||
def main():
|
||||
print("Testing dynamic pathology and medicine system...")
|
||||
|
||||
# Test pathology manager
|
||||
pm = PathologyManager()
|
||||
pathologies = pm.get_all_pathologies()
|
||||
print(f"✅ Loaded {len(pathologies)} pathologies:")
|
||||
for key, pathology in pathologies.items():
|
||||
print(f" {key}: {pathology.display_name}")
|
||||
|
||||
# Test medicine manager
|
||||
mm = MedicineManager()
|
||||
medicines = mm.get_all_medicines()
|
||||
print(f"✅ Loaded {len(medicines)} medicines:")
|
||||
for key, medicine in medicines.items():
|
||||
print(f" {key}: {medicine.display_name}")
|
||||
|
||||
print("🎉 Dynamic system working perfectly!")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user