Files
thechart/scripts/test_automated_punch.py

225 lines
6.6 KiB
Python

#!/usr/bin/env python3
"""
Automated test to simulate multiple punch button clicks and identify the
accumulation issue.
"""
import os
import sys
import tkinter as tk
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "src"))
import logging
from ui_manager import UIManager
def test_automated_multiple_punches():
"""Automatically simulate multiple punch button clicks."""
print("🤖 Automated Multiple Punch Test")
print("=" * 40)
root = tk.Tk()
root.title("Auto Multi-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 multi-punch test",
)
punch_results = []
save_result = None
def capture_save(*args):
nonlocal save_result
save_result = args[-1] if len(args) >= 12 else {}
print("\n💾 Save triggered, closing window...")
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 widgets we need
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 bupropion dose entry and text widgets
entry_widgets = [w for w in all_widgets if isinstance(w, tk.Entry)]
text_widgets = [w for w in all_widgets if isinstance(w, tk.Text)]
buttons = [w for w in all_widgets if isinstance(w, tk.ttk.Button)]
# Find the specific widgets for bupropion
bupropion_entry = None
bupropion_text = None
bupropion_button = None
# The first text widget should be bupropion (based on order in
# _add_dose_display_to_edit)
if len(text_widgets) >= 1:
bupropion_text = text_widgets[0]
# Find the entry widget and button for bupropion
for button in buttons:
try:
if "Take Bupropion" in button.cget("text"):
bupropion_button = button
break
except Exception:
pass
# Find the entry widget near the bupropion button
# This is tricky - let's use the first few entry widgets
if len(entry_widgets) >= 6: # Skip the first 5 (date, symptoms)
bupropion_entry = entry_widgets[5] # Should be first dose entry
if not all([bupropion_entry, bupropion_text, bupropion_button]):
print("❌ Could not find required widgets:")
print(f" Entry: {bupropion_entry is not None}")
print(f" Text: {bupropion_text is not None}")
print(f" Button: {bupropion_button is not None}")
edit_window.destroy()
return False
print("✅ Found bupropion widgets, starting automated test...")
# Test sequence: Add 3 doses
doses = ["100mg", "200mg", "300mg"]
for i, dose in enumerate(doses, 1):
print(f"\n🔄 Punch {i}: Adding {dose}")
# Get content before
before_content = bupropion_text.get(1.0, tk.END).strip()
print(f" Content before: '{before_content}'")
# Set the dose in entry
bupropion_entry.delete(0, tk.END)
bupropion_entry.insert(0, dose)
# Click the punch button
bupropion_button.invoke()
# Allow UI to update
root.update()
# Get content after
after_content = bupropion_text.get(1.0, tk.END).strip()
print(f" Content after: '{after_content}'")
# Count lines
lines = len([line for line in after_content.split("\n") if line.strip()])
print(f" Lines in text: {lines}")
punch_results.append(
{
"dose": dose,
"before": before_content,
"after": after_content,
"lines": lines,
}
)
# Small delay
root.after(100)
root.update()
# Now trigger save
print("\n💾 Triggering save...")
save_button = None
for button in buttons:
try:
if "Save" in button.cget("text"):
save_button = button
break
except Exception:
pass
if save_button:
save_button.invoke()
root.update()
else:
print("❌ Could not find Save button")
edit_window.destroy()
# Wait a moment for save to complete
root.after(100)
root.update()
# Analyze results
print("\n📊 RESULTS ANALYSIS:")
final_lines = punch_results[-1]["lines"] if punch_results else 0
print(f" Total punches: {len(punch_results)}")
print(f" Final content lines: {final_lines}")
print(f" Expected lines: {len(doses)}")
if save_result:
bup_doses = save_result.get("bupropion", "")
if bup_doses:
saved_dose_count = len(bup_doses.split("|"))
print(f" Saved dose count: {saved_dose_count}")
print(f" Saved doses: {bup_doses}")
# Check if all doses were saved
if saved_dose_count == len(doses):
print("✅ All doses were saved correctly!")
return True
else:
print("❌ Not all doses were saved!")
return False
else:
print("❌ No doses were saved!")
return False
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:
import contextlib
with contextlib.suppress(Exception):
root.destroy()
if __name__ == "__main__":
os.chdir("/home/will/Code/thechart")
success = test_automated_multiple_punches()
if success:
print("\n🎯 Automated test PASSED - multiple doses work correctly!")
else:
print("\n🚨 Automated test FAILED - multiple dose issue confirmed!")