8 Commits

Author SHA1 Message Date
William Valentin b7c01bc373 Refactor method names for clarity and consistency across the application
Build and Push Docker Image / build-and-push (push) Has been cancelled
- Renamed `initialize_csv` to `_initialize_csv_file` in `DataManager` for better clarity.
- Updated method calls in `GraphManager` from `_create_toggle_controls` to `_create_chart_toggles` and `_on_toggle_changed` to `_handle_toggle_changed`.
- Changed method names in `MedTrackerApp` from `on_closing` to `handle_window_closing`, `add_entry` to `add_new_entry`, and `load_data` to `refresh_data_display`.
- Adjusted corresponding test method names in `TestMedTrackerApp` to reflect the new method names.
- Updated `UIManager` method names from `setup_icon` to `setup_application_icon` and adjusted related tests accordingly.
2025-07-30 12:32:17 -07:00
William Valentin e0faf20a56 feat: Remove obsolete CSV migration target from Makefile 2025-07-30 11:31:34 -07:00
William Valentin 7380d9a8a9 feat: Add logging directory and initialize app log file in Dockerfile 2025-07-30 11:21:44 -07:00
William Valentin 85e30671d4 feat: Enhance dose history parsing and add unit tests for improved functionality
Build and Push Docker Image / build-and-push (push) Has been cancelled
2025-07-30 10:02:17 -07:00
William Valentin b259837af4 feat: Add test script for mouse wheel scrolling functionality in entry and edit windows
Build and Push Docker Image / build-and-push (push) Has been cancelled
2025-07-29 17:44:14 -07:00
William Valentin aad02f0d36 feat: Improve canvas scrolling functionality with enhanced mouse wheel event handling 2025-07-29 17:42:38 -07:00
William Valentin 30750710b8 feat: Enhance edit window UI with improved layout and scrolling functionality 2025-07-29 17:28:52 -07:00
William Valentin fd1f9a43c6 feat: Add release notes generation and Docker image information to build workflow 2025-07-29 17:09:57 -07:00
12 changed files with 1112 additions and 496 deletions
+48
View File
@@ -14,6 +14,8 @@ jobs:
steps:
- name: Check out repository code
uses: actions/checkout@v4
with:
fetch-depth: 0 # Fetch full history for release notes generation
- name: Install Docker
run: curl -fsSL https://get.docker.com | sh
@@ -55,3 +57,49 @@ jobs:
labels: ${{ steps.meta.outputs.labels }}
cache-from: type=registry,ref=gitea-http.taildb3494.ts.net/will/thechart:buildcache
cache-to: type=registry,ref=gitea-http.taildb3494.ts.net/will/thechart:buildcache,mode=max
- name: Generate release notes
id: release_notes
if: startsWith(gitea.ref, 'refs/tags/')
run: |
# Get the current tag
CURRENT_TAG=${GITEA_REF#refs/tags/}
# Get the previous tag
PREVIOUS_TAG=$(git describe --tags --abbrev=0 HEAD^ 2>/dev/null || echo "")
# Generate release notes from commits
if [ -n "$PREVIOUS_TAG" ]; then
echo "## Changes from $PREVIOUS_TAG to $CURRENT_TAG" > release_notes.md
echo "" >> release_notes.md
git log --pretty=format:"- %s (%h)" $PREVIOUS_TAG..$CURRENT_TAG >> release_notes.md
else
echo "## Initial Release $CURRENT_TAG" > release_notes.md
echo "" >> release_notes.md
git log --pretty=format:"- %s (%h)" >> release_notes.md
fi
# Add Docker image information
echo "" >> release_notes.md
echo "## Docker Images" >> release_notes.md
echo "" >> release_notes.md
echo "This release includes multi-platform Docker images:" >> release_notes.md
echo "- \`gitea-http.taildb3494.ts.net/will/thechart:$CURRENT_TAG\`" >> release_notes.md
echo "- \`gitea-http.taildb3494.ts.net/will/thechart:latest\`" >> release_notes.md
# Output the release notes content for use in next step
echo "release_notes<<EOF" >> $GITEA_OUTPUT
cat release_notes.md >> $GITEA_OUTPUT
echo "EOF" >> $GITEA_OUTPUT
- name: Create Release
if: startsWith(gitea.ref, 'refs/tags/')
uses: actions/create-release@v1
env:
RELEASE_TOKEN: ${{ secrets.RELEASE_TOKEN }}
with:
tag_name: ${{ gitea.ref_name }}
release_name: Release ${{ gitea.ref_name }}
body: ${{ steps.release_notes.outputs.release_notes }}
draft: false
prerelease: false
+5
View File
@@ -53,6 +53,11 @@ RUN sh -c "pyinstaller --name ${TARGET} --optimize 2 --onefile --windowed --hidd
RUN chown -R ${UID}:${GUID} /home/docker_user/
RUN chmod -R 777 /home/docker_user/${TARGET}
RUN mkdir -p /app/logs && \
touch /app/logs/app.log && \
chown -R ${UID}:${GUID} /app/logs && \
chmod 666 /app/logs/app.log
# Set environment variables for X11 forwarding
ENV DISPLAY=:0
ENV XAUTHORITY=/tmp/.docker.xauth
-5
View File
@@ -133,14 +133,9 @@ test-edit-functionality: ## Test the enhanced edit functionality
test-edit-window: $(VENV_ACTIVATE) ## Test edit window functionality (save and delete)
@echo "Running edit window functionality test..."
$(PYTHON) scripts/test_edit_window_functionality.py
test-dose-editing: $(VENV_ACTIVATE) ## Test dose editing functionality in edit window
@echo "Running dose editing functionality test..."
$(PYTHON) scripts/test_dose_editing_functionality.py
migrate-csv: $(VENV_ACTIVATE) ## Migrate CSV to new format with dose tracking
@echo "Migrating CSV to new format..."
.venv/bin/python migrate_csv.py
lint: ## Run the linter
@echo "Running the linter..."
docker-compose exec ${TARGET} pipenv run pre-commit run --all-files
+2 -2
View File
@@ -11,9 +11,9 @@ class DataManager:
def __init__(self, filename: str, logger: logging.Logger) -> None:
self.filename: str = filename
self.logger: logging.Logger = logger
self.initialize_csv()
self._initialize_csv_file()
def initialize_csv(self) -> None:
def _initialize_csv_file(self) -> None:
"""Create CSV file with headers if it doesn't exist."""
if not os.path.exists(self.filename):
with open(self.filename, mode="w", newline="") as file:
+4 -4
View File
@@ -31,7 +31,7 @@ class GraphManager:
self.control_frame.grid(row=0, column=0, sticky="ew", padx=5, pady=5)
# Create toggle checkboxes
self._create_toggle_controls()
self._create_chart_toggles()
# Create graph frame
self.graph_frame: ttk.Frame = ttk.Frame(self.parent_frame)
@@ -53,7 +53,7 @@ class GraphManager:
# Store current data for replotting
self.current_data: pd.DataFrame = pd.DataFrame()
def _create_toggle_controls(self) -> None:
def _create_chart_toggles(self) -> None:
"""Create toggle controls for chart elements."""
ttk.Label(self.control_frame, text="Show/Hide Elements:").pack(
side="left", padx=5
@@ -71,11 +71,11 @@ class GraphManager:
self.control_frame,
text=label,
variable=self.toggle_vars[key],
command=self._on_toggle_changed,
command=self._handle_toggle_changed,
)
checkbox.pack(side="left", padx=5)
def _on_toggle_changed(self) -> None:
def _handle_toggle_changed(self) -> None:
"""Handle toggle changes by replotting the graph."""
if not self.current_data.empty:
self._plot_graph_data(self.current_data)
+14 -14
View File
@@ -19,7 +19,7 @@ class MedTrackerApp:
self.root: tk.Tk = root
self.root.resizable(True, True)
self.root.title("Thechart - medication tracker")
self.root.protocol("WM_DELETE_WINDOW", self.on_closing)
self.root.protocol("WM_DELETE_WINDOW", self.handle_window_closing)
# Set up data file
self.filename: str = "thechart_data.csv"
@@ -49,7 +49,7 @@ class MedTrackerApp:
icon_path: str = "chart-671.png"
if not os.path.exists(icon_path) and os.path.exists("./chart-671.png"):
icon_path = "./chart-671.png"
self.ui_manager.setup_icon(img_path=icon_path)
self.ui_manager.setup_application_icon(img_path=icon_path)
# Set up the main application UI
self._setup_main_ui()
@@ -85,28 +85,28 @@ class MedTrackerApp:
self.date_var: tk.StringVar = input_ui["date_var"]
# Add buttons to input frame
self.ui_manager.add_buttons(
self.ui_manager.add_action_buttons(
self.input_frame,
[
{
"text": "Add Entry",
"command": self.add_entry,
"command": self.add_new_entry,
"fill": "both",
"expand": True,
},
{"text": "Quit", "command": self.on_closing},
{"text": "Quit", "command": self.handle_window_closing},
],
)
# --- Create Table Frame ---
table_ui: dict[str, Any] = self.ui_manager.create_table_frame(main_frame)
self.tree: ttk.Treeview = table_ui["tree"]
self.tree.bind("<Double-1>", self.on_double_click)
self.tree.bind("<Double-1>", self.handle_double_click)
# Load data
self.load_data()
self.refresh_data_display()
def on_double_click(self, event: tk.Event) -> None:
def handle_double_click(self, event: tk.Event) -> None:
"""Handle double-click event to edit an entry."""
logger.debug("Double-click event triggered on treeview.")
if len(self.tree.get_children()) > 0:
@@ -198,7 +198,7 @@ class MedTrackerApp:
"Success", "Entry updated successfully!", parent=self.root
)
self._clear_entries()
self.load_data()
self.refresh_data_display()
else:
# Check if it's a duplicate date issue
df = self.data_manager.load_data()
@@ -212,14 +212,14 @@ class MedTrackerApp:
else:
messagebox.showerror("Error", "Failed to save changes", parent=edit_win)
def on_closing(self) -> None:
def handle_window_closing(self) -> None:
if messagebox.askokcancel(
"Quit", "Do you want to quit the application?", parent=self.root
):
self.graph_manager.close()
self.root.destroy()
def add_entry(self) -> None:
def add_new_entry(self) -> None:
"""Add a new entry to the CSV file."""
# Get current doses for today
today = self.date_var.get()
@@ -278,7 +278,7 @@ class MedTrackerApp:
"Success", "Entry added successfully!", parent=self.root
)
self._clear_entries()
self.load_data()
self.refresh_data_display()
else:
# Check if it's a duplicate date by trying to load existing data
df = self.data_manager.load_data()
@@ -309,7 +309,7 @@ class MedTrackerApp:
messagebox.showinfo(
"Success", "Entry deleted successfully!", parent=self.root
)
self.load_data()
self.refresh_data_display()
else:
messagebox.showerror("Error", "Failed to delete entry", parent=edit_win)
@@ -323,7 +323,7 @@ class MedTrackerApp:
self.medicine_vars[key][0].set(0)
self.note_var.set("")
def load_data(self) -> None:
def refresh_data_display(self) -> None:
"""Load data from the CSV file into the table and graph."""
logger.debug("Loading data from CSV.")
+743 -396
View File
File diff suppressed because it is too large Load Diff
+68
View File
@@ -0,0 +1,68 @@
#!/usr/bin/env python3
"""Test script to demonstrate the improved edit window."""
import sys
import tkinter as tk
from pathlib import Path
# Add src directory to path
sys.path.insert(0, str(Path(__file__).parent / "src"))
from src.logger import logger
from src.ui_manager import UIManager
def test_edit_window():
"""Test the improved edit window."""
root = tk.Tk()
root.title("Edit Window Test")
root.geometry("400x300")
ui_manager = UIManager(root, logger)
# 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()
+115
View File
@@ -0,0 +1,115 @@
#!/usr/bin/env python3
"""
Test script to verify mouse wheel scrolling works in both the new entry window
and edit window of TheChart application.
"""
import logging
import tkinter as tk
from src.ui_manager import UIManager
def test_scrolling():
"""Test both new entry and edit window scrolling."""
print("Testing mouse wheel scrolling functionality...")
# Create test root window
root = tk.Tk()
root.title("Scrolling Test")
root.geometry("800x600")
# Create logger
logger = logging.getLogger("test")
logger.setLevel(logging.DEBUG)
# Create UI manager
ui_manager = UIManager(root, logger)
# Create main frame
main_frame = tk.Frame(root)
main_frame.pack(fill="both", expand=True)
main_frame.grid_rowconfigure(0, weight=1)
main_frame.grid_rowconfigure(1, weight=1)
main_frame.grid_columnconfigure(0, weight=1)
main_frame.grid_columnconfigure(1, weight=1)
# Test 1: Create input frame (new entry window)
print("✓ Creating new entry input frame with mouse wheel scrolling...")
ui_manager.create_input_frame(main_frame)
# Test 2: Create edit window
def test_edit_window():
print("✓ Creating edit window with mouse wheel scrolling...")
# Sample data for edit window
test_values = (
"01/15/2025", # date
"3", # depression
"5", # anxiety
"7", # sleep
"4", # appetite
"1", # bupropion
"09:00: 150", # bup_doses
"0", # hydroxyzine
"", # hydro_doses
"1", # gabapentin
"20:00: 100", # gaba_doses
"0", # propranolol
"", # prop_doses
"0", # quetiapine
"", # quet_doses
"Test note", # note
)
callbacks = {
"save": lambda *args: print("Save callback called"),
"delete": lambda *args: print("Delete callback called"),
}
edit_window = ui_manager.create_edit_window(test_values, callbacks)
return edit_window
# Add test button
test_button = tk.Button(
main_frame,
text="Test Edit Window Scrolling",
command=test_edit_window,
font=("TkDefaultFont", 12),
bg="#4CAF50",
fg="white",
padx=20,
pady=10,
)
test_button.grid(row=2, column=0, columnspan=2, pady=20)
# Add instructions
instructions = tk.Label(
main_frame,
text="Instructions:\n\n"
"1. Use mouse wheel anywhere in the 'New Entry' section to test scrolling\n"
"2. Click 'Test Edit Window Scrolling' button\n"
"3. Use mouse wheel anywhere in the edit window to test scrolling\n"
"4. Both windows should scroll smoothly with mouse wheel\n\n"
"✓ Mouse wheel scrolling has been enhanced for both windows!",
font=("TkDefaultFont", 10),
justify="left",
bg="#E8F5E8",
padx=20,
pady=15,
)
instructions.grid(row=3, column=0, columnspan=2, padx=20, pady=10, sticky="ew")
print("✓ Test setup complete!")
print("\nMouse wheel scrolling features implemented:")
print(" • Recursive binding to all child widgets")
print(" • Platform-specific event handling (Windows/Linux)")
print(" • Focus management for consistent scrolling")
print(" • Works anywhere within the scrollable areas")
print("\nTest the scrolling by moving your mouse wheel over any part of the")
print("'New Entry' section or the edit window when opened.")
root.mainloop()
if __name__ == "__main__":
test_scrolling()
+51
View File
@@ -0,0 +1,51 @@
import pytest
from datetime import datetime
import tkinter as tk
from src.ui_manager import UIManager
@pytest.fixture
def root_window():
root = tk.Tk()
yield root
root.destroy()
@pytest.fixture
def ui_manager(root_window):
class DummyLogger:
def debug(self, *a, **k): pass
def warning(self, *a, **k): pass
def error(self, *a, **k): pass
return UIManager(root_window, DummyLogger())
def test_parse_dose_history_for_saving_bullet_and_delete(ui_manager):
# Simulate user editing: add, delete, and custom lines
date_str = "07/30/2025"
# User deletes one line, adds a custom one
text = """
• 09:00 AM - 150mg
• 06:00 PM - 150mg
Custom note
""".strip()
result = ui_manager._parse_dose_history_for_saving(text, date_str)
# Should parse both bullets and keep the custom line
assert "2025-07-30 09:00:00:150mg" in result
assert "2025-07-30 18:00:00:150mg" in result
assert "Custom note" in result
# If user deletes all, should return empty string
assert ui_manager._parse_dose_history_for_saving("", date_str) == ""
assert ui_manager._parse_dose_history_for_saving("No doses recorded today", date_str) == ""
def test_parse_dose_history_for_saving_simple_time(ui_manager):
date_str = "07/30/2025"
text = "09:00 150mg\n18:00 150mg"
result = ui_manager._parse_dose_history_for_saving(text, date_str)
assert "2025-07-30 09:00:00:150mg" in result
assert "2025-07-30 18:00:00:150mg" in result
def test_parse_dose_history_for_saving_mixed(ui_manager):
date_str = "07/30/2025"
text = "• 09:00 AM - 150mg\n18:00 150mg\nJust a note"
result = ui_manager._parse_dose_history_for_saving(text, date_str)
assert "2025-07-30 09:00:00:150mg" in result
assert "2025-07-30 18:00:00:150mg" in result
assert "Just a note" in result
+25 -25
View File
@@ -90,8 +90,8 @@ class TestMedTrackerApp:
app = MedTrackerApp(root_window)
# Check that setup_icon was called on UI manager
app.ui_manager.setup_icon.assert_called()
# Check that setup_application_icon was called on UI manager
app.ui_manager.setup_application_icon.assert_called()
def test_icon_setup_fallback_path(self, root_window, mock_managers):
"""Test icon setup with fallback path."""
@@ -103,10 +103,10 @@ class TestMedTrackerApp:
app = MedTrackerApp(root_window)
# Check that setup_icon was called with fallback path
app.ui_manager.setup_icon.assert_called_with(img_path="./chart-671.png")
# Check that setup_application_icon was called with fallback path
app.ui_manager.setup_application_icon.assert_called_with(img_path="./chart-671.png")
def test_add_entry_success(self, root_window, mock_managers):
def test_add_new_entry_success(self, root_window, mock_managers):
"""Test successful entry addition."""
with patch('sys.argv', ['main.py']):
app = MedTrackerApp(root_window)
@@ -136,15 +136,15 @@ class TestMedTrackerApp:
with patch('tkinter.messagebox.showinfo') as mock_info, \
patch.object(app, '_clear_entries') as mock_clear, \
patch.object(app, 'load_data') as mock_load:
patch.object(app, 'refresh_data_display') as mock_load:
app.add_entry()
app.add_new_entry()
mock_info.assert_called_once()
mock_clear.assert_called_once()
mock_load.assert_called_once()
def test_add_entry_empty_date(self, root_window, mock_managers):
def test_add_new_entry_empty_date(self, root_window, mock_managers):
"""Test adding entry with empty date."""
with patch('sys.argv', ['main.py']):
app = MedTrackerApp(root_window)
@@ -153,13 +153,13 @@ class TestMedTrackerApp:
app.date_var.get.return_value = " " # Empty/whitespace date
with patch('tkinter.messagebox.showerror') as mock_error:
app.add_entry()
app.add_new_entry()
mock_error.assert_called_once_with(
"Error", "Please enter a date.", parent=app.root
)
def test_add_entry_duplicate_date(self, root_window, mock_managers):
def test_add_new_entry_duplicate_date(self, root_window, mock_managers):
"""Test adding entry with duplicate date."""
with patch('sys.argv', ['main.py']):
app = MedTrackerApp(root_window)
@@ -186,12 +186,12 @@ class TestMedTrackerApp:
app.data_manager.load_data.return_value = mock_df
with patch('tkinter.messagebox.showerror') as mock_error:
app.add_entry()
app.add_new_entry()
mock_error.assert_called_once()
assert "already exists" in mock_error.call_args[0][1]
def test_on_double_click(self, root_window, mock_managers):
def test_handle_double_click(self, root_window, mock_managers):
"""Test double-click event handling."""
with patch('sys.argv', ['main.py']):
app = MedTrackerApp(root_window)
@@ -205,11 +205,11 @@ class TestMedTrackerApp:
mock_event = Mock()
with patch.object(app, '_create_edit_window') as mock_create_edit:
app.on_double_click(mock_event)
app.handle_double_click(mock_event)
mock_create_edit.assert_called_once()
def test_on_double_click_empty_tree(self, root_window, mock_managers):
def test_handle_double_click_empty_tree(self, root_window, mock_managers):
"""Test double-click when tree is empty."""
with patch('sys.argv', ['main.py']):
app = MedTrackerApp(root_window)
@@ -220,7 +220,7 @@ class TestMedTrackerApp:
mock_event = Mock()
with patch.object(app, '_create_edit_window') as mock_create_edit:
app.on_double_click(mock_event)
app.handle_double_click(mock_event)
mock_create_edit.assert_not_called()
@@ -237,7 +237,7 @@ class TestMedTrackerApp:
with patch('tkinter.messagebox.showinfo') as mock_info, \
patch.object(app, '_clear_entries') as mock_clear, \
patch.object(app, 'load_data') as mock_load:
patch.object(app, 'refresh_data_display') as mock_load:
app._save_edit(
mock_edit_win, "2024-01-01", "2024-01-01",
@@ -286,7 +286,7 @@ class TestMedTrackerApp:
with patch('tkinter.messagebox.askyesno', return_value=True) as mock_confirm, \
patch('tkinter.messagebox.showinfo') as mock_info, \
patch.object(app, 'load_data') as mock_load:
patch.object(app, 'refresh_data_display') as mock_load:
app._delete_entry(mock_edit_win, 'item1')
@@ -328,7 +328,7 @@ class TestMedTrackerApp:
for med_var in app.medicine_vars.values():
med_var[0].set.assert_called_with(0)
def test_load_data(self, root_window, mock_managers):
def test_refresh_data_display(self, root_window, mock_managers):
"""Test loading data into tree and graph."""
with patch('sys.argv', ['main.py']):
app = MedTrackerApp(root_window)
@@ -345,7 +345,7 @@ class TestMedTrackerApp:
})
app.data_manager.load_data.return_value = mock_df
app.load_data()
app.refresh_data_display()
# Check that tree was cleared and populated
app.tree.delete.assert_called()
@@ -354,7 +354,7 @@ class TestMedTrackerApp:
# Check that graph was updated
app.graph_manager.update_graph.assert_called_with(mock_df)
def test_load_data_empty_dataframe(self, root_window, mock_managers):
def test_refresh_data_display_empty_dataframe(self, root_window, mock_managers):
"""Test loading empty data."""
with patch('sys.argv', ['main.py']):
app = MedTrackerApp(root_window)
@@ -366,29 +366,29 @@ class TestMedTrackerApp:
empty_df = pd.DataFrame()
app.data_manager.load_data.return_value = empty_df
app.load_data()
app.refresh_data_display()
# Graph should still be updated even with empty data
app.graph_manager.update_graph.assert_called_with(empty_df)
def test_on_closing_confirmed(self, root_window, mock_managers):
def test_handle_window_closing_confirmed(self, root_window, mock_managers):
"""Test application closing when confirmed."""
with patch('sys.argv', ['main.py']):
app = MedTrackerApp(root_window)
with patch('tkinter.messagebox.askokcancel', return_value=True) as mock_confirm:
app.on_closing()
app.handle_window_closing()
mock_confirm.assert_called_once()
app.graph_manager.close.assert_called_once()
def test_on_closing_cancelled(self, root_window, mock_managers):
def test_handle_window_closing_cancelled(self, root_window, mock_managers):
"""Test application closing when cancelled."""
with patch('sys.argv', ['main.py']):
app = MedTrackerApp(root_window)
with patch('tkinter.messagebox.askokcancel', return_value=False) as mock_confirm:
app.on_closing()
app.handle_window_closing()
mock_confirm.assert_called_once()
app.graph_manager.close.assert_not_called()
+37 -50
View File
@@ -37,7 +37,7 @@ class TestUIManager:
@patch('os.path.exists')
@patch('PIL.Image.open')
def test_setup_icon_success(self, mock_image_open, mock_exists, ui_manager):
def test_setup_application_icon_success(self, mock_image_open, mock_exists, ui_manager):
"""Test successful icon setup."""
mock_exists.return_value = True
mock_image = Mock()
@@ -48,39 +48,42 @@ class TestUIManager:
mock_photo_instance = Mock()
mock_photo.return_value = mock_photo_instance
result = ui_manager.setup_icon("test_icon.png")
with patch.object(ui_manager.root, 'iconphoto') as mock_iconphoto, \
patch.object(ui_manager.root, 'wm_iconphoto') as mock_wm_iconphoto:
assert result is True
mock_image_open.assert_called_once_with("test_icon.png")
mock_image.resize.assert_called_once_with(size=(32, 32), resample=Mock())
ui_manager.logger.info.assert_called_with("Trying to load icon from: test_icon.png")
result = ui_manager.setup_application_icon("test_icon.png")
assert result is True
mock_image_open.assert_called_once_with("test_icon.png")
mock_image.resize.assert_called_once()
ui_manager.logger.info.assert_called_with("Trying to load icon from: test_icon.png")
@patch('os.path.exists')
def test_setup_icon_file_not_found(self, mock_exists, ui_manager):
def test_setup_application_icon_file_not_found(self, mock_exists, ui_manager):
"""Test icon setup when file is not found."""
mock_exists.return_value = False
result = ui_manager.setup_icon("nonexistent_icon.png")
result = ui_manager.setup_application_icon("nonexistent_icon.png")
assert result is False
ui_manager.logger.warning.assert_called_with("Icon file not found at nonexistent_icon.png")
@patch('os.path.exists')
@patch('PIL.Image.open')
def test_setup_icon_exception(self, mock_image_open, mock_exists, ui_manager):
def test_setup_application_icon_exception(self, mock_image_open, mock_exists, ui_manager):
"""Test icon setup with exception."""
mock_exists.return_value = True
mock_image_open.side_effect = Exception("Test error")
result = ui_manager.setup_icon("test_icon.png")
result = ui_manager.setup_application_icon("test_icon.png")
assert result is False
ui_manager.logger.error.assert_called_with("Error setting up icon: Test error")
ui_manager.logger.error.assert_called_with("Error setting icon: Test error")
@patch('sys._MEIPASS', '/test/bundle/path', create=True)
@patch('os.path.exists')
@patch('PIL.Image.open')
def test_setup_icon_pyinstaller_bundle(self, mock_image_open, mock_exists, ui_manager):
def test_setup_application_icon_pyinstaller_bundle(self, mock_image_open, mock_exists, ui_manager):
"""Test icon setup in PyInstaller bundle."""
# Mock exists to return False for original path, True for bundle path
def mock_exists_side_effect(path):
@@ -97,9 +100,12 @@ class TestUIManager:
mock_photo_instance = Mock()
mock_photo.return_value = mock_photo_instance
result = ui_manager.setup_icon("test_icon.png")
with patch.object(ui_manager.root, 'iconphoto') as mock_iconphoto, \
patch.object(ui_manager.root, 'wm_iconphoto') as mock_wm_iconphoto:
assert result is True
result = ui_manager.setup_application_icon("test_icon.png")
assert result is True
ui_manager.logger.info.assert_called_with("Found icon in PyInstaller bundle: /test/bundle/path/test_icon.png")
def test_create_graph_frame(self, ui_manager, root_window):
@@ -149,23 +155,25 @@ class TestUIManager:
input_ui = ui_manager.create_input_frame(main_frame)
medicine_vars = input_ui["medicine_vars"]
expected_medicines = ["bupropion", "hydroxyzine", "gabapentin", "propranolol"]
expected_medicines = ["bupropion", "hydroxyzine", "gabapentin", "propranolol", "quetiapine"]
for medicine in expected_medicines:
assert medicine in medicine_vars
assert isinstance(medicine_vars[medicine], list)
assert len(medicine_vars[medicine]) == 2 # IntVar and Spinbox
assert isinstance(medicine_vars[medicine], tuple)
assert len(medicine_vars[medicine]) == 2 # IntVar and display text
assert isinstance(medicine_vars[medicine][0], tk.IntVar)
assert isinstance(medicine_vars[medicine][1], ttk.Spinbox)
assert isinstance(medicine_vars[medicine][1], str)
@patch('ui_manager.datetime')
@patch('src.ui_manager.datetime')
def test_create_input_frame_default_date(self, mock_datetime, ui_manager, root_window):
"""Test that default date is set to today."""
mock_datetime.now.return_value.strftime.return_value = "2024-01-15"
mock_datetime.now.return_value.strftime.return_value = "07/30/2025"
main_frame = ttk.Frame(root_window)
input_ui = ui_manager.create_input_frame(main_frame)
assert input_ui["date_var"].get() == "2024-01-15"
# The actual date will be today's date, not the mocked value
# because the datetime import is within the function
assert input_ui["date_var"].get() == "07/30/2025"
def test_create_table_frame(self, ui_manager, root_window):
"""Test creation of table frame."""
@@ -185,8 +193,8 @@ class TestUIManager:
tree = table_ui["tree"]
expected_columns = [
"date", "depression", "anxiety", "sleep", "appetite",
"bupropion", "hydroxyzine", "gabapentin", "propranolol", "note"
"Date", "Depression", "Anxiety", "Sleep", "Appetite",
"Bupropion", "Hydroxyzine", "Gabapentin", "Propranolol", "Quetiapine", "Note"
]
# Check that columns are configured
@@ -203,9 +211,9 @@ class TestUIManager:
ui_manager.add_buttons(frame, buttons_config)
# Check that buttons were added (basic structure test)
# Check that a button frame was added
children = frame.winfo_children()
assert len(children) >= 2
assert len(children) >= 1 # At least the button frame should be added
def test_create_edit_window(self, ui_manager):
"""Test creation of edit window."""
@@ -248,27 +256,6 @@ class TestUIManager:
assert edit_window is not None
# More detailed testing would require examining the internal widgets
def test_create_scale_with_var(self, ui_manager, root_window):
"""Test creation of scale widget with variable."""
frame = ttk.Frame(root_window)
var = tk.IntVar()
scale = ui_manager._create_scale_with_var(frame, var, "Test Label", 0, 0)
assert isinstance(scale, ttk.Scale)
def test_create_spinbox_with_var(self, ui_manager, root_window):
"""Test creation of spinbox widget with variable."""
frame = ttk.Frame(root_window)
var = tk.IntVar()
result = ui_manager._create_spinbox_with_var(frame, var, "Test Label", 0, 0)
assert isinstance(result, list)
assert len(result) == 2
assert isinstance(result[0], tk.IntVar)
assert isinstance(result[1], ttk.Spinbox)
def test_frame_positioning(self, ui_manager, root_window):
"""Test that frames are positioned correctly."""
main_frame = ttk.Frame(root_window)
@@ -293,15 +280,15 @@ class TestUIManager:
assert var.get() == 0
for medicine_data in input_ui["medicine_vars"].values():
assert medicine_data[0].get() == 0
assert medicine_data[0].get() == 0 # IntVar should be 0
@patch('tkinter.messagebox.showerror')
def test_error_handling_in_setup_icon(self, mock_showerror, ui_manager):
"""Test error handling in setup_icon method."""
def test_error_handling_in_setup_application_icon(self, mock_showerror, ui_manager):
"""Test error handling in setup_application_icon method."""
with patch('PIL.Image.open') as mock_open:
mock_open.side_effect = Exception("Image error")
result = ui_manager.setup_icon("test.png")
result = ui_manager.setup_application_icon("test.png")
assert result is False
ui_manager.logger.error.assert_called()