From 1e1e6c78ace887965b75bbf04c0d1b9fbd33168c Mon Sep 17 00:00:00 2001 From: William Valentin Date: Thu, 7 Aug 2025 12:25:05 -0700 Subject: [PATCH] feat: Add test scripts for dose parsing and UI tracking functionality --- scripts/test_dose_parsing.py | 95 ++++++++++++++++++++++++++ scripts/test_dose_tracking_ui.py | 111 +++++++++++++++++++++++++++++++ 2 files changed, 206 insertions(+) create mode 100644 scripts/test_dose_parsing.py create mode 100644 scripts/test_dose_tracking_ui.py diff --git a/scripts/test_dose_parsing.py b/scripts/test_dose_parsing.py new file mode 100644 index 0000000..2dc5f16 --- /dev/null +++ b/scripts/test_dose_parsing.py @@ -0,0 +1,95 @@ +#!/usr/bin/env python3 +""" +Test the complete dose tracking flow: load -> display -> add -> save +""" + +import os +import sys +from datetime import datetime + +# Add the src directory to Python path +sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src")) + +from init import logger +from ui_manager import UIManager + + +def test_dose_parsing(): + """Test dose parsing functions directly.""" + + # Mock a UI manager instance for testing + class MockManager: + def get_all_medicines(self): + return ["bupropion"] + + def get_all_pathologies(self): + return [] + + ui_manager = UIManager(None, logger, MockManager(), MockManager(), None) + + # Test 1: Parse storage format to display format + print("=== Test 1: Storage to Display Format ===") + storage_format = "2025-08-07 08:00:00:150mg|2025-08-07 12:00:00:150mg" + print(f"Input (storage): {storage_format}") + + # This would normally be done by _populate_dose_history + formatted_doses = [] + for dose_entry in storage_format.split("|"): + if ":" in dose_entry: + parts = dose_entry.rsplit(":", 1) + if len(parts) == 2: + timestamp, dose = parts + try: + dt = datetime.strptime(timestamp, "%Y-%m-%d %H:%M:%S") + time_str = dt.strftime("%I:%M %p") + formatted_doses.append(f"• {time_str} - {dose}") + except ValueError: + formatted_doses.append(f"• {dose_entry}") + else: + formatted_doses.append(f"• {dose_entry}") + else: + formatted_doses.append(f"• {dose_entry}") + + display_format = "\n".join(formatted_doses) + print(f"Output (display): {display_format}") + + # Test 2: Add new dose in display format + print("\n=== Test 2: Add New Dose ===") + new_timestamp = datetime.now().strftime("%I:%M %p") + new_dose = f"• {new_timestamp} - 150mg" + print(f"New dose to add: {new_dose}") + + updated_display = display_format + f"\n{new_dose}" + print(f"Updated display: {updated_display}") + + # Test 3: Parse display format back to storage format + print("\n=== Test 3: Display to Storage Format ===") + test_date = "2025-08-07" + parsed_storage = ui_manager._parse_dose_history_for_saving( + updated_display, test_date + ) + print(f"Input (display): {updated_display}") + print(f"Output (storage): {parsed_storage}") + + # Test 4: Verify round-trip integrity + print("\n=== Test 4: Round-trip Test ===") + print(f"Original storage: {storage_format}") + print(f"Final storage: {parsed_storage}") + + # Check if we preserved the original doses + original_count = len(storage_format.split("|")) + final_count = len(parsed_storage.split("|")) if parsed_storage else 0 + print(f"Dose count: {original_count} -> {final_count}") + + if final_count == original_count + 1: + print("✅ SUCCESS: New dose was added without replacing existing ones") + elif final_count == original_count: + print("❌ FAILURE: No new dose was added") + elif final_count < original_count: + print("❌ FAILURE: Existing doses were lost") + else: + print(f"⚠️ UNEXPECTED: Dose count changed unexpectedly ({final_count})") + + +if __name__ == "__main__": + test_dose_parsing() diff --git a/scripts/test_dose_tracking_ui.py b/scripts/test_dose_tracking_ui.py new file mode 100644 index 0000000..fc3abe3 --- /dev/null +++ b/scripts/test_dose_tracking_ui.py @@ -0,0 +1,111 @@ +#!/usr/bin/env python3 +""" +Test script for dose tracking UI in edit window. +Tests the specific issue where adding new doses replaces existing ones. +""" + +import os +import sys +import tkinter as tk +from datetime import datetime + +# Add the src directory to Python path +sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src")) + +from init import logger +from medicine_manager import MedicineManager +from pathology_manager import PathologyManager +from theme_manager import ThemeManager +from ui_manager import UIManager + + +def test_dose_tracking(): + """Test the dose tracking functionality.""" + + # Create test window + root = tk.Tk() + root.title("Dose Tracking Test") + root.geometry("800x600") + + # Initialize managers + medicine_manager = MedicineManager(logger=logger) + pathology_manager = PathologyManager(logger=logger) + theme_manager = ThemeManager(root, logger) + + ui_manager = UIManager( + root, logger, medicine_manager, pathology_manager, theme_manager + ) + + # Add a test medicine if none exist + medicines = medicine_manager.get_all_medicines() + if not medicines: + from medicine_manager import Medicine + + test_medicine = Medicine( + key="bupropion", + display_name="Bupropion", + dosage="150mg", + color="#4CAF50", + quick_doses=["150", "300"], + is_default=True, + ) + medicine_manager.add_medicine(test_medicine) + print("Added test medicine: Bupropion") + + # Test data - simulate existing doses for today + test_date = datetime.now().strftime("%Y-%m-%d") + existing_doses = {"bupropion": "• 08:00 AM - 150mg\n• 12:00 PM - 150mg"} + + # Create test callbacks + def test_save_callback(edit_win, *args): + print(f"Save callback called with {len(args)} arguments") + print(f"Arguments: {args}") + # Don't actually save, just print for testing + + def test_delete_callback(edit_win): + print("Delete callback called") + edit_win.destroy() + + callbacks = {"save": test_save_callback, "delete": test_delete_callback} + + # Test values to populate the edit window + test_values = ( + test_date, # date + 0, # pathology score (if any) + 1, # medicine taken (bupropion) + existing_doses["bupropion"], # existing doses + "Test note", # note + ) + + print(f"Creating edit window with test values: {test_values}") + + # Create the edit window + _ = ui_manager.create_edit_window(test_values, callbacks) + + # Add instructions label + instructions = tk.Label( + root, + text="Instructions:\n" + "1. The edit window should show existing doses: 08:00 AM and 12:00 PM\n" + "2. Enter a new dose (e.g., 150) and click 'Take Bupropion'\n" + "3. The new dose should be ADDED to existing doses, not replace them\n" + "4. Click Save to see the final dose data in console", + justify=tk.LEFT, + wraplength=500, + bg="lightyellow", + padx=10, + pady=10, + ) + instructions.pack(pady=10, padx=10, fill=tk.X) + + print("Test setup complete. Check the edit window for dose tracking behavior.") + print( + "Expected behavior: New doses should be added to existing ones, " + "not replace them." + ) + + root.mainloop() + + +if __name__ == "__main__": + test_dose_tracking()