Files
dotfiles/quickshell/tests/notifications.py
T
2026-11-17 18:15:16 +07:00

178 lines
9.3 KiB
Python

#!/usr/bin/env python3
"""Exercise real notification D-Bus lifecycle in a private session and temporary state."""
import json
import os
from pathlib import Path
import subprocess
import sys
import tempfile
import time
# Isolation is enforced even when the test is run without dbus-run-session.
if os.environ.get('ADAPTIVE_NOTIFICATION_TEST_BUS') != '1':
env = dict(os.environ, ADAPTIVE_NOTIFICATION_TEST_BUS='1')
os.execvpe('dbus-run-session', ['dbus-run-session', '--', sys.executable, __file__], env)
from gi.repository import Gio, GLib
ROOT = Path(__file__).resolve().parents[1]
connection = Gio.bus_get_sync(Gio.BusType.SESSION, None)
events = []
connection.signal_subscribe(None, 'org.freedesktop.Notifications', None,
'/org/freedesktop/Notifications', None, Gio.DBusSignalFlags.NONE,
lambda conn, sender, path, interface, name, params: events.append((name, params.unpack())))
def call(method, signature, values):
return connection.call_sync('org.freedesktop.Notifications', '/org/freedesktop/Notifications',
'org.freedesktop.Notifications', method,
GLib.Variant(signature, values), None,
Gio.DBusCallFlags.NONE, 5000, None).unpack()
def notify(title, replace=0, timeout=0, urgency=1, transient=False, actions=None):
return call('Notify', '(susssasa{sv}i)', ('Adaptive Test', replace, '', title, 'Body <b>plain</b>',
actions or [], {'urgency': GLib.Variant('y', urgency), 'transient': GLib.Variant('b', transient)}, timeout))[0]
def pump():
context = GLib.MainContext.default()
while context.pending(): context.iteration(False)
def wait_for(predicate, description, timeout=8):
end = time.monotonic() + timeout
while time.monotonic() < end:
pump()
if predicate(): return
time.sleep(.05)
raise AssertionError(description)
with tempfile.TemporaryDirectory(prefix='adaptive-notifications-') as tmp:
env = dict(os.environ, QT_QPA_PLATFORM='wayland', QT_QUICK_CONTROLS_STYLE='Material',
XDG_STATE_HOME=tmp, XDG_CACHE_HOME=tmp, ADAPTIVE_NOTIFICATIONS='1')
log_path = Path(tmp, 'shell.log')
log = log_path.open('w')
process = None
def start():
return subprocess.Popen(['quickshell', '-p', str(ROOT), '--no-color'], env=env,
stdout=log, stderr=subprocess.STDOUT)
def ipc(*args):
result = subprocess.run(['quickshell', 'ipc', '--pid', str(process.pid), 'call', 'shell', *args],
env=env, capture_output=True, text=True, timeout=30)
if result.returncode: raise RuntimeError(result.stderr)
return result.stdout
def status(): return json.loads(ipc('status'))
def ready():
if process.poll() is not None: raise RuntimeError(log_path.read_text())
try: return status()['preferencesWritable'] and status()['notificationsReady']
except (RuntimeError, ValueError): return False
def stop():
process.terminate()
try: process.wait(timeout=3)
except subprocess.TimeoutExpired: process.kill(); process.wait()
try:
process = start()
wait_for(ready, 'shell readiness', 60)
call('GetServerInformation', '()', ())
persistent = notify('original')
wait_for(lambda: len(status()['notifications']) == 1, 'first notification')
assert notify('updated', replace=persistent) == persistent
wait_for(lambda: status()['notifications'][0]['summary'] == 'updated', 'replacement')
assert status()['notificationHistoryCount'] == 1
count = status()['notificationHistoryCount']
ipc('reload')
time.sleep(.5)
wait_for(ready, 'reloaded shell readiness', 60)
wait_for(lambda: len(status()['notifications']) == 1, 'live notification restored after reload')
assert status()['notificationHistoryCount'] == count, 'QML reload must not duplicate history'
assert status()['notificationPopup'] == 0, 'QML reload must not replay popups'
timed_reload = notify('reload deadline', timeout=10000)
reload_history_path = next(Path(tmp).rglob('notifications.json'))
def recorded_deadline():
return next((e['deadline'] for e in json.loads(reload_history_path.read_text())['entries'] if e['summary'] == 'reload deadline'), None)
wait_for(lambda: recorded_deadline() is not None, 'deadline recorded')
deadline = recorded_deadline()
ipc('reload')
time.sleep(.5)
wait_for(ready, 'second reload readiness', 60)
wait_for(lambda: len(status()['notifications']) == 2, 'timed notification restored')
assert recorded_deadline() == deadline, 'Reload must preserve the absolute deadline'
ipc('dismissNotification', str(timed_reload))
print('PASS replacement and QML reload preserve history and timer deadline', flush=True)
expiring = notify('short timeout', timeout=250)
wait_for(lambda: ('NotificationClosed', (expiring, 1)) in events, 'expired close reason')
ipc('dismissNotification', str(persistent))
wait_for(lambda: ('NotificationClosed', (persistent, 2)) in events, 'dismissed close reason')
closing = notify('client close')
call('CloseNotification', '(u)', (closing,))
wait_for(lambda: ('NotificationClosed', (closing, 3)) in events, 'client close reason')
resetting = notify('timer before replacement', timeout=1600)
time.sleep(.8)
notify('timer after replacement', replace=resetting, timeout=1600)
time.sleep(1)
assert any(n['id'] == resetting for n in status()['notifications']), 'Replacement must restart timeout'
wait_for(lambda: ('NotificationClosed', (resetting, 1)) in events, 'replacement expiration')
print('PASS timeout, replacement timer reset and close reasons 1/2/3', flush=True)
action_id = notify('action', actions=['open', 'Open'])
wait_for(lambda: any(n['id'] == action_id for n in status()['notifications']), 'action notification')
ipc('notificationAction', str(action_id), 'open')
wait_for(lambda: ('ActionInvoked', (action_id, 'open')) in events, 'ActionInvoked')
print('PASS notification actions', flush=True)
ipc('dnd', 'true')
quiet = notify('quiet')
wait_for(lambda: any(n['id'] == quiet for n in status()['notifications']), 'DND retains notification')
assert status()['notificationPopup'] == 0, status()
ipc('dnd', 'false')
assert status()['notificationPopup'] == 0, 'DND must not replay popups'
print('PASS DND suppresses popups without dropping notifications', flush=True)
critical = notify('critical', timeout=100, urgency=2)
time.sleep(.35)
assert any(n['id'] == critical for n in status()['notifications'])
assert status()['notificationPopup'] == critical
before = status()['notificationHistoryCount']
transient_id = notify('transient', transient=True)
wait_for(lambda: any(n['id'] == transient_id for n in status()['notifications']), 'transient notification')
assert status()['notificationHistoryCount'] == before
print('PASS critical stays live and transient skips history', flush=True)
history_path = next(Path(tmp).rglob('notifications.json'))
wait_for(lambda: len(json.loads(history_path.read_text())['entries']) == before, 'history written')
assert history_path.parent.stat().st_mode & 0o777 == 0o700
history = json.loads(history_path.read_text())
assert not any(e['summary'] == 'transient' for e in history['entries'])
assert len([e for e in history['entries'] if e['summary'] == 'updated']) == 1
ipc('dnd', 'true')
stop()
process = start()
wait_for(ready, 'restarted shell readiness', 60)
wait_for(lambda: status()['notificationHistoryCount'] == before, 'history restored')
assert status()['notificationDnd'] is True
assert not status()['notifications'], 'Archived notifications cannot restore live actions'
assert status()['notificationGroups'] == 1, 'One application must form one group'
ipc('notifications')
ipc('clearNotifications')
wait_for(lambda: not json.loads(history_path.read_text())['entries'], 'history cleared')
assert status()['notificationGroups'] == 0
ipc('notificationHistory', 'false')
notify('history disabled')
time.sleep(.2)
assert status()['notificationHistoryCount'] == 0
ipc('clearNotifications')
print('PASS grouping, private history, restart, clear-all and history opt-out', flush=True)
stop()
history_path.write_text('{invalid history')
process = start()
wait_for(ready, 'shell with invalid history', 60)
assert status()['notificationHistoryError']
notify('corrupt file must survive')
time.sleep(.2)
assert history_path.read_text() == '{invalid history'
print('PASS corrupt history preserved while delivery continues', flush=True)
finally:
if process and process.poll() is None: stop()
log.close()
logs = log_path.read_text()
print(logs)
for marker in ['Failed to load configuration', 'ReferenceError', 'TypeError', 'Binding loop', 'Cannot assign', 'Cannot create delegate']:
assert marker not in logs, marker