added adaptive quickshell

This commit is contained in:
wt committed 2026-11-17 18:15:16 +07:00
1 parent 6eb56d2065
commit 5b33a73fd8
189 files changed
+8678 -15

No files matched your search

+27
View File
@@ -0,0 +1,27 @@
#!/usr/bin/env python3
"""Real controllers and Process, fake helper only; no production Bluetooth singleton."""
import os
from pathlib import Path
import shutil
import subprocess
import tempfile
root = Path(__file__).resolve().parents[1]
with tempfile.TemporaryDirectory(prefix='adaptive-bluetooth-controller-') as tmp:
runtime = Path(tmp, 'runtime')
runtime.mkdir(mode=0o700)
config = Path(tmp, 'config')
config.mkdir()
shutil.copyfile(root / 'tests/fixtures/bluetooth.qml', config / 'shell.qml')
shutil.copyfile(root / 'tests/bluetooth_fake.py', config / 'bluetooth_fake.py')
for name in ['BluetoothController.qml', 'BluetoothDiscovery.qml']:
shutil.copyfile(root / 'services' / name, config / name)
env = dict(os.environ, QT_QPA_PLATFORM='offscreen', XDG_RUNTIME_DIR=str(runtime),
XDG_STATE_HOME=tmp, XDG_CACHE_HOME=tmp)
result = subprocess.run(['quickshell', '-p', str(config), '--no-color'], env=env,
capture_output=True, text=True, timeout=23)
logs = result.stdout + result.stderr
print(logs)
assert result.returncode == 0 and 'BLUETOOTH_TEST_PASS: 14 scenarios' in logs, logs
for marker in ['BLUETOOTH_TEST_FAIL', 'Failed to load configuration', 'ReferenceError', 'TypeError', 'Binding loop']:
assert marker not in logs, marker
+21
View File
@@ -0,0 +1,21 @@
#!/usr/bin/env python3
"""Explicit test command, never a production backend mode."""
import json
import sys
import time
mode, action, *args = sys.argv[1:]
if mode == 'stall': time.sleep(10)
if mode == 'malformed':
print('not json', flush=True)
sys.exit(0)
if mode == 'failure':
print(json.dumps({'ok': False, 'error': 'Mock BlueZ NotReady'}), flush=True)
sys.exit(1)
if action == 'status':
print(json.dumps({'ok': True, 'adapterCount': 2}), flush=True)
elif action == 'discover':
print(json.dumps({'ok': True, 'event': 'started'}), flush=True)
time.sleep(10)
else:
print(json.dumps({'ok': True}), flush=True)
+103
View File
@@ -0,0 +1,103 @@
pragma ComponentBehavior: Bound
import QtQuick
import Quickshell
import "."
ShellRoot {
id: test
property var controller: null
property var discovery: null
property var adapter: null
property int scenario: -1
property int step: 0
property int successes: 0
property bool finished: false
readonly property var names: ["status and exact action", "BlueZ error", "malformed response", "watchdog", "invalid action", "close stops own search", "discovery deadline", "foreign search untouched", "disabled adapter", "discovery startup error", "adapter change stops lease", "startup timeout", "close before startup", "missing discovery executable"]
Component { id: controls; BluetoothController { backendCommand: ["python3", Quickshell.shellPath("bluetooth_fake.py"), "success"]; timeoutMs: 2000 } }
Component { id: scans; BluetoothDiscovery { backendCommand: ["python3", Quickshell.shellPath("bluetooth_fake.py"), "success"]; active: true; startTimeoutMs: 1000 } }
Component { id: adapters; QtObject { property bool enabled: true; property bool discovering: false; property string dbusPath: "/org/bluez/hci1" } }
Connections {
target: test.controller
function onSucceeded(action) { test.successes++; }
function onBusyChanged() { if (!test.controller.busy) Qt.callLater(test.advance); }
}
Connections {
target: test.discovery
function onOwnedChanged() { if (test.discovery.owned) Qt.callLater(test.advance); }
function onBusyChanged() { if (!test.discovery.busy) Qt.callLater(test.advance); }
function onStoppingChanged() { if (!test.discovery.stopping) Qt.callLater(test.advance); }
}
function check(value, message) { if (!value) { finished = true; console.error("BLUETOOTH_TEST_FAIL: " + message); Qt.exit(1); throw new Error(message); } }
function complete() { console.log("PASS Bluetooth: " + names[scenario]); Qt.callLater(next); }
function next() {
if (controller) controller.destroy();
if (discovery) discovery.destroy();
if (adapter) adapter.destroy();
controller = null; discovery = null; adapter = null;
scenario++; step = 0; successes = 0;
if (scenario === names.length) { finished = true; console.log("BLUETOOTH_TEST_PASS: 14 scenarios"); Qt.quit(); return; }
if (scenario <= 4) {
controller = controls.createObject(test);
const mode = ["success", "failure", "malformed", "stall", "success"][scenario];
controller.backendCommand = ["python3", Quickshell.shellPath("bluetooth_fake.py"), mode];
if (scenario === 3) controller.timeoutMs = 100;
if (scenario === 4) { check(!controller.start("bad command", ""), "unknown action accepted"); complete(); return; }
check(controller.refresh(), "refresh rejected");
} else {
adapter = adapters.createObject(test);
discovery = scans.createObject(test, {adapter: adapter});
if (scenario === 7) {
adapter.discovering = true;
check(!discovery.start(), "foreign search joined unexpectedly");
discovery.active = false;
check(adapter.discovering, "foreign search stopped"); complete(); return;
}
if (scenario === 8) {
adapter.enabled = false;
check(!discovery.start() && !discovery.busy, "disabled adapter searched"); complete(); return;
}
if (scenario === 9) discovery.backendCommand = ["python3", Quickshell.shellPath("bluetooth_fake.py"), "failure"];
if (scenario === 6) discovery.durationMs = 100;
if (scenario === 11 || scenario === 12) {
discovery.backendCommand = ["python3", Quickshell.shellPath("bluetooth_fake.py"), "stall"];
discovery.startTimeoutMs = 100;
}
if (scenario === 13) { discovery.backendCommand = ["adaptive-nonexistent-executable"]; discovery.startTimeoutMs = 100; }
check(discovery.start(), "discovery rejected");
check(!discovery.start(), "duplicate discovery accepted");
if (scenario === 12) discovery.active = false;
}
}
function advance() {
if (finished) return;
if (scenario <= 4) {
if (!controller || controller.busy) return;
if (scenario === 0) {
if (step === 0) {
check(controller.readiness === "ready" && controller.adapterCount === 2, "status lost");
step = 1;
check(controller.start("connect", "/org/bluez/hci1/dev_AA_BB_CC_DD_EE_FF"), "connect rejected");
check(!controller.refresh(), "duplicate command accepted"); return;
}
check(successes === 1 && controller.error === "", "action failed");
} else if (scenario === 1) check(controller.error.includes("Mock BlueZ NotReady") && controller.readiness === "unavailable", "backend failure lost");
else if (scenario === 2) check(controller.error !== "" && controller.readiness === "unavailable", "invalid response accepted");
else if (scenario === 3) check(controller.timedOut && controller.error !== "", "watchdog failed");
} else {
if (!discovery) return;
if (discovery.owned && step === 0) {
step = 1;
if (scenario === 5) discovery.active = false;
else if (scenario === 10) discovery.adapter = null;
return;
}
if (discovery.busy || discovery.stopping) return;
if (scenario === 9) check(discovery.error.includes("Mock BlueZ NotReady"), "discovery error lost");
else if (scenario === 11 || scenario === 13) check(!discovery.owned && discovery.error !== "", "startup failure not handled");
else check(!discovery.owned && discovery.error === "", "discovery cleanup failed");
}
complete();
}
Component.onCompleted: Qt.callLater(next)
Timer { interval: 18000; running: !test.finished; onTriggered: test.check(false, "harness timeout") }
}
+133
View File
@@ -0,0 +1,133 @@
pragma ComponentBehavior: Bound
import QtQuick
import Quickshell
import Quickshell.Networking
import "."
import "components"
ShellRoot {
id: test
property var device: null
property var network: null
property var controller: null
property var card: null
property int scenario: -1
property int successes: 0
property int secretRequests: 0
property bool finished: false
readonly property var names: ["connect and duplicate prevention", "failure and credentials request", "device removal", "disconnect", "timeout", "unmanaged device", "PSK forwarding", "wrong adapter", "credential field lifecycle"]
Component {
id: devices
QtObject {
property bool connected: false
property bool nmManaged: true
property int type: DeviceType.Wifi
property int state: 0
property int disconnects: 0
function disconnect() { disconnects++; connected = false; }
}
}
Component {
id: networks
QtObject {
property var device: null
property bool connected: false
property int state: 0
property int connects: 0
property string name: "Test network"
property bool known: false
property real signalStrength: 0.8
property int security: WifiSecurityType.Wpa2Psk
property int pskConnects: 0
property string captured: ""
signal connectionFailed(int reason)
function connect() { connects++; }
function connectWithPsk(value) { pskConnects++; captured = value; }
}
}
Component { id: cards; NetworkCard { width: 400; active: true; network: test.network; device: test.device; controller: test.controller } }
Component { id: controllers; NetworkController { timeoutMs: 1000 } }
Connections {
target: test.controller
function onSucceeded(action) { test.successes++; }
function onNeedsSecret(network) { test.secretRequests++; }
function onBusyChanged() { if (test.scenario === 4 && !test.controller.busy) Qt.callLater(test.finishTimeout); }
}
function check(value, message) { if (!value) { finished = true; console.error("NETWORK_TEST_FAIL: " + message); Qt.exit(1); throw new Error(message); } }
function complete() { console.log("PASS network controller: " + names[scenario]); Qt.callLater(next); }
function finishTimeout() {
check(controller.error !== "", "timeout error missing");
check(successes === 0 && device.disconnects === 0, "timeout triggered a mutation or success");
complete();
}
function next() {
if (card) { card.destroy(); card = null; }
if (controller) controller.destroy();
if (network) network.destroy();
if (device) device.destroy();
controller = null; network = null; device = null;
scenario++; successes = 0; secretRequests = 0;
if (scenario === names.length) { finished = true; console.log("NETWORK_TEST_PASS: 9 scenarios"); Qt.quit(); return; }
device = devices.createObject(test);
network = networks.createObject(test, {device: device});
controller = controllers.createObject(test, {device: device});
if (scenario === 0) {
check(controller.requestConnect(network), "connect rejected");
check(controller.busy && network.connects === 1, "connect not sent");
check(!controller.requestConnect(network), "duplicate request accepted");
network.connected = true;
check(!controller.busy && successes === 1, "connected state did not complete request");
} else if (scenario === 1) {
controller.requestConnect(network);
network.connectionFailed(ConnectionFailReason.NoSecrets);
check(!controller.busy && controller.error !== "", "failure lost");
check(secretRequests === 1 && successes === 0, "wrong failure result");
} else if (scenario === 2) {
controller.requestConnect(network);
controller.device = null;
check(!controller.busy && controller.error !== "" && successes === 0, "removed device not handled");
} else if (scenario === 3) {
device.connected = true;
check(controller.requestDisconnect(), "disconnect rejected");
check(device.disconnects === 1 && !controller.busy && successes === 1, "disconnect did not complete");
} else if (scenario === 4) {
controller.timeoutMs = 30;
controller.requestConnect(network);
return;
} else if (scenario === 5) {
device.nmManaged = false;
check(!controller.requestConnect(network) && network.connects === 0, "unmanaged device mutated");
} else if (scenario === 6) {
check(controller.requestConnect(network, "synthetic-test-key"), "PSK request rejected");
check(network.pskConnects === 1 && network.connects === 0 && network.captured === "synthetic-test-key", "PSK not forwarded correctly");
network.connectionFailed(ConnectionFailReason.NoSecrets);
check(!controller.error.includes("synthetic-test-key"), "PSK leaked into error");
} else if (scenario === 7) {
network.device = null;
check(!controller.requestConnect(network) && network.connects === 0, "wrong adapter accepted");
} else if (scenario === 8) {
card = cards.createObject(test);
const password = findItem(card, "networkPassword");
check(password !== null, "credential field not found");
card.credentials = true; password.text = "synthetic-test-key";
check(password.echoMode === TextInput.Password, "password is not masked");
card.active = false;
check(password.text === "" && !card.credentials, "password survived page close");
card.active = true;
controller.requestConnect(network);
network.connectionFailed(ConnectionFailReason.NoSecrets);
check(card.credentials, "credential prompt not opened");
password.text = "synthetic-test-key";
network.connected = true;
check(password.text === "" && !card.credentials, "password survived connection");
}
complete();
}
function findItem(parent, name) {
if (parent.objectName === name) return parent;
for (const child of parent.children || []) { const found = findItem(child, name); if (found) return found; }
return null;
}
Component.onCompleted: Qt.callLater(next)
Timer { interval: 15000; running: !test.finished; onTriggered: test.check(false, "harness timeout") }
}
+69
View File
@@ -0,0 +1,69 @@
pragma ComponentBehavior: Bound
import QtQuick
import Quickshell
import "."
ShellRoot {
id: test
property var instance: null
property int scenario: -1
property int step: 0
property int successes: 0
property bool finished: false
readonly property var names: ["success and duplicate prevention", "denied capability", "backend error", "malformed response", "watchdog", "invalid action", "missing helper"]
Component {
id: factory
PowerController { backendCommand: ["python3", Quickshell.shellPath("power_fake.py"), "success"]; timeoutMs: 3000 }
}
Connections {
target: test.instance
function onBusyChanged() { if (!test.instance.busy) Qt.callLater(test.advance); }
function onSucceeded(action) { test.successes++; }
}
function check(value, message) { if (!value) { finished = true; console.error("POWER_TEST_FAIL: " + message); Qt.exit(1); throw new Error(message); } }
function next() {
if (instance) instance.destroy();
instance = null;
scenario++;
if (scenario === names.length) { finished = true; console.log("POWER_TEST_PASS: 7 scenarios"); Qt.quit(); return; }
step = 0; successes = 0;
instance = factory.createObject(test);
const mode = ["success", "denied", "failure", "malformed", "stall", "success", "success"][scenario];
instance.backendCommand = ["python3", Quickshell.shellPath("power_fake.py"), mode];
if (scenario === 4) instance.timeoutMs = 150;
if (scenario === 5) {
check(!instance.start("bad command"), "invalid action accepted");
check(instance.error !== "", "invalid action error missing");
complete(); return;
}
if (scenario === 6) instance.backendCommand = ["python3", "/nonexistent/adaptive-power.py"];
check(instance.refresh(), "refresh rejected");
}
function complete() { console.log("PASS power controller: " + names[scenario]); Qt.callLater(next); }
function advance() {
if (finished || !instance || instance.busy) return;
if (scenario === 0 || scenario === 2) {
if (step === 0) {
check(instance.available("reboot"), "capability not loaded");
step = 1;
check(instance.start("reboot"), "action rejected");
check(!instance.start("poweroff"), "concurrent action accepted");
return;
}
if (scenario === 0) { check(successes === 1, "success not emitted"); check(instance.error === "", "unexpected error"); }
else { check(successes === 0, "error reported as success"); check(instance.error.includes("Mock authorization denied"), "backend error lost"); }
} else if (scenario === 1) {
check(!instance.available("suspend"), "denied action available");
check(!instance.start("suspend"), "denied action started");
} else if (scenario === 3 || scenario === 6) {
check(instance.capabilityError !== "", "capability error missing");
check(!instance.available("reboot"), "action available after backend failure");
} else if (scenario === 4) {
check(instance.timedOut, "watchdog did not fire");
check(instance.error !== "", "watchdog error missing");
}
complete();
}
Component.onCompleted: Qt.callLater(next)
Timer { interval: 20000; running: !test.finished; onTriggered: test.check(false, "harness timeout") }
}
+26
View File
@@ -0,0 +1,26 @@
// Pure JavaScript policy tests, runnable without a Wayland session or Qt.
const assert = require('node:assert/strict');
const fs = require('node:fs');
const vm = require('node:vm');
const path = require('node:path');
const source = fs.readFileSync(path.join(__dirname, '../services/HardwarePolicy.js'), 'utf8').replace(/^\.pragma library\s*\n/, '');
const ctx = vm.createContext({});
vm.runInContext(source, ctx);
const caps = ctx.networkCapabilities([{type: 2, name: 'enp1s0', connected: true}, {type: 2, name: 'enp2s0', connected: false}], 1, 2);
assert.equal(caps.wifi, false);
assert.equal(caps.wired.length, 2);
assert.equal(ctx.ethernetSummary(caps.wired), 'Ethernet · 1/2');
assert.equal(ctx.networkCapabilities([{type: 1, enabled: false}], 1, 2).wifi, true);
const full = ctx.visibleSettingsSections(true, true, true);
assert.equal(full.map(x => x.id).join(','), 'appearance,audio,network,wallpaper,bluetooth,system');
const reduced = ctx.visibleSettingsSections(false, true, false);
assert.equal(reduced.map(x => x.id).join(','), 'appearance,network,wallpaper,system');
assert.equal(ctx.sectionIndex(reduced, 'bluetooth'), -1);
assert.equal(ctx.pageIndex('network'), 2);
assert.equal(ctx.pageIndex('bluetooth'), 4);
assert.equal(ctx.pageIndex('invalid'), 0);
const battery = ctx.visibleSettingsSections(false, false, false, false, true);
assert.equal(battery.map(x => x.id).join(','), 'appearance,wallpaper,battery,system');
assert.equal(ctx.pageIndex('battery'), 7);
assert.equal(ctx.visibleSettingsSections(false, false, false, false, false).some(x => x.id === 'battery'), false);
console.log('PASS: hardware policy, section visibility, hotplug and stable page IDs');
+17
View File
@@ -0,0 +1,17 @@
const fs = require('fs');
const vm = require('vm');
const assert = require('node:assert/strict');
const path = require('path');
const source = fs.readFileSync(path.join(__dirname, '../services/Policy.js'), 'utf8')
.replace(/^\.pragma.*$/gm, '').replace(/^\.import.*$/gm, '');
const ctx = {WallpaperPolicy: {validate: () => {}}};
vm.createContext(ctx);
vm.runInContext(source, ctx);
function plain(value) { return JSON.parse(JSON.stringify(value)); }
assert.deepEqual(plain(ctx.homePages([], 12)), [[]]);
assert.deepEqual(plain(ctx.homePages(['a','b','c'], 2)), [['a','b'],['c']]);
assert.deepEqual(plain(ctx.moveFavorite(['a','b','c'], 'b', 1)), ['a','c','b']);
assert.deepEqual(plain(ctx.moveFavorite(['a','b','c'], 'a', -1)), ['a','b','c']);
assert.deepEqual(plain(ctx.moveFavorite(['a','b','c'], 'missing', 1)), ['a','b','c']);
assert.throws(() => ctx.homePages(['a'], 0));
console.log('PASS home pages and favorite reordering');
+33
View File
@@ -0,0 +1,33 @@
#!/usr/bin/env python3
"""Run the actual NetworkController with QML fake devices; never instantiate Networking."""
import os
from pathlib import Path
import shutil
import subprocess
import tempfile
root = Path(__file__).resolve().parents[1]
with tempfile.TemporaryDirectory(prefix='adaptive-network-controller-') as tmp:
runtime = Path(tmp, 'runtime')
runtime.mkdir(mode=0o700)
config = Path(tmp, 'config')
config.mkdir()
shutil.copyfile(root / 'tests/fixtures/network.qml', config / 'shell.qml')
shutil.copyfile(root / 'services/NetworkController.qml', config / 'NetworkController.qml')
components = config / 'components'
components.mkdir()
for name in ['NetworkCard.qml', 'ActionButton.qml']:
shutil.copyfile(root / 'components' / name, components / name)
services = config / 'services'
services.mkdir()
(services / 'qmldir').write_text('singleton Theme 1.0 Theme.qml\n')
(services / 'Theme.qml').write_text('pragma Singleton\nimport QtQuick\nQtObject { property color foreground: "white"; property color outline: "gray"; property color background: "black"; property color surface: "#222222"; property color primary: "#d0bcff" }\n')
env = dict(os.environ, QT_QPA_PLATFORM='offscreen', XDG_RUNTIME_DIR=str(runtime),
XDG_STATE_HOME=tmp, XDG_CACHE_HOME=tmp)
result = subprocess.run(['quickshell', '-p', str(config), '--no-color'], env=env,
capture_output=True, text=True, timeout=20)
logs = result.stdout + result.stderr
print(logs)
assert result.returncode == 0 and 'NETWORK_TEST_PASS: 9 scenarios' in logs, logs
for marker in ['NETWORK_TEST_FAIL', 'Failed to load configuration', 'ReferenceError', 'TypeError', 'Binding loop']:
assert marker not in logs, marker
+177
View File
@@ -0,0 +1,177 @@
#!/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
+28
View File
@@ -0,0 +1,28 @@
#!/usr/bin/env python3
"""Run Quickshell's real Process-backed controller exclusively against a fake helper."""
import os
from pathlib import Path
import subprocess
import tempfile
import shutil
fixture = Path(__file__).resolve().parent / 'fixtures/power.qml'
with tempfile.TemporaryDirectory(prefix='adaptive-power-controller-') as tmp:
runtime = Path(tmp, 'runtime')
runtime.mkdir(mode=0o700)
env = dict(os.environ, QT_QPA_PLATFORM='offscreen', XDG_RUNTIME_DIR=str(runtime),
XDG_STATE_HOME=tmp, XDG_CACHE_HOME=tmp)
# Quickshell resolves directory imports inside its config root: stage the exact controller
# source beside the fixture so the offscreen shell has no access to production entrypoints.
config = Path(tmp, 'config')
config.mkdir()
shutil.copyfile(fixture, config / 'shell.qml')
shutil.copyfile(fixture.parents[2] / 'services/PowerController.qml', config / 'PowerController.qml')
shutil.copyfile(fixture.parents[1] / 'power_fake.py', config / 'power_fake.py')
result = subprocess.run(['quickshell', '-p', str(config), '--no-color'], env=env,
capture_output=True, text=True, timeout=25)
logs = result.stdout + result.stderr
print(logs)
assert result.returncode == 0 and 'POWER_TEST_PASS: 7 scenarios' in logs, logs
for marker in ['POWER_TEST_FAIL', 'Failed to load configuration', 'ReferenceError', 'TypeError', 'Binding loop']:
assert marker not in logs, marker
+19
View File
@@ -0,0 +1,19 @@
#!/usr/bin/env python3
"""Explicitly injected by tst_power.qml; never selected by production configuration."""
import json
import sys
import time
mode, action = sys.argv[1:]
if mode == 'stall': time.sleep(5)
if mode == 'malformed':
print('not json')
sys.exit(0)
if action == 'capabilities':
print(json.dumps({'ok': True, 'capabilities': {name: {'state': 'no' if mode == 'denied' else 'yes'}
for name in ['lock', 'logout', 'suspend', 'reboot', 'poweroff']}}))
elif mode == 'failure':
print(json.dumps({'ok': False, 'error': 'Mock authorization denied'}))
sys.exit(1)
else:
print(json.dumps({'ok': True}))
+88
View File
@@ -0,0 +1,88 @@
#!/usr/bin/env python3
"""Wayland integration test. Uses private state and D-Bus, never stops legacy daemons."""
import json
import os
from pathlib import Path
import subprocess
import tempfile
import time
import sys
if os.environ.get("ADAPTIVE_SMOKE_TEST_BUS") != "1":
os.execvpe("dbus-run-session", ["dbus-run-session", "--", sys.executable, __file__], dict(os.environ, ADAPTIVE_SMOKE_TEST_BUS="1"))
ROOT = Path(__file__).resolve().parents[1]
with tempfile.TemporaryDirectory(prefix="adaptive-test-") 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")
with log_path.open("w") as log:
process = subprocess.Popen(["quickshell", "-p", str(ROOT), "--no-color"], env=env,
stdout=log, stderr=subprocess.STDOUT)
def ipc(*args):
return subprocess.run(["quickshell", "ipc", "--pid", str(process.pid),
"call", "shell", *args], env=env, capture_output=True, text=True, timeout=30)
try:
for _ in range(50):
if process.poll() is not None: raise RuntimeError(log_path.read_text())
if ipc("close").returncode == 0: break
time.sleep(.1)
else: raise RuntimeError("IPC did not become ready")
def status():
result = ipc("status")
assert result.returncode == 0, result.stderr
return json.loads(result.stdout)
for page in ["launcher", "settings", "audio", "network", "bluetooth", "wallpapers", "quickSettings", "recent", "power"]:
result = ipc(page)
assert result.returncode == 0, result.stderr
time.sleep(1)
print("PASS", page)
clients = subprocess.run(["hyprctl", "-j", "clients"], env=env, capture_output=True, text=True, check=True)
windows = json.loads(clients.stdout)
assert any(w.get("pid") == process.pid and w.get("title") == "Settings" for w in windows), "Settings must be a managed desktop window"
assert status()["settingsVisible"] is True
capture = os.environ.get("ADAPTIVE_CAPTURE_DIR")
if capture:
assert ipc("audio").returncode == 0
time.sleep(.5)
window = next(w for w in windows if w.get("pid") == process.pid and w.get("title") == "Settings")
x, y = window["at"]
width, height = window["size"]
subprocess.run(["grim", "-g", f"{x},{y} {width}x{height}", str(Path(capture, "adaptive-audio.png"))], env=env, check=True)
print("PASS managed Settings window", status())
for mode in ["phone", "tablet", "desktop"]:
assert ipc("mode", mode).returncode == 0
time.sleep(.3)
assert ipc("theme", "light").returncode == 0
time.sleep(.3)
configs = list(Path(tmp).rglob("preferences.json"))
assert len(configs) == 1, configs
data = json.loads(configs[0].read_text())
assert data["mode"] == "desktop" and data["theme"] == "light", data
data["favorites"] = ["test.desktop"]
configs[0].write_text(json.dumps(data))
time.sleep(.4)
assert status()["favorites"] == ["test.desktop"], status()
configs[0].write_text("{broken json")
time.sleep(.4)
assert status()["preferencesWritable"] is False, status()
ipc("theme", "dark")
time.sleep(.2)
assert configs[0].read_text() == "{broken json", "Corrupt preferences must not be overwritten"
configs[0].write_text(json.dumps(data))
time.sleep(.4)
assert status()["preferencesWritable"] is True and not status()["preferencesError"], status()
print("PASS external preferences, corruption protection and recovery")
subprocess.run(["notify-send", "--app-name=Adaptive Test", "Shell smoke test", "Plain text <b>body</b>"], env=env, check=True)
assert ipc("notifications").returncode == 0
time.sleep(1)
assert ipc("close").returncode == 0
print("PASS modes, persistence, notification delivery")
finally:
process.terminate()
try: process.wait(timeout=3)
except subprocess.TimeoutExpired: process.kill(); process.wait()
logs = log_path.read_text()
print(logs)
for marker in ["Failed to load configuration", "ReferenceError", "TypeError", "Binding loop", "Cannot assign", "is not a type", "Cannot create delegate"]:
assert marker not in logs, marker
@@ -0,0 +1,84 @@
"""Never uses the real system bus: all BlueZ calls are injected."""
import importlib.util
from pathlib import Path
import unittest
import io
from contextlib import redirect_stdout
from unittest.mock import Mock
spec = importlib.util.spec_from_file_location('bluetooth_backend', Path(__file__).resolve().parents[1] / 'backend/bluetooth.py')
backend = importlib.util.module_from_spec(spec)
spec.loader.exec_module(backend)
ADAPTER = '/org/bluez/hci1'
DEVICE = ADAPTER + '/dev_AA_BB_CC_DD_EE_FF'
class BluetoothTests(unittest.TestCase):
def setUp(self):
self.bluez = Mock()
self.factory = Mock(return_value=self.bluez)
def test_status_is_read_only(self):
self.bluez.status.return_value = {'adapterCount': 2}
self.assertEqual(backend.execute('status', factory=self.factory), {'adapterCount': 2})
self.bluez.power.assert_not_called()
self.bluez.connect.assert_not_called()
def test_power_paths_and_values(self):
for action, enabled in [('power-on', True), ('power-off', False)]:
backend.execute(action, ADAPTER, self.factory)
self.bluez.power.assert_called_with(ADAPTER, enabled)
def test_device_actions_route_to_exact_device(self):
for action in ['connect', 'disconnect', 'forget']:
backend.execute(action, DEVICE, self.factory)
getattr(self.bluez, action).assert_called_once_with(DEVICE)
def test_discovery_uses_adapter(self):
backend.execute('discover', ADAPTER, self.factory)
self.bluez.discover.assert_called_once_with(ADAPTER)
def test_invalid_paths_never_create_backend(self):
for path in ['', '/org/bluez/hci1/extra', '/org/bluez/hci1; command', '../hci1', DEVICE]:
with self.assertRaises(ValueError): backend.execute('power-on', path, self.factory)
for path in [ADAPTER, DEVICE + '/extra', '/org/bluez/hci1/dev_wrong']:
with self.assertRaises(ValueError): backend.execute('connect', path, self.factory)
self.factory.assert_not_called()
def test_unknown_action_and_status_arguments_rejected(self):
with self.assertRaises(ValueError): backend.execute('pair', DEVICE, self.factory)
with self.assertRaises(ValueError): backend.execute('status', DEVICE, self.factory)
self.factory.assert_not_called()
def test_errors_propagate_without_success(self):
self.bluez.connect.side_effect = RuntimeError('org.bluez.Error.NotReady')
with self.assertRaisesRegex(RuntimeError, 'NotReady'):
backend.execute('connect', DEVICE, self.factory)
def test_forget_uses_the_owning_adapter(self):
bluez = object.__new__(backend.Bluez)
bluez.call = Mock()
bluez.forget(DEVICE)
bluez.call.assert_called_once_with(ADAPTER, 'org.bluez.Adapter1', 'RemoveDevice', '(o)', (DEVICE,))
class DiscoveryLeaseTests(unittest.TestCase):
def setUp(self):
self.bluez = object.__new__(backend.Bluez)
self.bluez.GLib = Mock()
self.bluez.call = Mock()
def test_started_lease_is_released_by_same_connection(self):
with redirect_stdout(io.StringIO()): self.bluez.discover(ADAPTER)
self.assertEqual(self.bluez.call.call_args_list[0].args, (ADAPTER, 'org.bluez.Adapter1', 'StartDiscovery'))
self.assertEqual(self.bluez.call.call_args_list[1].args, (ADAPTER, 'org.bluez.Adapter1', 'StopDiscovery'))
self.bluez.GLib.MainLoop.return_value.run.assert_called_once()
def test_failed_start_never_sends_stop(self):
self.bluez.call.side_effect = RuntimeError('NotReady')
with self.assertRaisesRegex(RuntimeError, 'NotReady'): self.bluez.discover(ADAPTER)
self.bluez.call.assert_called_once()
self.bluez.GLib.MainLoop.return_value.run.assert_not_called()
if __name__ == '__main__': unittest.main()
+33
View File
@@ -0,0 +1,33 @@
import importlib.util
import pathlib
import unittest
from unittest.mock import patch
PATH = pathlib.Path(__file__).resolve().parents[1] / 'backend' / 'brightness.py'
spec = importlib.util.spec_from_file_location('brightness', PATH)
brightness = importlib.util.module_from_spec(spec)
spec.loader.exec_module(brightness)
class BrightnessTests(unittest.TestCase):
def test_parse_only_backlights(self):
data = 'intel_backlight,backlight,400,800,50%\nled0,leds,1,2,50%\n'
self.assertEqual(brightness.parse_devices(data), [{'name': 'intel_backlight', 'current': 400, 'maximum': 800, 'percent': 50}])
def test_reject_invalid_percent(self):
with self.assertRaises(ValueError):
brightness.main(['brightness.py', 'set', 'intel_backlight', '0'])
def test_reject_unlisted_device(self):
with patch.object(brightness, 'run', return_value='intel_backlight,backlight,50,100,50%'):
with self.assertRaises(ValueError):
brightness.main(['brightness.py', 'set', 'unknown', '40'])
def test_set_uses_argument_vector(self):
with patch.object(brightness, 'run', side_effect=['intel_backlight,backlight,50,100,50%', '', 'intel_backlight,backlight,60,100,60%']) as call:
self.assertEqual(brightness.main(['brightness.py', 'set', 'intel_backlight', '60'])['devices'][0]['percent'], 60)
self.assertEqual(call.call_args_list[1].args[0], ['--device', 'intel_backlight', 'set', '60%'])
if __name__ == '__main__':
unittest.main()
+25
View File
@@ -0,0 +1,25 @@
import importlib.util
from pathlib import Path
from unittest.mock import patch
import unittest
spec = importlib.util.spec_from_file_location('display_preview', Path(__file__).resolve().parents[1] / 'backend/display_preview.py')
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
class PositionTests(unittest.TestCase):
def test_negative_coordinates(self):
self.assertIn(',-1920x0,', module.monitor_rule('DP-1', '1920x1080@60', '-1920x0', '1', 1))
def test_invalid_position(self):
with self.assertRaises(ValueError):
module.monitor_rule('DP-1', 'preferred', 'left', '1')
def test_preview_validates_coordinate_pair(self):
with patch.object(module, 'current', return_value={'name':'DP-1','x':0,'y':0,'width':1920,'height':1080,'refreshRate':60,'scale':1,'transform':0}):
with self.assertRaisesRegex(ValueError, 'вместе'):
module.preview('DP-1', 'preferred', '1', '0', '10')
with self.assertRaisesRegex(ValueError, 'координаты'):
module.preview('DP-1', 'preferred', '1', '0', '999999', '0')
if __name__ == '__main__': unittest.main()
+59
View File
@@ -0,0 +1,59 @@
import importlib.util
from pathlib import Path
import unittest
from unittest.mock import patch
path = Path(__file__).resolve().parents[1] / 'backend' / 'display_preview.py'
spec = importlib.util.spec_from_file_location('display_preview', path)
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
class DisplayPreviewTests(unittest.TestCase):
def test_valid_rule(self):
self.assertEqual(mod.monitor_rule('eDP-1', '1920x1080@60.00', '0x0', '1.25'), 'eDP-1,1920x1080@60.00,0x0,1.25')
def test_reject_injection(self):
for value in ('eDP-1;rm -rf /', 'eDP-1,disable', '../monitor'):
with self.assertRaises(ValueError):
mod.monitor_rule(value, 'preferred', 'auto', '1')
with self.assertRaises(ValueError):
mod.monitor_rule('eDP-1', '1920x1080;bad', 'auto', '1')
def test_original_rule(self):
data = {'name':'eDP-1','width':1920,'height':1080,'refreshRate':60,'x':-1920,'y':0,'scale':1.5}
self.assertEqual(mod.original_rule(data), 'eDP-1,1920x1080@60.00,-1920x0,1.5,transform,0')
def test_transform_and_position(self):
self.assertEqual(mod.monitor_rule('DP-1', 'preferred', '-1200x0', '1.5', 3),
'DP-1,preferred,-1200x0,1.5,transform,3')
with self.assertRaises(ValueError):
mod.monitor_rule('DP-1', 'preferred', 'auto', '1', 8)
with self.assertRaises(ValueError):
mod.monitor_rule('DP-1', 'preferred', 'auto', '1', True)
def test_preview_keeps_position_and_rotation(self):
monitor = {'name':'eDP-1', 'width':1080, 'height':2400, 'refreshRate':60,
'x':-1080, 'y':200, 'scale':1.5, 'transform':1}
with patch.object(mod, 'current', return_value=monitor), \
patch.object(mod, 'state_dir') as directory, \
patch.object(mod, 'run_hypr') as run, \
patch.object(mod.subprocess, 'Popen') as popen:
import tempfile
with tempfile.TemporaryDirectory() as tmp:
directory.return_value = Path(tmp)
popen.return_value.pid = 123
result = mod.preview('eDP-1', 'preferred', '2', '3')
self.assertTrue(result['ok'])
run.assert_called_once_with('eDP-1,preferred,-1080x200,2,transform,3')
def test_unknown_command(self):
with self.assertRaises(ValueError):
mod.main(['delete', 'eDP-1'])
def test_hyprctl_no_shell(self):
with patch.object(mod.subprocess, 'run') as run:
mod.run_hypr('eDP-1,preferred,auto,1')
self.assertEqual(run.call_args.args[0], ['hyprctl','keyword','monitor','eDP-1,preferred,auto,1'])
if __name__ == '__main__':
unittest.main()
+39
View File
@@ -0,0 +1,39 @@
import importlib.util
import pathlib
import unittest
from unittest.mock import patch
PATH = pathlib.Path(__file__).resolve().parents[1] / 'backend' / 'displays.py'
spec = importlib.util.spec_from_file_location('displays', PATH)
displays = importlib.util.module_from_spec(spec)
spec.loader.exec_module(displays)
class DisplayTests(unittest.TestCase):
def test_normalize(self):
monitor = {'name': 'eDP-1', 'width': 1920, 'height': 1080, 'refreshRate': 59.999, 'scale': 1.25, 'focused': True, 'availableModes': ['1920x1080@60.00Hz']}
result = displays.normalize([monitor])[0]
self.assertEqual((result['width'], result['height']), (1920, 1080))
self.assertEqual(result['refreshRate'], 60.0)
self.assertEqual(result['availableModes'], ['1920x1080@60.00Hz'])
def test_invalid_list(self):
with self.assertRaises(ValueError):
displays.normalize({})
def test_missing_name_skipped(self):
self.assertEqual(displays.normalize([{}, None]), [])
def test_read_only_command(self):
with patch.object(displays.subprocess, 'run') as run:
run.return_value.stdout = '[]'
self.assertEqual(displays.main(['list'])['monitors'], [])
self.assertEqual(run.call_args.args[0], ['hyprctl', '-j', 'monitors', 'all'])
def test_mutating_command_rejected(self):
with self.assertRaises(ValueError):
displays.main(['set', 'eDP-1', '1920x1080'])
if __name__ == '__main__':
unittest.main()
+21
View File
@@ -0,0 +1,21 @@
-- Exercise startup selection without executing commands or changing the session.
local profile, notification_profile = arg[1], arg[2]
local original_getenv = os.getenv
os.getenv = function(name)
if name == "ADAPTIVE_SHELL" then return profile end
if name == "ADAPTIVE_NOTIFICATIONS" then return notification_profile end
return original_getenv(name)
end
local commands = {}
hl = {
on = function(event, callback) assert(event == "hyprland.start"); callback() end,
exec_cmd = function(command) commands[command] = true end,
}
dofile("hypr/startup.lua")
dofile("hypr/programs.lua")
assert(commands["hypridle"] and commands["lxpolkit"] and commands["clipse -listen"])
assert(commands["waybar"] == (profile ~= "1" and true or nil))
assert(commands["~/dotfiles/hypr/bin/adaptive-shell start"] == (profile == "1" and true or nil))
assert(commands["swaync"] == ((profile ~= "1" or notification_profile ~= "1") and true or nil))
assert((launcher:find("adaptive-shell", 1, true) ~= nil) == (profile == "1"))
print("PASS startup and command routing", profile, notification_profile)
@@ -0,0 +1,39 @@
import importlib.util
from pathlib import Path
from unittest import TestCase
from unittest.mock import patch
path = Path(__file__).resolve().parents[1] / 'backend' / 'mobile_connections.py'
spec = importlib.util.spec_from_file_location('mobile_connections', path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
UID = '12345678-1234-1234-1234-123456789abc'
class MobileConnectionsTests(TestCase):
@patch.object(module.shutil, 'which', return_value='/usr/bin/nmcli')
def test_create_argument_vector(self, _):
calls = []
def runner(args, **kwargs):
calls.append(args)
return type('R', (), {'returncode': 0, 'stdout': '', 'stderr': ''})()
self.assertTrue(module.manage('create', 'Mobile internet', 'internet', runner)['ok'])
self.assertEqual(calls[0][-9:], ['connection', 'add', 'type', 'gsm', 'con-name', 'Mobile internet', 'apn', 'internet', 'connection.autoconnect', 'no'][-9:])
@patch.object(module.shutil, 'which', return_value='/usr/bin/nmcli')
def test_rejects_injection(self, _):
for apn in ('bad;echo', '--help', 'foo bar', ''):
self.assertFalse(module.manage('create', 'internet', apn)['ok'])
self.assertFalse(module.manage('delete', '--all')['ok'])
@patch.object(module.shutil, 'which', return_value='/usr/bin/nmcli')
def test_only_mobile_uuid_allowed(self, _):
def runner(args, **kwargs):
return type('R', (), {'returncode': 0, 'stdout': UID + ':802-3-ethernet:Wired\n', 'stderr': ''})()
self.assertFalse(module.manage('delete', UID, runner=runner)['ok'])
@patch.object(module.shutil, 'which', return_value='/usr/bin/nmcli')
def test_lists_mobile_only(self, _):
def runner(args, **kwargs):
return type('R', (), {'returncode': 0, 'stdout': UID + ':gsm:Mobile\n' + UID + ':wifi:Wifi\n', 'stderr': ''})()
self.assertEqual(len(module.list_profiles(runner)['profiles']), 1)
+27
View File
@@ -0,0 +1,27 @@
import importlib.util
from pathlib import Path
from unittest import TestCase
from unittest.mock import patch
path = Path(__file__).resolve().parents[1] / 'backend' / 'modem_control.py'
spec = importlib.util.spec_from_file_location('modem_control', path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
class ModemControlTests(TestCase):
def test_rejects_invalid_ids(self):
for value in ('-1', '1;touch /tmp/foo', '../../etc/passwd', '999999'):
self.assertFalse(module.control(value, 'enable')['ok'])
def test_rejects_arbitrary_actions(self):
self.assertFalse(module.control('0', 'reset')['ok'])
@patch.object(module.shutil, 'which', return_value='/usr/bin/mmcli')
def test_uses_argument_vector(self, _):
calls = []
def runner(args, **kwargs):
calls.append(args)
return type('Result', (), {'returncode': 0, 'stderr': ''})()
self.assertTrue(module.control('7', 'disable', runner)['ok'])
self.assertEqual(calls, [['mmcli', '-m', '7', '--disable']])
+29
View File
@@ -0,0 +1,29 @@
import importlib.util
import pathlib
import unittest
MODULE = pathlib.Path(__file__).resolve().parents[1] / 'backend' / 'modems.py'
spec = importlib.util.spec_from_file_location('modems', MODULE)
modems = importlib.util.module_from_spec(spec)
spec.loader.exec_module(modems)
class ModemTests(unittest.TestCase):
def test_empty_inventory(self):
self.assertEqual(modems.modem_paths({'modem-list': []}), [])
def test_reject_invalid_paths(self):
self.assertEqual(modems.modem_paths({'modem-list': ['/tmp/evil', '/org/freedesktop/ModemManager1/Modem/3']}), ['/org/freedesktop/ModemManager1/Modem/3'])
def test_modem_without_sim(self):
item = modems.describe({'modem': {'generic': {'model': 'LTE', 'sim': '--', 'signal-quality': {'value': 55}}}}, '/org/freedesktop/ModemManager1/Modem/2')
self.assertFalse(item['simPresent'])
self.assertEqual(item['signal'], 55)
def test_modem_with_sim(self):
item = modems.describe({'modem': {'generic': {'sim': '/org/freedesktop/ModemManager1/SIM/0'}}}, '/org/freedesktop/ModemManager1/Modem/0')
self.assertTrue(item['simPresent'])
if __name__ == '__main__':
unittest.main()
+164
View File
@@ -0,0 +1,164 @@
"""All mutation tests use injected objects. No real logind or Wayland calls."""
import importlib.util
from pathlib import Path
import subprocess
import unittest
import sys
from unittest.mock import Mock, patch
spec = importlib.util.spec_from_file_location('power_backend', Path(__file__).resolve().parents[1] / 'backend/power.py')
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'backend'))
backend = importlib.util.module_from_spec(spec)
spec.loader.exec_module(backend)
class PowerTests(unittest.TestCase):
def setUp(self):
self.events = []
self.logind = Mock()
self.logind.can.side_effect = lambda action: self.events.append('can:' + action) or 'yes'
self.logind.perform.side_effect = lambda action: self.events.append('perform:' + action)
self.observer = Mock()
self.observer.ensure_locked.side_effect = lambda: self.events.append('locked')
self.observer.close.side_effect = lambda: self.events.append('observer closed')
self.factory = Mock(return_value=self.logind)
self.observer_factory = Mock(return_value=self.observer)
def execute(self, action):
backend.execute(action, logind_factory=self.factory, observer_factory=self.observer_factory)
def test_authorization_is_not_interactive_after_lock(self):
logind = object.__new__(backend.Logind)
logind.call = Mock()
logind.perform('suspend')
logind.call.assert_called_with('Suspend', False)
logind.perform('reboot')
logind.call.assert_called_with('Reboot', True)
def test_suspend_waits_for_lock(self):
self.execute('suspend')
self.assertEqual(self.events, ['can:suspend', 'locked', 'perform:suspend', 'observer closed'])
def test_lock_failure_prevents_suspend(self):
self.observer.ensure_locked.side_effect = RuntimeError('no lock confirmation')
with self.assertRaisesRegex(RuntimeError, 'no lock confirmation'): self.execute('suspend')
self.logind.perform.assert_not_called()
self.observer.close.assert_called_once()
def test_unavailable_protocol_prevents_suspend(self):
self.observer_factory.side_effect = ImportError('no protocol')
with self.assertRaises(ImportError): self.execute('suspend')
self.logind.perform.assert_not_called()
def test_suspend_challenge_never_locks_or_sleeps(self):
self.logind.can.side_effect = None
self.logind.can.return_value = 'challenge'
with self.assertRaisesRegex(RuntimeError, 'before locking'): self.execute('suspend')
self.observer_factory.assert_not_called()
self.logind.perform.assert_not_called()
def test_reboot_challenge_uses_logind(self):
self.logind.can.side_effect = None
self.logind.can.return_value = 'challenge'
self.execute('reboot')
self.logind.perform.assert_called_once_with('reboot')
self.observer_factory.assert_not_called()
def test_denied_actions_never_execute(self):
for state in ['no', 'na', 'unknown']:
self.logind.can.side_effect = None
self.logind.can.return_value = state
with self.assertRaises(RuntimeError): self.execute('poweroff')
self.logind.perform.assert_not_called()
def test_lock_only_never_uses_logind(self):
self.execute('lock')
self.factory.assert_not_called()
self.observer.ensure_locked.assert_called_once()
self.observer.close.assert_called_once()
def test_unknown_action_never_executes(self):
with self.assertRaises(ValueError): self.execute('reboot; command')
self.factory.assert_not_called()
self.observer_factory.assert_not_called()
def test_logout_dispatch_is_fixed_and_session_scoped(self):
for provider, expected in [('lua', ['hyprctl', 'eval', 'hl.dispatch(hl.dsp.exit())']), ('conf', ['hyprctl', 'dispatch', 'exit'])]:
run = Mock()
backend.execute('logout', compositor_query=lambda: {'configProvider': provider}, run=run)
self.assertEqual(run.call_args.args[0], expected)
def test_logout_error_propagates(self):
run = Mock(side_effect=subprocess.TimeoutExpired('hyprctl', 5))
with self.assertRaises(subprocess.TimeoutExpired):
backend.execute('logout', compositor_query=lambda: {'configProvider': 'lua'}, run=run)
@patch.object(backend.shutil, 'which', return_value='/test/hyprlock')
def test_capabilities_are_real_states(self, which):
result = backend.capabilities(self.factory, self.observer_factory, lambda: {})
self.assertEqual(result['lock']['state'], 'yes')
self.assertEqual(result['suspend']['state'], 'yes')
self.logind.perform.assert_not_called()
self.observer.ensure_locked.assert_not_called()
def test_unavailable_backend_never_reports_yes(self):
fail = Mock(side_effect=RuntimeError('unavailable'))
result = backend.capabilities(fail, fail, fail)
self.assertFalse(any(action['state'] == 'yes' for action in result.values()))
from lock_observer import LockObserver
class LockObserverTests(unittest.TestCase):
def setUp(self):
self.observer = object.__new__(LockObserver)
self.observer.locked = False
self.observer.display = Mock()
self.child = Mock()
self.child.poll.return_value = None
def test_existing_lock_is_rechecked(self):
self.observer.locked = True
with patch('lock_observer.subprocess.Popen') as popen:
self.observer.ensure_locked()
self.observer.display.roundtrip.assert_called_once()
popen.assert_not_called()
def test_missing_locker_cannot_confirm_lock(self):
with patch('lock_observer.shutil.which', return_value=None):
with self.assertRaisesRegex(RuntimeError, 'not installed'): self.observer.ensure_locked()
@patch('lock_observer.shutil.which', return_value='/test/hyprlock')
def test_locker_exit_is_not_confirmation(self, which):
self.child.poll.return_value = 1
with patch('lock_observer.subprocess.Popen', return_value=self.child):
with self.assertRaisesRegex(RuntimeError, 'before the compositor'): self.observer.ensure_locked()
@patch('lock_observer.shutil.which', return_value='/test/hyprlock')
def test_lock_timeout_is_not_confirmation(self, which):
with patch('lock_observer.subprocess.Popen', return_value=self.child), patch('lock_observer.time.monotonic', side_effect=[0, 20]):
with self.assertRaisesRegex(RuntimeError, 'Timed out'): self.observer.ensure_locked()
self.child.terminate.assert_not_called()
@patch('lock_observer.shutil.which', return_value='/test/hyprlock')
def test_compositor_event_confirms_lock(self, which):
def ready(*args):
self.observer.locked = True
return ([1], [], [])
with patch('lock_observer.subprocess.Popen', return_value=self.child) as popen, patch('lock_observer.select.select', side_effect=ready):
self.observer.ensure_locked()
self.assertEqual(popen.call_args.args[0], ['/test/hyprlock', '--grace', '0'])
self.observer.display.roundtrip.assert_called_once()
@patch('lock_observer.shutil.which', return_value='/test/hyprlock')
def test_unlock_before_action_is_rejected(self, which):
def ready(*args):
self.observer.locked = True
return ([1], [], [])
self.observer.display.roundtrip.side_effect = lambda: setattr(self.observer, 'locked', False)
with patch('lock_observer.subprocess.Popen', return_value=self.child), patch('lock_observer.select.select', side_effect=ready):
with self.assertRaisesRegex(RuntimeError, 'unlocked'): self.observer.ensure_locked()
if __name__ == '__main__': unittest.main()
+31
View File
@@ -0,0 +1,31 @@
import importlib.util
from pathlib import Path
from types import SimpleNamespace
path = Path(__file__).resolve().parents[1] / 'backend' / 'power_profiles.py'
spec = importlib.util.spec_from_file_location('power_profiles', path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
def test_get():
def runner(args, **kwargs):
assert args == ['powerprofilesctl', 'get']
return SimpleNamespace(returncode=0, stdout='balanced\n', stderr='')
assert module.execute(['get'], runner=runner, which=lambda _: '/bin/powerprofilesctl')['profile'] == 'balanced'
def test_invalid_profile_never_invokes_command():
def runner(*args, **kwargs):
raise AssertionError('must not run')
assert not module.execute(['set', ';reboot'], runner=runner, which=lambda _: '/bin/powerprofilesctl')['ok']
def test_missing_utility():
assert not module.execute(['get'], which=lambda _: None)['ok']
def test_backend_failure():
def runner(args, **kwargs):
return SimpleNamespace(returncode=1, stdout='', stderr='denied')
assert 'denied' in module.execute(['set', 'balanced'], runner=runner, which=lambda _: '/bin/powerprofilesctl')['error']
+24
View File
@@ -0,0 +1,24 @@
import importlib.util
from pathlib import Path
import tempfile
import unittest
spec = importlib.util.spec_from_file_location('system_info', Path(__file__).resolve().parents[1] / 'backend/system_info.py')
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
class SystemInfoTests(unittest.TestCase):
def test_os_release(self):
with tempfile.TemporaryDirectory() as folder:
path = Path(folder) / 'os-release'
path.write_text('PRETTY_NAME="Arch Linux ARM"\nIGNORED=secret\n')
self.assertEqual(module.os_release(path), {'PRETTY_NAME': 'Arch Linux ARM'})
def test_memory(self):
with tempfile.TemporaryDirectory() as folder:
path = Path(folder) / 'meminfo'
path.write_text('MemTotal: 4096000 kB\nMemAvailable: 1024000 kB\n')
self.assertEqual(module.memory_kib(path)['MemTotal'], 4096000)
def test_uptime_invalid(self):
self.assertEqual(module.uptime_seconds('/nonexistent/uptime'), 0)
if __name__ == '__main__': unittest.main()
+51
View File
@@ -0,0 +1,51 @@
import QtQuick
import QtTest
import "../services/HardwarePolicy.js" as Policy
TestCase {
name: "HardwarePolicy"
function test_ethernet_only() {
const devices = [{type: 2, name: "enp3s0", connected: true}, {type: 2, name: "enp4s0", connected: false}];
const caps = Policy.networkCapabilities(devices, 1, 2);
compare(caps.wifi, false);
compare(caps.wired.length, 2);
compare(Policy.ethernetSummary(caps.wired), "Ethernet · 1/2");
}
function test_disabled_wifi_remains_visible() {
const caps = Policy.networkCapabilities([{type: 1, enabled: false}], 1, 2);
compare(caps.wifi, true);
compare(caps.wired.length, 0);
}
function test_hotplug_recomputed() {
const initial = Policy.networkCapabilities([], 1, 2);
const plugged = Policy.networkCapabilities([{type: 2, connected: false}], 1, 2);
compare(initial.hasNetworkDevices, false);
compare(plugged.hasNetworkDevices, true);
compare(Policy.ethernetSummary(plugged.wired), "Ethernet · нет подключения");
}
function test_battery_hotplug() {
const withBattery = Policy.visibleSettingsSections(false, false, false, false, true);
compare(withBattery.map(s => s.id).join(","), "appearance,wallpaper,battery,system");
compare(Policy.pageIndex("battery"), 7);
compare(Policy.visibleSettingsSections(false, false, false, false, false).some(s => s.id === "battery"), false);
}
function test_settings_capabilities() {
const sections = Policy.visibleSettingsSections(false, true, false);
compare(sections.map(s => s.id).join(","), "appearance,network,wallpaper,system");
}
function test_settings_order_and_pages() {
const sections = Policy.visibleSettingsSections(true, true, true);
compare(sections.map(s => s.id).join(","), "appearance,audio,network,wallpaper,bluetooth,system");
compare(Policy.sectionIndex(sections, "bluetooth"), 4);
compare(Policy.pageIndex("bluetooth"), 4);
compare(Policy.pageIndex("network"), 2);
}
function test_hotplug_removes_section_without_reindexing_page() {
const plugged = Policy.visibleSettingsSections(false, true, true);
const unplugged = Policy.visibleSettingsSections(false, true, false);
compare(Policy.sectionIndex(plugged, "bluetooth"), 3);
compare(Policy.sectionIndex(unplugged, "bluetooth"), -1);
compare(Policy.pageIndex("network"), 2);
compare(Policy.pageIndex("missing"), 0);
}
}
+34
View File
@@ -0,0 +1,34 @@
import QtQuick
import QtTest
import "../services/NotificationPolicy.js" as Policy
TestCase {
name: "NotificationPolicy"
function test_timeout() {
compare(Policy.timeoutMs(-1, 0), 3000);
compare(Policy.timeoutMs(-1, 1), 6000);
compare(Policy.timeoutMs(250, 1), 250);
compare(Policy.timeoutMs(0, 1), 0);
compare(Policy.timeoutMs(1, 2), 0);
compare(Policy.timeoutMs(1e20, 1), 2147483647);
}
function entry(key) { return {key: key, appName: "Test", summary: "Summary", body: "Body", state: "received", urgency: 1, time: 100}; }
function test_history_limit_and_replace() {
let history = [];
for (let i = 0; i < 110; i++) history = Policy.upsert(history, entry(String(i)));
compare(history.length, 100);
compare(history[0].key, "109");
const replacement = entry("109"); replacement.summary = "Updated";
history = Policy.upsert(history, replacement);
compare(history.length, 100);
compare(history[0].summary, "Updated");
}
function test_validation() {
compare(Policy.validate({version: 1, entries: [entry("a")]}).length, 1);
for (const invalid of [{version: 2, entries: []}, {version: 1, entries: [entry("a"), entry("a")]}, {version: 1, entries: [{key: "bad"}]}, {version: 1, entries: [Object.assign(entry("a"), {deadline: "soon"})]}]) {
let rejected = false;
try { Policy.validate(invalid); } catch(e) { rejected = true; }
verify(rejected);
}
}
}
+50
View File
@@ -0,0 +1,50 @@
import QtQuick
import QtTest
import "../services/Policy.js" as Policy
TestCase {
name: "AdaptivePolicy"
function verifyExceptionThrown(fn) {
let threw = false;
try { fn(); } catch (e) { threw = true; }
verify(threw, "Invalid preferences must be rejected");
}
function defaults() { return {version: 1, mode: "auto", theme: "dark", touch: false, reducedMotion: false, outputs: {}}; }
function test_modes_data() {
return [
{tag: "narrow desktop", preference: "auto", width: 400, touch: false, expected: "desktop"},
{tag: "phone", preference: "auto", width: 390, touch: true, expected: "phone"},
{tag: "tablet boundary", preference: "auto", width: 600, touch: true, expected: "tablet"},
{tag: "external monitor", preference: "auto", width: 1920, touch: true, expected: "desktop"},
{tag: "manual phone on PC", preference: "phone", width: 3440, touch: false, expected: "phone"}
];
}
function test_modes(data) { compare(Policy.modeFor(data.preference, data.width, data.touch), data.expected); }
function test_valid() { compare(Policy.validate(defaults()).version, 1); }
function test_reject_schema() { const d = defaults(); d.version = 2; verifyExceptionThrown(() => Policy.validate(d)); }
function test_reject_mode() { const d = defaults(); d.mode = "watch"; verifyExceptionThrown(() => Policy.validate(d)); }
function test_reject_output() { const d = defaults(); d.outputs = {"DP-1": "invalid"}; verifyExceptionThrown(() => Policy.validate(d)); }
function test_reject_flags() { const d = defaults(); d.touch = "yes"; verifyExceptionThrown(() => Policy.validate(d)); }
function test_launcher_rank() {
const apps = [{id: "a", name: "Alpha"}, {id: "b", name: "Beta"}, {id: "c", name: "Charlie"}];
compare(Policy.rankApps(apps, ["c"], ["b"]).map(a => a.id).join(","), "c,b,a");
compare(apps[0].id, "a"); // Ranking must not mutate the model.
}
function test_history_bounded() {
const history = Array.from({length: 50}, (_, i) => String(i));
const next = Policy.recordLaunch(history, "new");
compare(next.length, 50);
compare(next[0], "new");
compare(Policy.recordLaunch(next, "1").filter(id => id === "1").length, 1);
}
function test_favorite_toggle() {
compare(Policy.toggleFavorite(["a"], "a").length, 0);
compare(Policy.toggleFavorite([], "a")[0], "a");
}
function test_invalid_application_lists() {
for (const invalid of [["a", "a"], [""], [42], "a"]) {
const data = defaults(); data.favorites = invalid;
verifyExceptionThrown(() => Policy.validate(data));
}
}
}
+41
View File
@@ -0,0 +1,41 @@
import QtQuick
import QtTest
import "../services/WallpaperPolicy.js" as Policy
import "../services/Policy.js" as PreferencesPolicy
TestCase {
name: "WallpaperPolicy"
function test_local_paths() {
const path = "/tmp/обои a '#%?.png";
const url = Policy.localUrl(path);
verify(url.startsWith("file:///tmp/"));
verify(url.includes("%20"));
verify(url.includes("%23"));
compare(Policy.localUrl(url), url);
compare(decodeURIComponent(url.slice(7)), path);
compare(Policy.localUrl(""), "");
}
function test_reject_nonlocal() {
for (const path of ["https://example.com/a.png", "../a.png", "~/a.png", "file://host/a.png", "file:///%GG", "file:///tmp/a%00b", "/tmp/a\u0000b", null]) {
let rejected = false;
try { Policy.localUrl(path); } catch(e) { rejected = true; }
verify(rejected, String(path));
}
}
function test_override_and_disable() {
const wallpapers = {"*": "/tmp/all.png", "DP-1": ""};
compare(Policy.sourceFor(wallpapers, "DP-1"), "");
compare(Policy.sourceFor(wallpapers, "HDMI-A-1"), "file:///tmp/all.png");
compare(Policy.sourceFor(undefined, "DP-1"), "");
}
function test_schema_compatibility() {
const prefs = {version: 1, mode: "auto", theme: "dark", touch: false, reducedMotion: false, outputs: {}};
compare(PreferencesPolicy.validate(prefs).version, 1);
prefs.wallpapers = {"*": "/tmp/a.png"};
compare(PreferencesPolicy.validate(prefs).wallpapers["*"], "/tmp/a.png");
prefs.wallpapers = {"*": "https://example.com/a.png"};
let rejected = false;
try { PreferencesPolicy.validate(prefs); } catch(e) { rejected = true; }
verify(rejected);
}
}
+125
View File
@@ -0,0 +1,125 @@
#!/usr/bin/env python3
"""Static wallpaper integration on desktop; never stops the existing wallpaper daemon."""
import json
import os
from pathlib import Path
import struct
import subprocess
import sys
import tempfile
import time
from urllib.parse import quote
import zlib
if os.environ.get('ADAPTIVE_WALLPAPER_TEST_BUS') != '1':
os.execvpe('dbus-run-session', ['dbus-run-session', '--', sys.executable, __file__],
dict(os.environ, ADAPTIVE_WALLPAPER_TEST_BUS='1'))
ROOT = Path(__file__).resolve().parents[1]
def image(path, color):
def chunk(kind, data):
return struct.pack('!I', len(data)) + kind + data + struct.pack('!I', zlib.crc32(kind + data))
raw = (b'\x00' + bytes(color) * 64) * 64
path.write_bytes(b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('!2I5B', 64, 64, 8, 2, 0, 0, 0))
+ chunk(b'IDAT', zlib.compress(raw)) + chunk(b'IEND', b''))
def url(path): return 'file://' + quote(str(path), safe="/!~*'()")
def wait_for(predicate, description, timeout=10):
end = time.monotonic() + timeout
while time.monotonic() < end:
if predicate(): return
time.sleep(.1)
raise AssertionError(description)
with tempfile.TemporaryDirectory(prefix='adaptive-wallpaper-') as tmp:
tmp = Path(tmp)
first = tmp / "обои a '#%.png"
second = tmp / 'second.png'
image(first, (35, 45, 65))
image(second, (65, 45, 35))
env = dict(os.environ, QT_QPA_PLATFORM='wayland', QT_QUICK_CONTROLS_STYLE='Material',
XDG_STATE_HOME=str(tmp), XDG_CACHE_HOME=str(tmp), ADAPTIVE_NOTIFICATIONS='0')
log_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, text=True, capture_output=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']
except (ValueError, RuntimeError): return False
def stop():
process.terminate()
try: process.wait(timeout=3)
except subprocess.TimeoutExpired: process.kill(); process.wait()
def layers():
result = subprocess.run(['hyprctl', '-j', 'layers'], env=env, capture_output=True, text=True, check=True, timeout=10)
def walk(node):
if isinstance(node, dict):
if node.get('namespace') == 'adaptive-wallpaper' and node.get('pid') == process.pid: yield node
for child in node.values(): yield from walk(child)
elif isinstance(node, list):
for child in node: yield from walk(child)
return list(walk(json.loads(result.stdout)))
try:
process = start()
wait_for(ready, 'shell readiness', 60)
monitors = json.loads(subprocess.run(['hyprctl', '-j', 'monitors'], env=env, capture_output=True, text=True, check=True, timeout=10).stdout)
monitor = next((m for m in monitors if m.get('focused')), monitors[0])['name']
ipc('wallpapers')
assert all(s['state'] == 'disabled' for s in status()['wallpapers'].values())
assert not layers(), 'Unconfigured wallpapers must not map a surface'
ipc('setWallpaper', '*', str(first))
wait_for(lambda: len(status()['wallpapers']) == len(monitors) and all(s['state'] == 'ready' and s['displayed'] == url(first) for s in status()['wallpapers'].values()), 'common wallpaper ready')
wait_for(lambda: len(layers()) == len(monitors), 'background layer on each monitor')
ipc('reload')
time.sleep(.5)
wait_for(ready, 'reload readiness', 60)
wait_for(lambda: len(status()['wallpapers']) == len(monitors) and all(s['state'] == 'ready' and s['displayed'] == url(first) for s in status()['wallpapers'].values()), 'wallpaper ready after QML reload')
print('PASS common wallpaper, special paths, background layers and QML reload', flush=True)
ipc('setWallpaper', monitor, str(second))
wait_for(lambda: status()['wallpapers'][monitor]['displayed'] == url(second), 'per-output override')
assert all(s['displayed'] == url(first) for name, s in status()['wallpapers'].items() if name != monitor)
ipc('setWallpaper', monitor, 'https://example.com/image.png')
assert status()['wallpaperError'], 'Remote source must be rejected'
assert status()['wallpapers'][monitor]['displayed'] == url(second)
ipc('setWallpaper', monitor, str(tmp / 'missing.png'))
wait_for(lambda: status()['wallpapers'][monitor]['state'] == 'error', 'invalid file reported')
assert status()['wallpapers'][monitor]['displayed'] == url(second), 'Keep last good wallpaper'
print('PASS output override, remote rejection and missing-file fallback', flush=True)
ipc('setWallpaper', monitor, '')
wait_for(lambda: status()['wallpapers'][monitor]['state'] == 'disabled', 'override disabled')
wait_for(lambda: len(layers()) == len(monitors) - 1, 'disabled surface removed')
ipc('inheritWallpaper', monitor)
wait_for(lambda: status()['wallpapers'][monitor]['displayed'] == url(first), 'inherit common wallpaper')
ipc('setWallpaper', 'TEST-DISCONNECTED', str(second))
prefs = next(tmp.rglob('preferences.json'))
wait_for(lambda: json.loads(prefs.read_text()).get('wallpapers', {}).get('TEST-DISCONNECTED') == url(second), 'disconnected output preference saved')
stop()
process = start()
wait_for(ready, 'restarted shell readiness', 60)
wait_for(lambda: status()['wallpapers'][monitor]['displayed'] == url(first), 'wallpaper restored')
assert json.loads(prefs.read_text())['wallpapers']['TEST-DISCONNECTED'] == url(second)
ipc('setWallpaper', '*', '')
wait_for(lambda: not layers(), 'all test backgrounds removed')
print('PASS disable, inherit, disconnected preference and restart persistence', flush=True)
finally:
if process and process.poll() is None:
print('Final wallpaper state:', status(), flush=True)
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
+16
View File
@@ -0,0 +1,16 @@
const assert = require('node:assert/strict');
const fs = require('node:fs');
const vm = require('node:vm');
const source = fs.readFileSync(__dirname + '/../services/WindowPolicy.js', 'utf8').replace(/^\.pragma library\s*/m, '');
const ctx = vm.createContext({});
vm.runInContext(source, ctx);
const windows = [{activate(){}}, {activate(){}}, {activate(){}}];
assert.equal(ctx.cycle(windows, -1, 1), windows[0]);
assert.equal(ctx.cycle(windows, 0, 1), windows[1]);
assert.equal(ctx.cycle(windows, 0, -1), windows[2]);
assert.equal(ctx.cycle([], 0, 1), null);
assert.equal(ctx.cycle(windows, 0, 3), null);
assert.equal(ctx.shouldDismissSwipe(0, -90, 300), true);
assert.equal(ctx.shouldDismissSwipe(90, -40, 300), false);
assert.equal(ctx.shouldDismissSwipe(0, 30, 300), false);
console.log('WindowPolicy tests passed');