Files
anode/tests/test_replace.py
T

806 lines
35 KiB
Python
Raw Normal View History

#!/usr/bin/env python3
"""Headless Xvfb tests for ANODE live X11 replacement and fastfetch DE/WM identity."""
import ctypes
import ctypes.util
import json
import os
import shutil
import signal
import subprocess
import sys
import tempfile
import time
ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
BUILD = os.path.join(ROOT, "build")
DWM_BIN = os.path.join(BUILD, "dwm", "dwm")
REPLACE_BIN = os.path.join(ROOT, "scripts", "anode-replace")
libx11_name = ctypes.util.find_library("X11") or "libX11.so.6"
X11 = ctypes.CDLL(libx11_name)
Window = ctypes.c_ulong
Atom = ctypes.c_ulong
Display_p = ctypes.c_void_p
class XWindowAttributes(ctypes.Structure):
_fields_ = [
("x", ctypes.c_int), ("y", ctypes.c_int),
("width", ctypes.c_int), ("height", ctypes.c_int),
("border_width", ctypes.c_int), ("depth", ctypes.c_int),
("visual", ctypes.c_void_p), ("root", Window),
("class", ctypes.c_int), ("bit_gravity", ctypes.c_int),
("win_gravity", ctypes.c_int), ("backing_store", ctypes.c_int),
("backing_planes", ctypes.c_ulong), ("backing_pixel", ctypes.c_ulong),
("save_under", ctypes.c_int), ("colormap", ctypes.c_ulong),
("map_installed", ctypes.c_int), ("map_state", ctypes.c_int),
("all_event_masks", ctypes.c_long), ("your_event_mask", ctypes.c_long),
("do_not_propagate_mask", ctypes.c_long), ("override_redirect", ctypes.c_int),
("screen", ctypes.c_void_p),
]
X11.XOpenDisplay.argtypes = [ctypes.c_char_p]
X11.XOpenDisplay.restype = Display_p
X11.XCloseDisplay.argtypes = [Display_p]
X11.XDefaultRootWindow.argtypes = [Display_p]
X11.XDefaultRootWindow.restype = Window
X11.XDefaultScreen.argtypes = [Display_p]
X11.XDefaultScreen.restype = ctypes.c_int
X11.XInternAtom.argtypes = [Display_p, ctypes.c_char_p, ctypes.c_int]
X11.XInternAtom.restype = Atom
X11.XGetSelectionOwner.argtypes = [Display_p, Atom]
X11.XGetSelectionOwner.restype = Window
X11.XGetWindowProperty.argtypes = [
Display_p, Window, Atom, ctypes.c_long, ctypes.c_long, ctypes.c_int, Atom,
ctypes.POINTER(Atom), ctypes.POINTER(ctypes.c_int),
ctypes.POINTER(ctypes.c_ulong), ctypes.POINTER(ctypes.c_ulong),
ctypes.POINTER(ctypes.POINTER(ctypes.c_ubyte)),
]
X11.XGetWindowProperty.restype = ctypes.c_int
X11.XFree.argtypes = [ctypes.c_void_p]
X11.XFetchName.argtypes = [Display_p, Window, ctypes.POINTER(ctypes.c_char_p)]
X11.XFetchName.restype = ctypes.c_int
X11.XCreateSimpleWindow.argtypes = [
Display_p, Window, ctypes.c_int, ctypes.c_int, ctypes.c_uint, ctypes.c_uint,
ctypes.c_uint, ctypes.c_ulong, ctypes.c_ulong,
]
X11.XCreateSimpleWindow.restype = Window
X11.XMapWindow.argtypes = [Display_p, Window]
X11.XDestroyWindow.argtypes = [Display_p, Window]
X11.XGetWindowAttributes.argtypes = [Display_p, Window, ctypes.POINTER(XWindowAttributes)]
X11.XGetWindowAttributes.restype = ctypes.c_int
X11.XSync.argtypes = [Display_p, ctypes.c_int]
def pick_display():
for d in range(70, 120):
if not os.path.exists(f"/tmp/.X{d}-lock") and not os.path.exists(f"/tmp/.X11-unix/X{d}"):
return f":{d}"
return ":95"
def wait_until(pred, timeout=6.0, interval=0.05):
end = time.monotonic() + timeout
while time.monotonic() < end:
res = pred()
if res:
return res
time.sleep(interval)
return None
def terminate(proc):
if proc and proc.poll() is None:
proc.terminate()
try:
proc.wait(timeout=3)
except subprocess.TimeoutExpired:
proc.kill()
proc.wait(timeout=2)
def get_win_prop_ulong(dpy, win, atom_name):
atom = X11.XInternAtom(dpy, atom_name.encode(), 0)
da = Atom()
di = ctypes.c_int()
n = ctypes.c_ulong()
dl = ctypes.c_ulong()
prop = ctypes.POINTER(ctypes.c_ubyte)()
rc = X11.XGetWindowProperty(
dpy, win, atom, 0, 1, 0, 0,
ctypes.byref(da), ctypes.byref(di), ctypes.byref(n), ctypes.byref(dl), ctypes.byref(prop),
)
val = None
if rc == 0 and prop and di.value == 32 and n.value >= 1:
val = int(ctypes.cast(prop, ctypes.POINTER(ctypes.c_ulong))[0])
if prop:
X11.XFree(prop)
return val
def get_win_prop_str(dpy, win, atom_name):
atom = X11.XInternAtom(dpy, atom_name.encode(), 0)
da = Atom()
di = ctypes.c_int()
n = ctypes.c_ulong()
dl = ctypes.c_ulong()
prop = ctypes.POINTER(ctypes.c_ubyte)()
rc = X11.XGetWindowProperty(
dpy, win, atom, 0, 256, 0, 0,
ctypes.byref(da), ctypes.byref(di), ctypes.byref(n), ctypes.byref(dl), ctypes.byref(prop),
)
out = None
if rc == 0 and prop and di.value == 8 and n.value > 0:
out = bytes(prop[i] for i in range(n.value)).decode("utf-8", errors="ignore").rstrip("\x00")
if prop:
X11.XFree(prop)
return out
def make_env(tmp, disp):
home = os.path.join(tmp, "home")
xdg_home = os.path.join(home, ".config")
# Provide an isolated bin dir with anode binaries but without long-lived daemons interfering
bin_dir = os.path.join(tmp, "bin")
os.makedirs(xdg_home, exist_ok=True)
os.makedirs(bin_dir, exist_ok=True)
os.symlink(DWM_BIN, os.path.join(bin_dir, "dwm"))
os.symlink(os.path.join(ROOT, "scripts", "anode-session"), os.path.join(bin_dir, "anode-session"))
os.symlink(os.path.join(ROOT, "scripts", "anode-replace"), os.path.join(bin_dir, "anode-replace"))
os.symlink(os.path.join(ROOT, "scripts", "anode-apply-scale"), os.path.join(bin_dir, "anode-apply-scale"))
os.symlink(os.path.join(ROOT, "scripts", "anode-apply-theme"), os.path.join(bin_dir, "anode-apply-theme"))
env = dict(os.environ)
env["DISPLAY"] = disp
env["HOME"] = home
env["XDG_CONFIG_HOME"] = xdg_home
env["ANODE_PREFIX"] = ROOT
env["ANODE_NO_SIGNAL"] = "1"
env["ANODE_NO_DBUS"] = "1"
env["PATH"] = bin_dir + ":" + env.get("PATH", "/usr/bin:/bin")
for k in (
"WAYLAND_DISPLAY", "SWAYSOCK", "HYPRLAND_INSTANCE_SIGNATURE", "I3SOCK",
"KDE_FULL_SESSION", "GNOME_DESKTOP_SESSION_ID",
):
env.pop(k, None)
return env
def kill_pid_and_wait(pid):
if not pid or pid <= 1:
return
try:
os.kill(pid, signal.SIGTERM)
except ProcessLookupError:
return
for _ in range(30):
try:
os.kill(pid, 0)
time.sleep(0.05)
except ProcessLookupError:
return
try:
os.kill(pid, signal.SIGKILL)
except ProcessLookupError:
pass
def test_fastfetch_identity():
disp = pick_display()
with tempfile.TemporaryDirectory() as tmp:
env = make_env(tmp, disp)
env["XDG_CURRENT_DESKTOP"] = "ANODE"
env["XDG_SESSION_DESKTOP"] = "anode"
env["DESKTOP_SESSION"] = "anode"
xvfb = subprocess.Popen(
["Xvfb", disp, "-screen", "0", "1280x720x24", "-nolisten", "tcp"],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
)
dwm = None
dpy = None
try:
dpy = wait_until(lambda: X11.XOpenDisplay(disp.encode()), timeout=5.0)
assert dpy, f"Xvfb failed on {disp}"
root = X11.XDefaultRootWindow(dpy)
scr = X11.XDefaultScreen(dpy)
wm_sel = X11.XInternAtom(dpy, f"WM_S{scr}".encode(), 0)
dwm = subprocess.Popen([DWM_BIN], env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
wmcheck = wait_until(lambda: get_win_prop_ulong(dpy, root, "_NET_SUPPORTING_WM_CHECK"), timeout=5.0)
assert wmcheck, "dwm did not publish _NET_SUPPORTING_WM_CHECK"
assert get_win_prop_str(dpy, wmcheck, "_NET_WM_NAME") == "ANODE WM"
assert get_win_prop_ulong(dpy, wmcheck, "_NET_WM_PID") == dwm.pid
assert X11.XGetSelectionOwner(dpy, wm_sel) == wmcheck
nm = ctypes.c_char_p()
assert X11.XFetchName(dpy, wmcheck, ctypes.byref(nm)) and nm.value == b"ANODE WM"
X11.XFree(nm)
if shutil.which("fastfetch"):
r = subprocess.run(
["fastfetch", "--format", "json", "--structure", "DE:WM"],
env=env, capture_output=True, text=True, check=True,
)
data = json.loads(r.stdout)
mods = {item["type"]: item.get("result", {}) for item in data}
assert mods.get("DE", {}).get("prettyName") == "ANODE", f"unexpected DE: {data}"
assert mods.get("WM", {}).get("prettyName") == "ANODE WM", f"unexpected WM: {data}"
finally:
terminate(dwm)
if dpy:
X11.XCloseDisplay(dpy)
terminate(xvfb)
def test_icccm_replace_and_client_preservation():
disp = pick_display()
with tempfile.TemporaryDirectory() as tmp:
env = make_env(tmp, disp)
env["XDG_CURRENT_DESKTOP"] = "XFCE"
env["KDE_FULL_SESSION"] = "true"
xvfb = subprocess.Popen(
["Xvfb", disp, "-screen", "0", "1280x720x24", "-nolisten", "tcp"],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
)
dwm1 = None
dpy = None
new_pid = None
try:
dpy = wait_until(lambda: X11.XOpenDisplay(disp.encode()), timeout=5.0)
assert dpy
root = X11.XDefaultRootWindow(dpy)
dwm1 = subprocess.Popen([DWM_BIN], env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
wm1 = wait_until(lambda: get_win_prop_ulong(dpy, root, "_NET_SUPPORTING_WM_CHECK"), timeout=5.0)
assert wm1
client = X11.XCreateSimpleWindow(dpy, root, 40, 40, 300, 200, 0, 0, 0xffffff)
X11.XMapWindow(dpy, client)
X11.XSync(dpy, 0)
dry = subprocess.run([REPLACE_BIN, "--dry-run"], env=env, capture_output=True, text=True)
assert dry.returncode == 0, dry.stderr
assert "ANODE WM" in dry.stdout
rep = subprocess.run(
[REPLACE_BIN, "--no-autostart", "--keep-panels"],
env=env, capture_output=True, text=True,
)
assert rep.returncode == 0, f"anode-replace failed: stdout={rep.stdout} stderr={rep.stderr}"
assert "DE: ANODE, WM: ANODE WM" in rep.stdout
# Original dwm must exit cleanly via SelectionClear (status 75)
assert wait_until(lambda: dwm1.poll() is not None, timeout=5.0), "old dwm did not exit on SelectionClear"
assert dwm1.returncode == 75, f"old dwm exited with {dwm1.returncode}, expected 75"
wm2 = get_win_prop_ulong(dpy, root, "_NET_SUPPORTING_WM_CHECK")
assert wm2 and wm2 != wm1, f"expected new _NET_SUPPORTING_WM_CHECK window (wm1={wm1}, wm2={wm2})"
assert get_win_prop_str(dpy, wm2, "_NET_WM_NAME") == "ANODE WM"
new_pid = get_win_prop_ulong(dpy, wm2, "_NET_WM_PID")
assert new_pid and new_pid != dwm1.pid
# Mapped client window must survive replacement
attr = XWindowAttributes()
assert X11.XGetWindowAttributes(dpy, client, ctypes.byref(attr)) != 0
X11.XDestroyWindow(dpy, client)
finally:
terminate(dwm1)
kill_pid_and_wait(new_pid)
if dpy:
X11.XCloseDisplay(dpy)
terminate(xvfb)
def test_non_icccm_wm_fallback_replace():
disp = pick_display()
with tempfile.TemporaryDirectory() as tmp:
env = make_env(tmp, disp)
xvfb = subprocess.Popen(
["Xvfb", disp, "-screen", "0", "1280x720x24", "-nolisten", "tcp"],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
)
mock_wm = None
dpy = None
new_pid = None
mock_code = (
"import ctypes, ctypes.util, os, signal, time\n"
"X11 = ctypes.CDLL(ctypes.util.find_library('X11') or 'libX11.so.6')\n"
"X11.XOpenDisplay.restype = ctypes.c_void_p\n"
"X11.XDefaultRootWindow.argtypes = [ctypes.c_void_p]\n"
"X11.XDefaultRootWindow.restype = ctypes.c_ulong\n"
"X11.XSelectInput.argtypes = [ctypes.c_void_p, ctypes.c_ulong, ctypes.c_long]\n"
"X11.XCreateSimpleWindow.argtypes = [ctypes.c_void_p, ctypes.c_ulong, ctypes.c_int, ctypes.c_int, ctypes.c_uint, ctypes.c_uint, ctypes.c_uint, ctypes.c_ulong, ctypes.c_ulong]\n"
"X11.XCreateSimpleWindow.restype = ctypes.c_ulong\n"
"X11.XInternAtom.argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_int]\n"
"X11.XInternAtom.restype = ctypes.c_ulong\n"
"X11.XChangeProperty.argtypes = [ctypes.c_void_p, ctypes.c_ulong, ctypes.c_ulong, ctypes.c_ulong, ctypes.c_int, ctypes.c_int, ctypes.c_void_p, ctypes.c_int]\n"
"X11.XSync.argtypes = [ctypes.c_void_p, ctypes.c_int]\n"
"dpy = X11.XOpenDisplay(None)\n"
"root = X11.XDefaultRootWindow(dpy)\n"
"X11.XSelectInput(dpy, root, 1 << 20)\n"
"w = X11.XCreateSimpleWindow(dpy, root, 0, 0, 1, 1, 0, 0, 0)\n"
"a_chk = X11.XInternAtom(dpy, b'_NET_SUPPORTING_WM_CHECK', 0)\n"
"a_nm = X11.XInternAtom(dpy, b'_NET_WM_NAME', 0)\n"
"a_pid = X11.XInternAtom(dpy, b'_NET_WM_PID', 0)\n"
"a_utf = X11.XInternAtom(dpy, b'UTF8_STRING', 0)\n"
"a_win = X11.XInternAtom(dpy, b'WINDOW', 0)\n"
"a_card = X11.XInternAtom(dpy, b'CARDINAL', 0)\n"
"wv = ctypes.c_ulong(w)\n"
"pv = ctypes.c_ulong(os.getpid())\n"
"X11.XChangeProperty(dpy, w, a_chk, a_win, 32, 0, ctypes.byref(wv), 1)\n"
"X11.XChangeProperty(dpy, w, a_nm, a_utf, 8, 0, b'LegacyWM', 8)\n"
"X11.XChangeProperty(dpy, w, a_pid, a_card, 32, 0, ctypes.byref(pv), 1)\n"
"X11.XChangeProperty(dpy, root, a_chk, a_win, 32, 0, ctypes.byref(wv), 1)\n"
"X11.XSync(dpy, 0)\n"
"signal.signal(signal.SIGTERM, lambda s, f: os._exit(0))\n"
"while True: time.sleep(0.2)\n"
)
try:
dpy = wait_until(lambda: X11.XOpenDisplay(disp.encode()), timeout=5.0)
assert dpy
root = X11.XDefaultRootWindow(dpy)
mock_wm = subprocess.Popen([sys.executable, "-c", mock_code], env=env)
wm1 = wait_until(lambda: get_win_prop_ulong(dpy, root, "_NET_SUPPORTING_WM_CHECK"), timeout=5.0)
assert wm1
assert get_win_prop_str(dpy, wm1, "_NET_WM_NAME") == "LegacyWM"
rep = subprocess.run(
[REPLACE_BIN, "--no-autostart", "--keep-panels"],
env=env, capture_output=True, text=True,
)
assert rep.returncode == 0, f"fallback replace failed: stdout={rep.stdout} stderr={rep.stderr}"
assert wait_until(lambda: mock_wm.poll() is not None, timeout=3.0), "legacy WM was not stopped"
wm2 = get_win_prop_ulong(dpy, root, "_NET_SUPPORTING_WM_CHECK")
assert wm2 and wm2 != wm1
assert get_win_prop_str(dpy, wm2, "_NET_WM_NAME") == "ANODE WM"
new_pid = get_win_prop_ulong(dpy, wm2, "_NET_WM_PID")
finally:
terminate(mock_wm)
kill_pid_and_wait(new_pid)
if dpy:
X11.XCloseDisplay(dpy)
terminate(xvfb)
def test_anode_session_holds_open_on_replace():
disp = pick_display()
with tempfile.TemporaryDirectory() as tmp:
env = make_env(tmp, disp)
env["XDG_CURRENT_DESKTOP"] = "ANODE"
env["XDG_SESSION_DESKTOP"] = "anode"
env["DESKTOP_SESSION"] = "anode"
xvfb = subprocess.Popen(
["Xvfb", disp, "-screen", "0", "1280x720x24", "-nolisten", "tcp"],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
)
sess1 = None
dpy = None
new_pid = None
try:
dpy = wait_until(lambda: X11.XOpenDisplay(disp.encode()), timeout=5.0)
assert dpy
root = X11.XDefaultRootWindow(dpy)
sess1 = subprocess.Popen(
[os.path.join(tmp, "bin", "anode-session"), "--no-autostart"],
env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
)
wm1 = wait_until(lambda: get_win_prop_ulong(dpy, root, "_NET_SUPPORTING_WM_CHECK"), timeout=5.0)
assert wm1
assert get_win_prop_str(dpy, wm1, "_NET_WM_NAME") == "ANODE WM"
rep = subprocess.run(
[REPLACE_BIN, "--no-autostart", "--keep-panels"],
env=env, capture_output=True, text=True,
)
assert rep.returncode == 0, f"replace inside anode-session failed: {rep.stderr}"
wm2 = wait_until(
lambda: (lambda w: w if w and w != wm1 else None)(get_win_prop_ulong(dpy, root, "_NET_SUPPORTING_WM_CHECK")),
timeout=5.0,
)
assert wm2
new_pid = get_win_prop_ulong(dpy, wm2, "_NET_WM_PID")
assert new_pid
# Original anode-session must stay alive after its dwm yields with status 75
time.sleep(0.8)
assert sess1.poll() is None, f"anode-session exited prematurely on replacement ({sess1.returncode})"
# Once the replacement WM exits, the original session holder should also exit cleanly
kill_pid_and_wait(new_pid)
new_pid = None
assert wait_until(lambda: sess1.poll() is not None, timeout=5.0), "anode-session did not exit after replacement WM died"
assert sess1.returncode == 0
finally:
terminate(sess1)
kill_pid_and_wait(new_pid)
if dpy:
X11.XCloseDisplay(dpy)
terminate(xvfb)
def compile_x11_flags():
try:
r = subprocess.run(
["pkg-config", "--cflags", "--libs", "x11"],
capture_output=True, text=True, check=True,
)
return r.stdout.split()
except Exception:
return ["-lX11"]
def test_dm_session_leader_guard():
disp = pick_display()
cc = os.environ.get("CC", "cc")
with tempfile.TemporaryDirectory() as tmp:
env = make_env(tmp, disp)
dm_bin = os.path.join(tmp, "bin", "lightdm")
wm_bin = os.path.join(tmp, "bin", "mockwm_tst")
dm_c = os.path.join(tmp, "lightdm.c")
with open(dm_c, "w", encoding="utf-8") as f:
f.write(
"#include <sys/wait.h>\n"
"#include <unistd.h>\n"
"int main(int argc, char **argv) {\n"
" if (argc < 2) return 1;\n"
" pid_t p = fork();\n"
" if (p == 0) { execvp(argv[1], argv + 1); _exit(127); }\n"
" int st = 0;\n"
" waitpid(p, &st, 0);\n"
" return WIFEXITED(st) ? WEXITSTATUS(st) : 1;\n"
"}\n"
)
subprocess.run([cc, "-O2", dm_c, "-o", dm_bin], check=True)
wm_c = os.path.join(tmp, "mockwm_tst.c")
with open(wm_c, "w", encoding="utf-8") as f:
f.write(
"#define _POSIX_C_SOURCE 200809L\n"
"#include <signal.h>\n"
"#include <string.h>\n"
"#include <time.h>\n"
"#include <unistd.h>\n"
"#include <X11/Xatom.h>\n"
"#include <X11/Xlib.h>\n"
"static volatile sig_atomic_t alive = 1;\n"
"static void stop_sig(int s) { (void)s; alive = 0; }\n"
"int main(void) {\n"
" signal(SIGTERM, stop_sig);\n"
" Display *d = XOpenDisplay(NULL);\n"
" if (!d) return 1;\n"
" Window root = DefaultRootWindow(d);\n"
" XSelectInput(d, root, SubstructureRedirectMask);\n"
" Window w = XCreateSimpleWindow(d, root, 0, 0, 1, 1, 0, 0, 0);\n"
" Atom ac = XInternAtom(d, \"_NET_SUPPORTING_WM_CHECK\", False);\n"
" Atom an = XInternAtom(d, \"_NET_WM_NAME\", False);\n"
" Atom au = XInternAtom(d, \"UTF8_STRING\", False);\n"
" XChangeProperty(d, w, ac, XA_WINDOW, 32, PropModeReplace, (unsigned char *)&w, 1);\n"
" XChangeProperty(d, w, an, au, 8, PropModeReplace, (unsigned char *)\"mockwm_tst\", 10);\n"
" XChangeProperty(d, root, ac, XA_WINDOW, 32, PropModeReplace, (unsigned char *)&w, 1);\n"
" XSync(d, False);\n"
" while (alive) { struct timespec ts = {0, 100000000L}; nanosleep(&ts, NULL); }\n"
" XDestroyWindow(d, w);\n"
" XCloseDisplay(d);\n"
" return 0;\n"
"}\n"
)
subprocess.run([cc, "-O2", wm_c, "-o", wm_bin] + compile_x11_flags(), check=True)
xvfb = subprocess.Popen(
["Xvfb", disp, "-screen", "0", "1280x720x24", "-nolisten", "tcp"],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
)
dm_proc = None
dpy = None
new_pid = None
try:
dpy = wait_until(lambda: X11.XOpenDisplay(disp.encode()), timeout=5.0)
assert dpy
root = X11.XDefaultRootWindow(dpy)
dm_proc = subprocess.Popen([dm_bin, wm_bin], env=env)
wm1 = wait_until(lambda: get_win_prop_ulong(dpy, root, "_NET_SUPPORTING_WM_CHECK"), timeout=5.0)
assert wm1
assert get_win_prop_str(dpy, wm1, "_NET_WM_NAME") == "mockwm_tst"
assert get_win_prop_ulong(dpy, wm1, "_NET_WM_PID") is None
dry = subprocess.run([REPLACE_BIN, "--dry-run"], env=env, capture_output=True, text=True)
assert dry.returncode == 0
assert "lightdm" in dry.stdout
assert "Warning:" in dry.stdout
blocked = subprocess.run(
[REPLACE_BIN, "--no-autostart", "--keep-panels"],
env=env, capture_output=True, text=True,
)
assert blocked.returncode != 0, "expected DM session-leader guard to refuse without --force"
assert "lightdm" in blocked.stderr
assert "--switch-session" in blocked.stderr
assert "--force" in blocked.stderr
assert dm_proc.poll() is None, "blocked replace must leave mock DM/WM running"
forced = subprocess.run(
[REPLACE_BIN, "--force", "--no-autostart", "--keep-panels"],
env=env, capture_output=True, text=True,
)
assert forced.returncode == 0, f"--force failed: stdout={forced.stdout} stderr={forced.stderr}"
wm2 = get_win_prop_ulong(dpy, root, "_NET_SUPPORTING_WM_CHECK")
assert wm2 and wm2 != wm1
assert get_win_prop_str(dpy, wm2, "_NET_WM_NAME") == "ANODE WM"
new_pid = get_win_prop_ulong(dpy, wm2, "_NET_WM_PID")
finally:
terminate(dm_proc)
kill_pid_and_wait(new_pid)
if dpy:
X11.XCloseDisplay(dpy)
terminate(xvfb)
def test_switch_session_xprofile_handoff():
import pwd
disp = pick_display()
cc = os.environ.get("CC", "cc")
cur_user = os.environ.get("USER") or pwd.getpwuid(os.getuid()).pw_name
with tempfile.TemporaryDirectory() as tmp:
env = make_env(tmp, disp)
xdg_cache = os.path.join(tmp, "cache")
env["XDG_CACHE_HOME"] = xdg_cache
dm_bin = os.path.join(tmp, "bin", "lightdm")
wm_bin = os.path.join(tmp, "bin", "mockwm_tst")
# Stub dm-tool reporting current user already has an active LightDM session
dm_tool_stub = os.path.join(tmp, "bin", "dm-tool")
with open(dm_tool_stub, "w", encoding="utf-8") as f:
f.write(
f"#!/bin/sh\n"
f"if [ \"${{1:-}}\" = \"list-seats\" ]; then\n"
f" printf \"Seat0\\n CanSwitch=true\\n Session0\\n UserName='%s'\\n\" '{cur_user}'\n"
f" exit 0\n"
f"fi\n"
f"exit 0\n"
)
os.chmod(dm_tool_stub, 0o755)
dm_c = os.path.join(tmp, "lightdm.c")
with open(dm_c, "w", encoding="utf-8") as f:
f.write(
"#include <sys/wait.h>\n"
"#include <unistd.h>\n"
"int main(int argc, char **argv) {\n"
" if (argc < 2) return 1;\n"
" pid_t p = fork();\n"
" if (p == 0) { execvp(argv[1], argv + 1); _exit(127); }\n"
" int st = 0;\n"
" waitpid(p, &st, 0);\n"
" return WIFEXITED(st) ? WEXITSTATUS(st) : 1;\n"
"}\n"
)
subprocess.run([cc, "-O2", dm_c, "-o", dm_bin], check=True)
wm_c = os.path.join(tmp, "mockwm_tst.c")
with open(wm_c, "w", encoding="utf-8") as f:
f.write(
"#define _POSIX_C_SOURCE 200809L\n"
"#include <signal.h>\n"
"#include <time.h>\n"
"#include <unistd.h>\n"
"#include <X11/Xatom.h>\n"
"#include <X11/Xlib.h>\n"
"static volatile sig_atomic_t alive = 1;\n"
"static void stop_sig(int s) { (void)s; alive = 0; }\n"
"int main(void) {\n"
" signal(SIGTERM, stop_sig);\n"
" Display *d = XOpenDisplay(NULL);\n"
" if (!d) return 1;\n"
" Window root = DefaultRootWindow(d);\n"
" XSelectInput(d, root, SubstructureRedirectMask);\n"
" Window w = XCreateSimpleWindow(d, root, 0, 0, 1, 1, 0, 0, 0);\n"
" Atom ac = XInternAtom(d, \"_NET_SUPPORTING_WM_CHECK\", False);\n"
" Atom an = XInternAtom(d, \"_NET_WM_NAME\", False);\n"
" Atom au = XInternAtom(d, \"UTF8_STRING\", False);\n"
" XChangeProperty(d, w, ac, XA_WINDOW, 32, PropModeReplace, (unsigned char *)&w, 1);\n"
" XChangeProperty(d, w, an, au, 8, PropModeReplace, (unsigned char *)\"mockwm_tst\", 10);\n"
" XChangeProperty(d, root, ac, XA_WINDOW, 32, PropModeReplace, (unsigned char *)&w, 1);\n"
" XSync(d, False);\n"
" while (alive) { struct timespec ts = {0, 100000000L}; nanosleep(&ts, NULL); }\n"
" XDestroyWindow(d, w);\n"
" XCloseDisplay(d);\n"
" return 0;\n"
"}\n"
)
subprocess.run([cc, "-O2", wm_c, "-o", wm_bin] + compile_x11_flags(), check=True)
xprofile = os.path.join(env["HOME"], ".xprofile")
# Intentionally omit trailing newline to verify safe hook append
with open(xprofile, "w", encoding="utf-8") as f:
f.write("export USER_VAR=kept")
xvfb = subprocess.Popen(
["Xvfb", disp, "-screen", "0", "1280x720x24", "-nolisten", "tcp"],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
)
dm_proc = None
dpy = None
switch_file = os.path.join(xdg_cache, "anode", "switch-once")
try:
dpy = wait_until(lambda: X11.XOpenDisplay(disp.encode()), timeout=5.0)
assert dpy
root = X11.XDefaultRootWindow(dpy)
dm_proc = subprocess.Popen([dm_bin, wm_bin], env=env)
assert wait_until(lambda: get_win_prop_ulong(dpy, root, "_NET_SUPPORTING_WM_CHECK"), timeout=5.0)
dry = subprocess.run(
[REPLACE_BIN, "--switch-session", "--profile", "work", "--dry-run"],
env=env, capture_output=True, text=True,
)
assert dry.returncode == 0, dry.stderr
assert ".xprofile" in dry.stdout and "switch-once" in dry.stdout
assert not os.path.exists(switch_file), "--dry-run must not write switch-once"
with open(xprofile, "r", encoding="utf-8") as f:
assert f.read() == "export USER_VAR=kept"
sw = subprocess.run(
[REPLACE_BIN, "--switch-session", "--profile", "work"],
env=env, capture_output=True, text=True,
)
assert sw.returncode == 0, f"--switch-session failed: {sw.stderr}"
assert wait_until(lambda: dm_proc.poll() is not None, timeout=4.0), "WM did not exit for session switch"
assert os.path.exists(switch_file), "switch-once sentinel was not created"
# Simulate LightDM /etc/lightdm/Xsession sourcing ~/.xprofile then running $@
xsession_sim = os.path.join(tmp, "Xsession")
with open(xsession_sim, "w", encoding="utf-8") as f:
f.write("#!/bin/sh\n. \"$HOME/.xprofile\"\nprintf 'USER_VAR=%s ARGS=%s\\n' \"${USER_VAR:-}\" \"$*\"\n")
os.chmod(xsession_sim, 0o755)
run1 = subprocess.run(["/bin/sh", xsession_sim, "i3"], env=env, capture_output=True, text=True, check=True)
expected_sess = os.path.join(ROOT, "scripts", "anode-session")
assert f"USER_VAR=kept ARGS={expected_sess} --profile work" == run1.stdout.strip(), run1.stdout
assert not os.path.exists(switch_file), "switch-once sentinel was not consumed on login"
# Subsequent login must return to original default session (one-shot)
run2 = subprocess.run(["/bin/sh", xsession_sim, "i3"], env=env, capture_output=True, text=True, check=True)
assert "USER_VAR=kept ARGS=i3" == run2.stdout.strip(), run2.stdout
# Re-running --switch-session without X11 WM still running must keep hook idempotent
sw_env = dict(env)
sw_env.pop("DISPLAY", None)
sw2 = subprocess.run(
[REPLACE_BIN, "--switch-session"],
env=sw_env, capture_output=True, text=True,
)
assert sw2.returncode == 0, sw2.stderr
with open(xprofile, "r", encoding="utf-8") as f:
xp_txt = f.read()
assert xp_txt.count("# >>> anode-switch-once >>>") == 1, "xprofile hook was duplicated"
assert "export USER_VAR=kept\n" in xp_txt
finally:
terminate(dm_proc)
if dpy:
X11.XCloseDisplay(dpy)
terminate(xvfb)
def test_switch_session_stale_i3sock_fallback():
import pwd
disp = pick_display()
cc = os.environ.get("CC", "cc")
cur_user = os.environ.get("USER") or pwd.getpwuid(os.getuid()).pw_name
with tempfile.TemporaryDirectory() as tmp:
env = make_env(tmp, disp)
env["XDG_CACHE_HOME"] = os.path.join(tmp, "cache")
env["I3SOCK"] = "/nonexistent/i3/ipc-socket.9999"
dm_tool_stub = os.path.join(tmp, "bin", "dm-tool")
with open(dm_tool_stub, "w", encoding="utf-8") as f:
f.write(
f"#!/bin/sh\n"
f"if [ \"${{1:-}}\" = \"list-seats\" ]; then\n"
f" printf \"Seat0\\n CanSwitch=true\\n Session0\\n UserName='%s'\\n\" '{cur_user}'\n"
f"fi\nexit 0\n"
)
os.chmod(dm_tool_stub, 0o755)
seen_file = os.path.join(tmp, "i3sock_seen")
i3_msg_stub = os.path.join(tmp, "bin", "i3-msg")
with open(i3_msg_stub, "w", encoding="utf-8") as f:
f.write(
f"#!/bin/sh\n"
f"printf '%s\\n' \"${{I3SOCK:-UNSET}}\" > '{seen_file}'\n"
f"exit 1\n"
)
os.chmod(i3_msg_stub, 0o755)
wm_bin = os.path.join(tmp, "bin", "mock_i3")
wm_c = os.path.join(tmp, "mock_i3.c")
with open(wm_c, "w", encoding="utf-8") as f:
f.write(
"#define _POSIX_C_SOURCE 200809L\n"
"#include <signal.h>\n"
"#include <time.h>\n"
"#include <unistd.h>\n"
"#include <X11/Xatom.h>\n"
"#include <X11/Xlib.h>\n"
"static volatile sig_atomic_t alive = 1;\n"
"static void stop_sig(int s) { (void)s; alive = 0; }\n"
"int main(void) {\n"
" signal(SIGTERM, stop_sig);\n"
" Display *d = XOpenDisplay(NULL);\n"
" if (!d) return 1;\n"
" Window root = DefaultRootWindow(d);\n"
" XSelectInput(d, root, SubstructureRedirectMask);\n"
" Window w = XCreateSimpleWindow(d, root, 0, 0, 1, 1, 0, 0, 0);\n"
" Atom ac = XInternAtom(d, \"_NET_SUPPORTING_WM_CHECK\", False);\n"
" Atom an = XInternAtom(d, \"_NET_WM_NAME\", False);\n"
" Atom ap = XInternAtom(d, \"_NET_WM_PID\", False);\n"
" Atom au = XInternAtom(d, \"UTF8_STRING\", False);\n"
" unsigned long pid = (unsigned long)getpid();\n"
" XChangeProperty(d, w, ac, XA_WINDOW, 32, PropModeReplace, (unsigned char *)&w, 1);\n"
" XChangeProperty(d, w, an, au, 8, PropModeReplace, (unsigned char *)\"i3\", 2);\n"
" XChangeProperty(d, w, ap, XA_CARDINAL, 32, PropModeReplace, (unsigned char *)&pid, 1);\n"
" XChangeProperty(d, root, ac, XA_WINDOW, 32, PropModeReplace, (unsigned char *)&w, 1);\n"
" XSync(d, False);\n"
" while (alive) { struct timespec ts = {0, 100000000L}; nanosleep(&ts, NULL); }\n"
" XDestroyWindow(d, w);\n"
" XCloseDisplay(d);\n"
" return 0;\n"
"}\n"
)
subprocess.run([cc, "-O2", wm_c, "-o", wm_bin] + compile_x11_flags(), check=True)
xvfb = subprocess.Popen(
["Xvfb", disp, "-screen", "0", "1280x720x24", "-nolisten", "tcp"],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
)
wm_proc = None
dpy = None
try:
dpy = wait_until(lambda: X11.XOpenDisplay(disp.encode()), timeout=5.0)
assert dpy
root = X11.XDefaultRootWindow(dpy)
wm_proc = subprocess.Popen([wm_bin], env=env)
assert wait_until(lambda: get_win_prop_ulong(dpy, root, "_NET_SUPPORTING_WM_CHECK"), timeout=5.0)
sw = subprocess.run([REPLACE_BIN, "--switch-session"], env=env, capture_output=True, text=True)
assert sw.returncode == 0, sw.stderr
assert wait_until(lambda: wm_proc.poll() is not None, timeout=4.0), "PID fallback did not stop WM after i3-msg failure"
with open(seen_file, "r", encoding="utf-8") as f:
assert f.read().strip() == "UNSET", "anode-replace did not unset stale I3SOCK before invoking i3-msg"
finally:
terminate(wm_proc)
if dpy:
X11.XCloseDisplay(dpy)
terminate(xvfb)
def main():
if not shutil.which("Xvfb"):
print("test_replace: Xvfb not installed (skipping)")
return 0
assert os.path.isfile(DWM_BIN), f"missing {DWM_BIN}"
test_fastfetch_identity()
test_icccm_replace_and_client_preservation()
test_non_icccm_wm_fallback_replace()
test_anode_session_holds_open_on_replace()
test_dm_session_leader_guard()
test_switch_session_xprofile_handoff()
test_switch_session_stale_i3sock_fallback()
print("test_replace: OK")
return 0
if __name__ == "__main__":
sys.exit(main())