Files
thechart/test_programmatic_punch.py

175 lines
4.9 KiB
Python

#!/usr/bin/env python3
"""
Test that programmatically clicks punch buttons to verify functionality.
"""
import os
import sys
import tkinter as tk
from datetime import datetime
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "src"))
import logging
from ui_manager import UIManager
def test_programmatic_punch():
"""Test punch buttons programmatically."""
print("🤖 Programmatic Punch Button Test")
print("=" * 40)
root = tk.Tk()
root.title("Auto Punch Test")
root.geometry("800x600")
logger = logging.getLogger("auto_punch")
ui_manager = UIManager(root, logger)
sample_values = (
"07/29/2025",
5,
3,
7,
6,
1,
"",
0,
"",
0,
"",
0,
"",
"Auto punch test",
)
save_called = False
saved_doses = None
def capture_save(*args):
nonlocal save_called, saved_doses
save_called = True
if len(args) >= 12:
saved_doses = args[-1]
print("💾 Save captured doses:")
for med, doses in saved_doses.items():
if doses:
count = len(doses.split("|")) if "|" in doses else 1
print(f" {med}: {count} dose(s) - {doses}")
else:
print(f" {med}: No doses")
if args and hasattr(args[0], "destroy"):
args[0].destroy()
callbacks = {"save": capture_save, "delete": lambda x: x.destroy()}
try:
edit_window = ui_manager.create_edit_window(sample_values, callbacks)
# Find the dose variables that were created
# We need to access them through the ui_manager somehow
print("🔍 Attempting to find dose widgets...")
# Let's manually trigger the punch button functionality
# by calling the _punch_dose_in_edit method directly
# Find the text widgets in the edit window
def find_widgets(widget, widget_list=None):
if widget_list is None:
widget_list = []
widget_list.append(widget)
for child in widget.winfo_children():
find_widgets(child, widget_list)
return widget_list
all_widgets = find_widgets(edit_window)
# Find Text widgets and Entry widgets
text_widgets = [w for w in all_widgets if isinstance(w, tk.Text)]
entry_widgets = [w for w in all_widgets if isinstance(w, tk.Entry)]
print(
f"Found {len(text_widgets)} Text widgets and "
f"{len(entry_widgets)} Entry widgets"
)
if len(text_widgets) >= 4: # Should have 4 dose text widgets
# Let's manually add doses to the first text widget (bupropion)
bupropion_text = text_widgets[0]
print("📝 Manually adding doses to bupropion text widget...")
# Clear and add multiple doses
bupropion_text.delete(1.0, tk.END)
now = datetime.now()
time1 = now.strftime("%H:%M")
time2 = (now.replace(minute=now.minute + 1)).strftime("%H:%M")
time3 = (now.replace(minute=now.minute + 2)).strftime("%H:%M")
dose_content = f"{time1}: 100mg\n{time2}: 200mg\n{time3}: 300mg"
bupropion_text.insert(1.0, dose_content)
print(f"Added content: {dose_content}")
# Verify content was added
actual_content = bupropion_text.get(1.0, tk.END).strip()
print(f"Actual content in widget: '{actual_content}'")
# Now trigger save
print("🔄 Triggering save...")
# We need to find the save button
buttons = [w for w in all_widgets if isinstance(w, tk.ttk.Button)]
save_button = None
for button in buttons:
try:
if "Save" in button.cget("text"):
save_button = button
break
except Exception:
pass
if save_button:
print("💾 Found Save button, clicking it...")
save_button.invoke()
else:
print("❌ Could not find Save button")
edit_window.destroy()
else:
print("❌ Could not find expected Text widgets")
edit_window.destroy()
# Wait for save to complete
root.update()
if save_called:
return True
else:
print("❌ Save was not called")
return False
except Exception as e:
print(f"❌ Error: {e}")
import traceback
traceback.print_exc()
return False
finally:
root.destroy()
if __name__ == "__main__":
os.chdir("/home/will/Code/thechart")
success = test_programmatic_punch()
if success:
print("\n✅ Programmatic test completed successfully!")
else:
print("\n❌ Programmatic test failed!")