feat: Add comprehensive test scripts for multiple dose functionality and save behavior
This commit is contained in:
171
scripts/test_dose_demonstration.py
Normal file
171
scripts/test_dose_demonstration.py
Normal file
@@ -0,0 +1,171 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Step-by-step test to demonstrate multiple dose functionality.
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import tkinter as tk
|
||||
|
||||
import pandas as pd
|
||||
|
||||
# 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"))
|
||||
|
||||
import logging
|
||||
|
||||
from ui_manager import UIManager
|
||||
|
||||
|
||||
def demonstrate_multiple_doses():
|
||||
"""Demonstrate the complete multiple dose workflow."""
|
||||
|
||||
print("🧪 Multiple Dose Demonstration")
|
||||
print("=" * 40)
|
||||
|
||||
# Check current CSV state
|
||||
try:
|
||||
df = pd.read_csv("thechart_data.csv")
|
||||
print(f"📋 Current CSV has {len(df)} entries")
|
||||
latest = df.iloc[-1]
|
||||
print(f"📅 Latest entry date: {latest['date']}")
|
||||
|
||||
# Show current dose state for latest entry
|
||||
dose_columns = [col for col in df.columns if col.endswith("_doses")]
|
||||
print("💊 Current doses in latest entry:")
|
||||
for dose_col in dose_columns:
|
||||
medicine = dose_col.replace("_doses", "")
|
||||
dose_data = str(latest[dose_col])
|
||||
if dose_data and dose_data != "nan" and dose_data.strip():
|
||||
dose_count = len(dose_data.split("|"))
|
||||
print(f" {medicine}: {dose_count} dose(s)")
|
||||
else:
|
||||
print(f" {medicine}: No doses")
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ Error reading CSV: {e}")
|
||||
return
|
||||
|
||||
print("\n🔬 Testing Edit Window Workflow:")
|
||||
print("1. Create edit window for latest entry")
|
||||
print("2. Add multiple doses using punch buttons")
|
||||
print("3. Save and verify CSV is updated")
|
||||
print("\nStarting test...")
|
||||
|
||||
# Create test environment
|
||||
root = tk.Tk()
|
||||
root.title("Dose Test")
|
||||
root.geometry("300x200")
|
||||
|
||||
logger = logging.getLogger("dose_test")
|
||||
logger.setLevel(logging.DEBUG)
|
||||
|
||||
ui_manager = UIManager(root, logger)
|
||||
|
||||
# Use the actual latest CSV data for testing
|
||||
if len(latest) >= 14:
|
||||
sample_values = tuple(latest.iloc[:14])
|
||||
else:
|
||||
# Pad with empty values if needed
|
||||
sample_values = tuple(list(latest) + [""] * (14 - len(latest)))
|
||||
|
||||
# Track save operations
|
||||
save_called = False
|
||||
saved_dose_data = None
|
||||
|
||||
def test_save(*args):
|
||||
nonlocal save_called, saved_dose_data
|
||||
save_called = True
|
||||
|
||||
if len(args) >= 12:
|
||||
saved_dose_data = args[-1] # dose_data is last argument
|
||||
|
||||
print("\n✅ Save called!")
|
||||
print("💾 Dose data being saved:")
|
||||
for med, doses in saved_dose_data.items():
|
||||
if doses:
|
||||
dose_count = len(doses.split("|")) if "|" in doses else 1
|
||||
print(f" {med}: {dose_count} dose(s) - {doses}")
|
||||
else:
|
||||
print(f" {med}: No doses")
|
||||
|
||||
# Close the window
|
||||
if args and hasattr(args[0], "destroy"):
|
||||
args[0].destroy()
|
||||
|
||||
def test_delete(*args):
|
||||
print("🗑️ Delete called")
|
||||
if args and hasattr(args[0], "destroy"):
|
||||
args[0].destroy()
|
||||
|
||||
callbacks = {
|
||||
"save": test_save,
|
||||
"delete": test_delete,
|
||||
}
|
||||
|
||||
try:
|
||||
# Create edit window
|
||||
edit_window = ui_manager.create_edit_window(sample_values, callbacks)
|
||||
edit_window.geometry("700x500")
|
||||
edit_window.lift()
|
||||
edit_window.focus_force()
|
||||
|
||||
print("\n📝 INSTRUCTIONS:")
|
||||
print("1. In any medicine dose field, enter a dose amount (e.g., '100mg')")
|
||||
print("2. Click the 'Take [Medicine]' button")
|
||||
print("3. Enter another dose amount")
|
||||
print("4. Click the 'Take [Medicine]' button again")
|
||||
print("5. You should see both doses in the text area")
|
||||
print("6. Click 'Save' to persist changes")
|
||||
print("\n⏳ Waiting for your interaction...")
|
||||
|
||||
# Wait for user interaction
|
||||
edit_window.wait_window()
|
||||
|
||||
if save_called:
|
||||
print("\n🎉 SUCCESS: Save operation completed!")
|
||||
print("📊 Multiple doses should now be saved to CSV")
|
||||
|
||||
# Verify the save actually updated the CSV
|
||||
try:
|
||||
df_after = pd.read_csv("thechart_data.csv")
|
||||
if len(df_after) > len(df):
|
||||
print("✅ New entry added to CSV")
|
||||
else:
|
||||
print("✅ Existing entry updated in CSV")
|
||||
|
||||
print("\n🔍 Verifying saved data...")
|
||||
latest_after = df_after.iloc[-1]
|
||||
for dose_col in dose_columns:
|
||||
medicine = dose_col.replace("_doses", "")
|
||||
dose_data = str(latest_after[dose_col])
|
||||
if dose_data and dose_data != "nan" and dose_data.strip():
|
||||
dose_count = len(dose_data.split("|"))
|
||||
print(f" {medicine}: {dose_count} dose(s) in CSV")
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ Error verifying CSV: {e}")
|
||||
|
||||
return True
|
||||
else:
|
||||
print("\n❌ Save was not called - test incomplete")
|
||||
return False
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ Error during test: {e}")
|
||||
import traceback
|
||||
|
||||
traceback.print_exc()
|
||||
return False
|
||||
finally:
|
||||
root.destroy()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
os.chdir("/home/will/Code/thechart")
|
||||
success = demonstrate_multiple_doses()
|
||||
|
||||
if success:
|
||||
print("\n🎯 Multiple dose functionality verified!")
|
||||
else:
|
||||
print("\n❓ Test incomplete or failed")
|
||||
147
scripts/test_dose_editing_functionality.py
Normal file
147
scripts/test_dose_editing_functionality.py
Normal file
@@ -0,0 +1,147 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Test script to verify dose editing functionality in the edit window.
|
||||
"""
|
||||
|
||||
import logging
|
||||
import os
|
||||
import shutil
|
||||
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 data_manager import DataManager
|
||||
|
||||
|
||||
def test_dose_editing_functionality():
|
||||
"""Test the dose editing functionality with the edit window."""
|
||||
print("Testing dose editing functionality in edit window...")
|
||||
|
||||
# Create a backup of the current CSV
|
||||
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 dose editing functionality")
|
||||
return False
|
||||
|
||||
# Test 1: Check that we can retrieve full row data including doses
|
||||
print("\n=== Testing Full Row Data Retrieval ===")
|
||||
first_entry_date = df.iloc[0]["date"]
|
||||
first_entry = df[df["date"] == first_entry_date].iloc[0]
|
||||
|
||||
print(f"Testing with date: {first_entry_date}")
|
||||
|
||||
# Check that all expected columns are present
|
||||
expected_columns = [
|
||||
"date",
|
||||
"depression",
|
||||
"anxiety",
|
||||
"sleep",
|
||||
"appetite",
|
||||
"bupropion",
|
||||
"bupropion_doses",
|
||||
"hydroxyzine",
|
||||
"hydroxyzine_doses",
|
||||
"gabapentin",
|
||||
"gabapentin_doses",
|
||||
"propranolol",
|
||||
"propranolol_doses",
|
||||
"note",
|
||||
]
|
||||
|
||||
missing_columns = [col for col in expected_columns if col not in df.columns]
|
||||
if missing_columns:
|
||||
print(f"✗ Missing columns: {missing_columns}")
|
||||
return False
|
||||
else:
|
||||
print("✓ All expected columns present in CSV")
|
||||
|
||||
# Test 2: Check dose data access
|
||||
print("\n=== Testing Dose Data Access ===")
|
||||
dose_columns = [
|
||||
"bupropion_doses",
|
||||
"hydroxyzine_doses",
|
||||
"gabapentin_doses",
|
||||
"propranolol_doses",
|
||||
]
|
||||
|
||||
for col in dose_columns:
|
||||
dose_data = first_entry[col]
|
||||
print(f"{col}: '{dose_data}'")
|
||||
|
||||
print("✓ Dose data accessible from CSV")
|
||||
|
||||
# Test 3: Test parsing dose text (simulate edit window input)
|
||||
print("\n=== Testing Dose Text Parsing ===")
|
||||
|
||||
# Simulate some dose text that a user might enter
|
||||
test_dose_text = "09:00: 150mg\n18:30: 150mg"
|
||||
test_date = "07/28/2025"
|
||||
|
||||
# Test the parsing logic (we'll need to import this)
|
||||
try:
|
||||
import tkinter as tk
|
||||
|
||||
from ui_manager import UIManager
|
||||
|
||||
# Create a temporary UI manager to test the parsing
|
||||
root = tk.Tk()
|
||||
root.withdraw() # Hide the window
|
||||
ui_manager = UIManager(root, logger)
|
||||
|
||||
parsed_doses = ui_manager._parse_dose_text(test_dose_text, test_date)
|
||||
print(f"Original text: '{test_dose_text}'")
|
||||
print(f"Parsed doses: '{parsed_doses}'")
|
||||
|
||||
if "|" in parsed_doses and "2025-07-28" in parsed_doses:
|
||||
print("✓ Dose text parsing working correctly")
|
||||
else:
|
||||
print("✗ Dose text parsing failed")
|
||||
root.destroy()
|
||||
return False
|
||||
|
||||
root.destroy()
|
||||
|
||||
except Exception as e:
|
||||
print(f"✗ Error testing dose parsing: {e}")
|
||||
return False
|
||||
|
||||
print("\n✓ All dose editing functionality tests passed!")
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
print(f"✗ Error during 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_dose_editing_functionality()
|
||||
104
scripts/test_dose_verification.py
Normal file
104
scripts/test_dose_verification.py
Normal file
@@ -0,0 +1,104 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Script to verify dose saving functionality by examining CSV data.
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
|
||||
import pandas as pd
|
||||
|
||||
|
||||
def verify_dose_saving():
|
||||
"""Verify that multiple doses are being saved correctly."""
|
||||
|
||||
# Read the CSV data
|
||||
try:
|
||||
df = pd.read_csv("thechart_data.csv")
|
||||
print("📊 Examining CSV data for dose entries...")
|
||||
print(f" Total entries: {len(df)}")
|
||||
|
||||
# Check for dose columns
|
||||
dose_columns = [col for col in df.columns if col.endswith("_doses")]
|
||||
print(f" Dose columns found: {dose_columns}")
|
||||
|
||||
# Look for entries with multiple doses
|
||||
entries_with_doses = 0
|
||||
entries_with_multiple_doses = 0
|
||||
|
||||
for _, row in df.iterrows():
|
||||
row_has_doses = False
|
||||
row_has_multiple = False
|
||||
|
||||
for dose_col in dose_columns:
|
||||
dose_data = str(row[dose_col])
|
||||
if dose_data and dose_data != "nan" and dose_data.strip():
|
||||
row_has_doses = True
|
||||
# Count doses (separated by |)
|
||||
dose_count = len(dose_data.split("|"))
|
||||
medicine_name = dose_col.replace("_doses", "")
|
||||
|
||||
print(f" {row['date']} - {medicine_name}: {dose_count} dose(s)")
|
||||
if dose_count > 1:
|
||||
row_has_multiple = True
|
||||
print(f" → Multiple doses: {dose_data}")
|
||||
|
||||
if row_has_doses:
|
||||
entries_with_doses += 1
|
||||
if row_has_multiple:
|
||||
entries_with_multiple_doses += 1
|
||||
|
||||
print("\n📈 Summary:")
|
||||
print(f" Entries with doses: {entries_with_doses}")
|
||||
print(f" Entries with multiple doses: {entries_with_multiple_doses}")
|
||||
|
||||
if entries_with_multiple_doses > 0:
|
||||
print("✅ Multiple dose saving IS working!")
|
||||
return True
|
||||
else:
|
||||
print("⚠️ No multiple dose entries found")
|
||||
return False
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ Error reading CSV: {e}")
|
||||
return False
|
||||
|
||||
|
||||
def check_latest_entry():
|
||||
"""Check the most recent entry for dose data."""
|
||||
try:
|
||||
df = pd.read_csv("thechart_data.csv")
|
||||
latest = df.iloc[-1]
|
||||
|
||||
print(f"\n🔍 Latest entry ({latest['date']}):")
|
||||
dose_columns = [col for col in df.columns if col.endswith("_doses")]
|
||||
|
||||
for dose_col in dose_columns:
|
||||
medicine = dose_col.replace("_doses", "")
|
||||
dose_data = str(latest[dose_col])
|
||||
|
||||
if dose_data and dose_data != "nan" and dose_data.strip():
|
||||
dose_count = len(dose_data.split("|"))
|
||||
print(f" {medicine}: {dose_count} dose(s) - {dose_data}")
|
||||
else:
|
||||
print(f" {medicine}: No doses")
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ Error checking latest entry: {e}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
print("🔬 Dose Verification Test")
|
||||
print("=" * 30)
|
||||
|
||||
# Change to the directory containing the CSV
|
||||
os.chdir("/home/will/Code/thechart")
|
||||
|
||||
success = verify_dose_saving()
|
||||
check_latest_entry()
|
||||
|
||||
if success:
|
||||
print("\n✅ Multiple dose functionality is working correctly!")
|
||||
else:
|
||||
print("\n❌ Multiple dose functionality needs investigation")
|
||||
sys.exit(1)
|
||||
126
scripts/test_edit_window_punch_buttons.py
Normal file
126
scripts/test_edit_window_punch_buttons.py
Normal file
@@ -0,0 +1,126 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Test script to verify the new punch button functionality in the edit window.
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import tkinter as tk
|
||||
|
||||
# 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"))
|
||||
|
||||
import logging
|
||||
|
||||
from ui_manager import UIManager
|
||||
|
||||
|
||||
def test_edit_window_punch_buttons():
|
||||
"""Test the punch buttons in the edit window."""
|
||||
print("Testing punch buttons in edit window...")
|
||||
|
||||
# Create a test Tkinter root
|
||||
root = tk.Tk()
|
||||
root.withdraw() # Hide the main window
|
||||
|
||||
# Create a logger
|
||||
logger = logging.getLogger("test_logger")
|
||||
logger.setLevel(logging.DEBUG)
|
||||
|
||||
# Create UIManager
|
||||
ui_manager = UIManager(root, logger)
|
||||
|
||||
# Sample dose data for testing
|
||||
sample_dose_data = {
|
||||
"bupropion": "2025-01-15 08:00:00:300mg|2025-01-15 20:00:00:150mg",
|
||||
"hydroxyzine": "2025-01-15 22:00:00:25mg",
|
||||
"gabapentin": "",
|
||||
"propranolol": "2025-01-15 09:30:00:10mg",
|
||||
}
|
||||
|
||||
# Sample values for the edit window (14 fields for new CSV format)
|
||||
sample_values = (
|
||||
"01/15/2025", # date
|
||||
5, # depression
|
||||
3, # anxiety
|
||||
7, # sleep
|
||||
6, # appetite
|
||||
1, # bupropion
|
||||
sample_dose_data["bupropion"], # bupropion_doses
|
||||
1, # hydroxyzine
|
||||
sample_dose_data["hydroxyzine"], # hydroxyzine_doses
|
||||
0, # gabapentin
|
||||
sample_dose_data["gabapentin"], # gabapentin_doses
|
||||
1, # propranolol
|
||||
sample_dose_data["propranolol"], # propranolol_doses
|
||||
"Test entry for punch button functionality", # note
|
||||
)
|
||||
|
||||
# Define dummy callbacks
|
||||
def dummy_save(*args):
|
||||
print("Save callback triggered with args:", args)
|
||||
|
||||
def dummy_delete(*args):
|
||||
print("Delete callback triggered")
|
||||
|
||||
callbacks = {
|
||||
"save": dummy_save,
|
||||
"delete": dummy_delete,
|
||||
}
|
||||
|
||||
try:
|
||||
# Create the edit window
|
||||
edit_window = ui_manager.create_edit_window(sample_values, callbacks)
|
||||
|
||||
print("✓ Edit window created successfully")
|
||||
print("✓ Edit window should now display:")
|
||||
print(" - Medicine checkboxes")
|
||||
print(" - Dose entry fields for each medicine")
|
||||
print(" - 'Take [Medicine]' punch buttons")
|
||||
print(" - Editable dose display areas")
|
||||
print(" - Formatted existing doses (times in HH:MM format)")
|
||||
|
||||
print("\n=== Testing Dose Display Formatting ===")
|
||||
print("Bupropion should show: 08:00: 300mg, 20:00: 150mg")
|
||||
print("Hydroxyzine should show: 22:00: 25mg")
|
||||
print("Gabapentin should show: No doses recorded")
|
||||
print("Propranolol should show: 09:30: 10mg")
|
||||
|
||||
print("\n=== Punch Button Test Instructions ===")
|
||||
print("1. Enter a dose amount in any medicine's entry field")
|
||||
print("2. Click the corresponding 'Take [Medicine]' button")
|
||||
print("3. The dose should be added to the dose display with current time")
|
||||
print("4. The entry field should be cleared")
|
||||
print("5. A success message should appear")
|
||||
|
||||
print("\n✓ Edit window is ready for testing")
|
||||
print("Close the edit window when done testing.")
|
||||
|
||||
# Start the event loop for the edit window
|
||||
edit_window.wait_window()
|
||||
|
||||
print("✓ Edit window test completed")
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
print(f"✗ Error creating edit window: {e}")
|
||||
import traceback
|
||||
|
||||
traceback.print_exc()
|
||||
return False
|
||||
|
||||
finally:
|
||||
root.destroy()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
print("Testing Edit Window Punch Button Functionality")
|
||||
print("=" * 50)
|
||||
|
||||
success = test_edit_window_punch_buttons()
|
||||
|
||||
if success:
|
||||
print("\n✓ All edit window punch button tests completed successfully!")
|
||||
else:
|
||||
print("\n✗ Edit window punch button tests failed!")
|
||||
sys.exit(1)
|
||||
141
scripts/test_multiple_punch_save.py
Normal file
141
scripts/test_multiple_punch_save.py
Normal file
@@ -0,0 +1,141 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Test script to verify multiple dose punching and saving behavior.
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import tkinter as tk
|
||||
|
||||
# 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"))
|
||||
|
||||
import logging
|
||||
|
||||
from ui_manager import UIManager
|
||||
|
||||
|
||||
def test_multiple_punch_and_save():
|
||||
"""Test multiple dose punching followed by save."""
|
||||
print("Testing multiple dose punching and save functionality...")
|
||||
|
||||
# Create a test Tkinter root
|
||||
root = tk.Tk()
|
||||
root.title("Test Root Window")
|
||||
root.geometry("200x100") # Small root window
|
||||
|
||||
# Create a logger
|
||||
logger = logging.getLogger("test_logger")
|
||||
logger.setLevel(logging.DEBUG)
|
||||
|
||||
# Create UIManager
|
||||
ui_manager = UIManager(root, logger)
|
||||
|
||||
# Sample dose data for testing
|
||||
sample_dose_data = {
|
||||
"bupropion": "2025-01-15 08:00:00:300mg",
|
||||
"hydroxyzine": "",
|
||||
"gabapentin": "",
|
||||
"propranolol": "",
|
||||
}
|
||||
|
||||
# Sample values for the edit window (14 fields for new CSV format)
|
||||
sample_values = (
|
||||
"01/15/2025", # date
|
||||
5, # depression
|
||||
3, # anxiety
|
||||
7, # sleep
|
||||
6, # appetite
|
||||
1, # bupropion
|
||||
sample_dose_data["bupropion"], # bupropion_doses
|
||||
0, # hydroxyzine
|
||||
sample_dose_data["hydroxyzine"], # hydroxyzine_doses
|
||||
0, # gabapentin
|
||||
sample_dose_data["gabapentin"], # gabapentin_doses
|
||||
0, # propranolol
|
||||
sample_dose_data["propranolol"], # propranolol_doses
|
||||
"Test entry for multiple punch testing", # note
|
||||
)
|
||||
|
||||
# Track save calls
|
||||
save_calls = []
|
||||
|
||||
# Define test callbacks
|
||||
def test_save(*args):
|
||||
save_calls.append(args)
|
||||
print(f"✓ Save called with {len(args)} arguments")
|
||||
|
||||
# Print dose data specifically
|
||||
if len(args) >= 12: # Should have dose_data as last argument
|
||||
dose_data = args[-1] # Last argument should be dose_data
|
||||
print(" Dose data received:")
|
||||
for med, doses in dose_data.items():
|
||||
print(f" {med}: {doses}")
|
||||
|
||||
# Close window after save
|
||||
if args and hasattr(args[0], "destroy"):
|
||||
args[0].destroy()
|
||||
|
||||
def test_delete(*args):
|
||||
print("Delete callback triggered")
|
||||
if args and hasattr(args[0], "destroy"):
|
||||
args[0].destroy()
|
||||
|
||||
callbacks = {
|
||||
"save": test_save,
|
||||
"delete": test_delete,
|
||||
}
|
||||
|
||||
try:
|
||||
# Create the edit window
|
||||
edit_window = ui_manager.create_edit_window(sample_values, callbacks)
|
||||
edit_window.geometry("600x400") # Set a reasonable size
|
||||
edit_window.lift() # Bring to front
|
||||
edit_window.focus_force() # Force focus
|
||||
|
||||
print("✓ Edit window created")
|
||||
print("✓ Now simulating multiple dose punches...")
|
||||
|
||||
# Let's simulate the manual process
|
||||
|
||||
print("\n=== Manual Test Instructions ===")
|
||||
print("1. In the Bupropion field, enter '150mg' and click 'Take Bupropion'")
|
||||
print("2. Enter '300mg' and click 'Take Bupropion' again")
|
||||
print("3. You should see both doses in the text area")
|
||||
print("4. Click 'Save' to persist the changes")
|
||||
print("5. Check if both doses are saved to the CSV")
|
||||
print("\nWindow will stay open for manual testing...")
|
||||
|
||||
# Wait for user to manually test
|
||||
edit_window.wait_window()
|
||||
|
||||
# Check if save was called
|
||||
if save_calls:
|
||||
print("✓ Save was called successfully")
|
||||
return True
|
||||
else:
|
||||
print("✗ Save was not called")
|
||||
return False
|
||||
|
||||
except Exception as e:
|
||||
print(f"✗ Error during test: {e}")
|
||||
import traceback
|
||||
|
||||
traceback.print_exc()
|
||||
return False
|
||||
|
||||
finally:
|
||||
root.destroy()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
print("Testing Multiple Dose Punching and Save")
|
||||
print("=" * 40)
|
||||
|
||||
success = test_multiple_punch_and_save()
|
||||
|
||||
if success:
|
||||
print("\n✅ Multiple punch and save test completed!")
|
||||
else:
|
||||
print("\n❌ Multiple punch and save test failed!")
|
||||
sys.exit(1)
|
||||
151
scripts/test_save_functionality.py
Normal file
151
scripts/test_save_functionality.py
Normal file
@@ -0,0 +1,151 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Quick test to verify the save functionality works correctly.
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import tkinter as tk
|
||||
|
||||
# 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"))
|
||||
|
||||
import logging
|
||||
|
||||
from ui_manager import UIManager
|
||||
|
||||
|
||||
def test_save_functionality():
|
||||
"""Test that the save button works without errors."""
|
||||
print("Testing save functionality in edit window...")
|
||||
|
||||
# Create a test Tkinter root
|
||||
root = tk.Tk()
|
||||
root.withdraw() # Hide the main window
|
||||
|
||||
# Create a logger
|
||||
logger = logging.getLogger("test_logger")
|
||||
logger.setLevel(logging.DEBUG)
|
||||
|
||||
# Create UIManager
|
||||
ui_manager = UIManager(root, logger)
|
||||
|
||||
# Sample dose data for testing
|
||||
sample_dose_data = {
|
||||
"bupropion": "2025-01-15 08:00:00:300mg|2025-01-15 20:00:00:150mg",
|
||||
"hydroxyzine": "2025-01-15 22:00:00:25mg",
|
||||
"gabapentin": "",
|
||||
"propranolol": "2025-01-15 09:30:00:10mg",
|
||||
}
|
||||
|
||||
# Sample values for the edit window (14 fields for new CSV format)
|
||||
sample_values = (
|
||||
"01/15/2025", # date
|
||||
5, # depression
|
||||
3, # anxiety
|
||||
7, # sleep
|
||||
6, # appetite
|
||||
1, # bupropion
|
||||
sample_dose_data["bupropion"], # bupropion_doses
|
||||
1, # hydroxyzine
|
||||
sample_dose_data["hydroxyzine"], # hydroxyzine_doses
|
||||
0, # gabapentin
|
||||
sample_dose_data["gabapentin"], # gabapentin_doses
|
||||
1, # propranolol
|
||||
sample_dose_data["propranolol"], # propranolol_doses
|
||||
"Test entry for save functionality", # note
|
||||
)
|
||||
|
||||
# Track if save was called successfully
|
||||
save_called = False
|
||||
save_args = None
|
||||
|
||||
# Define test callbacks
|
||||
def test_save(*args):
|
||||
nonlocal save_called, save_args
|
||||
save_called = True
|
||||
save_args = args
|
||||
print("✓ Save callback executed successfully")
|
||||
print(f" Arguments received: {len(args)} args")
|
||||
# Close the edit window after save
|
||||
if args and hasattr(args[0], "destroy"):
|
||||
args[0].destroy()
|
||||
|
||||
def test_delete(*args):
|
||||
print("Delete callback triggered")
|
||||
if args and hasattr(args[0], "destroy"):
|
||||
args[0].destroy()
|
||||
|
||||
callbacks = {
|
||||
"save": test_save,
|
||||
"delete": test_delete,
|
||||
}
|
||||
|
||||
try:
|
||||
# Create the edit window
|
||||
edit_window = ui_manager.create_edit_window(sample_values, callbacks)
|
||||
|
||||
print("✓ Edit window created successfully")
|
||||
print("✓ Testing automatic save...")
|
||||
|
||||
# Simulate clicking save button by calling the save function directly
|
||||
# First, we need to get the vars_dict from the window
|
||||
# We'll trigger a save by simulating the button press
|
||||
|
||||
# Find the save button and trigger it
|
||||
def find_save_button(widget):
|
||||
"""Recursively find the save button."""
|
||||
if isinstance(widget, tk.Button) and widget.cget("text") == "Save":
|
||||
return widget
|
||||
for child in widget.winfo_children():
|
||||
result = find_save_button(child)
|
||||
if result:
|
||||
return result
|
||||
return None
|
||||
|
||||
# Wait a moment for the window to fully initialize
|
||||
edit_window.update_idletasks()
|
||||
|
||||
# Find and click the save button
|
||||
save_button = find_save_button(edit_window)
|
||||
if save_button:
|
||||
print("✓ Found save button, triggering click...")
|
||||
save_button.invoke()
|
||||
else:
|
||||
print("✗ Could not find save button")
|
||||
edit_window.destroy()
|
||||
return False
|
||||
|
||||
# Check if save was called
|
||||
if save_called:
|
||||
print("✓ Save functionality test PASSED")
|
||||
print(
|
||||
f"✓ Save was called with {len(save_args) if save_args else 0} arguments"
|
||||
)
|
||||
return True
|
||||
else:
|
||||
print("✗ Save functionality test FAILED - save was not called")
|
||||
return False
|
||||
|
||||
except Exception as e:
|
||||
print(f"✗ Error during save test: {e}")
|
||||
import traceback
|
||||
|
||||
traceback.print_exc()
|
||||
return False
|
||||
|
||||
finally:
|
||||
root.destroy()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
print("Testing Save Functionality")
|
||||
print("=" * 30)
|
||||
|
||||
success = test_save_functionality()
|
||||
|
||||
if success:
|
||||
print("\n✅ Save functionality test completed successfully!")
|
||||
else:
|
||||
print("\n❌ Save functionality test failed!")
|
||||
sys.exit(1)
|
||||
Reference in New Issue
Block a user