-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathmanual_testing.py
More file actions
executable file
·337 lines (283 loc) · 11.3 KB
/
manual_testing.py
File metadata and controls
executable file
·337 lines (283 loc) · 11.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
#!/usr/bin/env python3
"""Simple testing utility for cc-notifier notifications."""
import json
import os
import subprocess
import sys
import time
import uuid
from pathlib import Path
from typing import Optional
# Check cc_notifier exists and import functions for isolated testing
try:
from cc_notifier import (
HookData,
PushConfig,
create_notification_data,
send_notification,
send_pushover_notification,
)
except ImportError:
print("❌ cc_notifier.py must be in the same directory")
sys.exit(1)
# Test session data
session_id = f"test-{uuid.uuid4().hex[:8]}"
hook_data = {
"session_id": session_id,
"cwd": str(Path.cwd()),
"hook_event_name": "Stop",
"message": "Test notification completed successfully!",
}
def get_push_credentials() -> tuple[Optional[str], Optional[str]]:
"""Get push credentials from environment or Claude settings."""
# Environment variables first
token, user = os.getenv("PUSHOVER_API_TOKEN"), os.getenv("PUSHOVER_USER_KEY")
if token and user:
return token, user
# Claude settings fallback
try:
with open(Path.home() / ".claude" / "settings.json") as f:
env_vars = json.load(f).get("env", {})
token, user = (
env_vars.get("PUSHOVER_API_TOKEN"),
env_vars.get("PUSHOVER_USER_KEY"),
)
return (token, user) if token and user else (None, None)
except (FileNotFoundError, json.JSONDecodeError, OSError):
return None, None
def run_command(cmd: str, debug: bool = False) -> None:
"""Run cc-notifier command with test data."""
env = os.environ.copy()
# Set wrapper environment variable to allow direct execution of cc_notifier.py
env["CC_NOTIFIER_WRAPPER"] = "1"
token, user = get_push_credentials()
if token and user:
env.update({"PUSHOVER_API_TOKEN": token, "PUSHOVER_USER_KEY": user})
command_args = ["python3", "cc_notifier.py"]
if debug:
command_args.append("--debug")
command_args.append(cmd)
try:
result = subprocess.run(
command_args,
input=json.dumps(hook_data),
text=True,
capture_output=True,
env=env,
)
if result.returncode != 0:
print(f"❌ Command '{cmd}' failed: {result.stderr.strip()}")
if debug and result.stdout:
print(f"🔍 Debug output: {result.stdout.strip()}")
except Exception as e:
print(f"❌ Command '{cmd}' failed: {e}")
def cleanup(debug: bool = False) -> None:
"""Clean up test session."""
print("\n🧹 Cleaning up...")
run_command("cleanup", debug)
def test_notification(
title: str, test_hook_data: HookData, push_only: bool = False, debug: bool = False
) -> None:
"""Common notification testing logic."""
title, subtitle, message = create_notification_data(test_hook_data)
if push_only:
# Test push notification only
token, user = get_push_credentials()
if not token or not user:
print("❌ Push notifications disabled - missing credentials")
return
print("📲 Sending test push notification...")
push_config = PushConfig(token=token, user=user)
current_time = time.strftime("%I:%M %p").lstrip("0")
success = send_pushover_notification(
push_config, f"{subtitle} 🔔 {current_time}", message
)
print(
"✅ Push notification sent!" if success else "❌ Push notification failed"
)
else:
# Test local notification with optional debug formatting
print("📱 Sending test local notification...")
if debug:
# Apply debug formatting like cc_notifier.py does
now = time.time()
dt = time.localtime(now)
milliseconds = int((now % 1) * 1000)
current_time = f"{time.strftime('%H:%M:%S', dt)}.{milliseconds:03d}"
title = f"[DEBUG] {title} [{current_time}]"
print(f"🔍 Debug title: {title}")
try:
send_notification(title=title, subtitle=subtitle, message=message)
print("✅ Local notification sent! Check your notification center")
except Exception as e:
print(f"❌ Local notification failed: {e}")
def test_system_mode(debug: bool = False) -> None:
"""Test full Claude Code hook emulation."""
print(f"🔧 Testing cc-notifier (Session: {session_id})")
if debug:
print("🐛 Debug mode ENABLED - detailed logging active")
# Check push configuration
push_token, push_user = get_push_credentials()
status = "✅ ENABLED" if push_token and push_user else "❌ DISABLED"
print(f"📲 Push notifications: {status}")
if not push_token or not push_user:
print(
" Set PUSHOVER_API_TOKEN and PUSHOVER_USER_KEY in environment or ~/.claude/settings.json"
)
print("💡 Switch to another app during countdown to see notification\n")
# Initialize and run test
run_command("init", debug)
print("✅ Session initialized - switch away now!")
# Countdown and notify
print("⏱️ Checking for notification in ", end="", flush=True)
for i in range(5, 0, -1):
print(f"{i}...", end="", flush=True)
time.sleep(1)
print(" NOW!")
print("📢 Sending notification if window focus changed...")
run_command("notify", debug)
time.sleep(3)
cleanup(debug)
def test_push_only() -> None:
"""Test push notifications only."""
print("🧪 Testing push notifications only...")
test_hook_data = HookData(
session_id=session_id,
cwd=str(Path.cwd()),
message="Push notification test successful!",
)
test_notification("Claude Code 🔔 (Test)", test_hook_data, push_only=True)
def test_local_only(debug: bool = False) -> None:
"""Test local notifications only."""
print("🧪 Testing local notifications only...")
if debug:
print("🐛 Debug mode ENABLED - notification will show debug timestamp")
test_hook_data = HookData(
session_id=session_id,
cwd=str(Path.cwd()),
message="Local notification test successful!",
)
test_notification("Claude Code 🔔 (Test)", test_hook_data, debug=debug)
def _get_app_info() -> tuple[str, str]:
"""Get current app path and display name."""
from pathlib import Path
from cc_notifier import get_focused_window_id
try:
_, app_path = get_focused_window_id()
app_display_name = Path(app_path).stem
print(f"✅ Detected current app: {app_display_name}")
print(f" Path: {app_path}")
return app_path, app_display_name
except Exception as e:
print(f"❌ Failed to detect app: {e}")
print("💡 Using Terminal as fallback")
return "/System/Applications/Utilities/Terminal.app", "Terminal"
def _test_open_command(app_path: str, app_display_name: str) -> None:
"""Test that open command works for the app."""
import subprocess
print(f"\n🔍 Testing if 'open \"{app_path}\"' works...")
try:
result = subprocess.run(
["open", app_path], capture_output=True, text=True, timeout=5
)
if result.returncode == 0:
print(f"✅ Successfully opened {app_display_name}")
else:
print(f"⚠️ Warning: 'open \"{app_path}\"' failed")
print(f" Error: {result.stderr.strip()}")
print(" Continuing anyway...")
except Exception as e:
print(f"⚠️ Warning: Error testing open command: {e}")
print(" Continuing anyway...")
def _send_test_notification(app_path: str, app_display_name: str) -> None:
"""Send test notification and report results."""
import subprocess
from cc_notifier import TERMINAL_NOTIFIER
cmd = [
TERMINAL_NOTIFIER,
"-title",
"cc-notifier Test",
"-subtitle",
f"Click to focus {app_display_name}",
"-message",
"Testing application-level focus fallback",
"-sound",
"Glass",
"-execute",
f'open "{app_path}"',
]
print("🔍 Executing terminal-notifier command:")
print(f" Command: {' '.join(cmd)}\n")
try:
result = subprocess.run(cmd, capture_output=True, text=True, timeout=10)
print(f"📡 terminal-notifier exit code: {result.returncode}")
if result.stdout:
print(f" stdout: {result.stdout}")
if result.stderr:
print(f" stderr: {result.stderr}")
if result.returncode == 0:
print("\n✅ Notification sent successfully!")
print(f"👆 Click the notification to test focusing {app_display_name}")
print(" (The notification should still be visible)")
print("\n💡 Using app path approach for reliable focusing")
print(f" Path: {app_path}")
else:
print(f"\n❌ terminal-notifier failed with exit code {result.returncode}")
except subprocess.TimeoutExpired:
print("⏱️ terminal-notifier timed out (but notification may still be visible)")
except Exception as e:
print(f"❌ Failed to send notification: {e}")
def test_app_focus() -> None:
"""Test application-level focus (error notification fallback behavior)."""
print("🧪 Testing application-level focus...")
print("📱 This simulates the error notification fallback behavior\n")
app_path, app_display_name = _get_app_info()
_test_open_command(app_path, app_display_name)
print("\n💡 Switch to another app, then click the notification to test focus")
print(f" Expected: Clicking notification will focus {app_display_name}\n")
# Wait for user to switch apps
print("⏱️ Sending notification in ", end="", flush=True)
for i in range(3, 0, -1):
print(f"{i}...", end="", flush=True)
time.sleep(1)
print(" NOW!\n")
_send_test_notification(app_path, app_display_name)
def show_help() -> None:
"""Display help information."""
print("🔧 cc-notifier Test Utility\n")
print("Usage: python3 manual_testing.py <mode> [--debug]\n")
print("Modes:")
print(" local - Test local notifications only")
print(" push - Test push notifications only (requires credentials)")
print(" system - Full Claude Code hook emulation")
print(" app-focus - Test application-level focus fallback")
print("\nOptions:")
print(
" --debug - Enable debug mode with detailed logging and timestamped notifications"
)
if __name__ == "__main__":
debug = False # Initialize debug variable
try:
# Parse arguments
debug = "--debug" in sys.argv
if debug:
sys.argv.remove("--debug")
if len(sys.argv) != 2 or sys.argv[1] in ("-h", "--help", "help"):
show_help()
sys.exit(0 if len(sys.argv) == 2 else 1)
mode = sys.argv[1]
if mode == "push":
test_push_only()
elif mode == "local":
test_local_only(debug=debug)
elif mode == "system":
test_system_mode(debug=debug)
elif mode == "app-focus":
test_app_focus()
else:
print(f"❌ Unknown mode: {mode}")
show_help()
sys.exit(1)
except KeyboardInterrupt:
cleanup(debug)
sys.exit(0)