okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Windows uninstaller: remove the app's own folders (control, host, node, harness) recursively; files the app wrote there while it ran (Python bytecode caches under control) are not in the installer's file list, so those folders and the program folder stayed behind after use (found on strix with a standard user after the process fix); test4b9e05a2a

main
9.3 KiB169 linesraw
1r"""The Windows installer must never touch the user's data. The app lives in %LOCALAPPDATA%\Programs\Strata; %LOCALAPPDATA%\Strata
2holds engines, model run configs, tuning. A build that installed the app into the data folder is migrated by removing only its app
3files. Exercised with makensis on a temp layout (the template's own migration macro, extracted and run); skipped without NSIS."""
4
5import os
6import re
7import subprocess
8import tempfile
9import unittest
10from pathlib import Path
11
12ROOT = Path(__file__).resolve().parents[2]
13TEMPLATE = ROOT / "apps" / "desktop" / "src-tauri" / "nsis" / "installer.nsi"
14MAKENSIS = Path(os.environ.get("LOCALAPPDATA", "")) / "tauri" / "NSIS" / "makensis.exe"
15DATA = ["components/engine/0.1.45/strata.exe", "install/strata-iq3_s.json", "procs/p.json", "runtime/r.json", "time-skip/t.json",
16        "presets/p.json"]
17APP = ["strata-desktop.exe", "uninstall.exe", "host/server/index.mjs", "node/node.exe", "control/python/python.exe"]
18BS = "\\"
19
20
21def touch(base: Path, names):
22    for name in names:
23        path = base / name
24        path.parent.mkdir(parents=True, exist_ok=True)
25        path.write_text("x", encoding="utf-8")
26
27
28class TemplateTests(unittest.TestCase):
29    text = TEMPLATE.read_text(encoding="utf-8")
30
31    def test_the_default_folder_is_programs_strata_and_the_data_folder_is_never_remembered_as_the_app(self):
32        self.assertIn(r'StrCpy $INSTDIR "$LOCALAPPDATA\Programs\${PRODUCTNAME}"', self.text)
33        self.assertIn(r'StrCmp $4 "$LOCALAPPDATA\${PRODUCTNAME}" restore_done 0', self.text)
34        self.assertIn("StrIsUnder", self.text)          # a remembered folder under Temp is ignored too
35
36    def test_the_install_folder_page_is_shown_except_in_an_update(self):
37        # #3186 #3190: the person can put the app on another drive; the app's own updater (passive) and silent installs keep the folder
38        # the earlier install wrote to the registry, so an update never asks again and never moves the app
39        text = self.text.replace("\r\n", "\n")
40        match = re.search(r"!define MUI_PAGE_CUSTOMFUNCTION_PRE (\w+)\n!insertmacro MUI_PAGE_DIRECTORY", text)
41        self.assertIsNotNone(match)
42        self.assertEqual(match.group(1), "SkipIfPassive")
43        self.assertIn('WriteRegStr SHCTX "${MANUPRODUCTKEY}" "" $INSTDIR', text)
44        self.assertIn("Call RestorePreviousInstallLocation", text)
45        conf = (ROOT / "apps" / "desktop" / "src-tauri" / "tauri.conf.json").read_text(encoding="utf-8")
46        self.assertIn('"installMode": "currentUser"', conf)
47
48    def test_the_uninstaller_removes_files_one_by_one_and_only_empty_folders(self):
49        uninstall = self.text[self.text.index("Section Uninstall"):]
50        self.assertNotRegex(uninstall, r'RMDir /r "\$INSTDIR"')
51        self.assertNotIn(r'RmDir /r "$LOCALAPPDATA\${PRODUCTNAME}"', self.text)
52        self.assertIn(r'RmDir /r "$LOCALAPPDATA\${BUNDLEID}"', self.text)
53
54
55@unittest.skipUnless(MAKENSIS.is_file(), "NSIS (the Tauri bundler's copy) is not installed here")
56class MigrationTests(unittest.TestCase):
57    def run_nsis(self, body: str, work: Path):
58        template = TEMPLATE.read_text(encoding="utf-8")
59        block = chr(10).join(re.search(rf"; STRATA-{name}-BEGIN.*?; STRATA-{name}-END", template, re.S).group(0) for name in ("MIGRATE", "STOP", "CLEAN"))
60        script = work / "t.nsi"
61        script.write_text('Unicode true\nOutFile "t.exe"\nRequestExecutionLevel user\nSilentInstall silent\n' + block + "\nSection\n" + body + "\nSectionEnd\n", encoding="utf-8")
62        done = subprocess.run([str(MAKENSIS), "/V1", str(script)], cwd=work, capture_output=True, text=True)
63        self.assertEqual(done.returncode, 0, done.stdout + done.stderr)
64        subprocess.run([str(work / "t.exe")], cwd=work, check=True, timeout=60)
65
66    def layout(self, base: Path) -> Path:
67        old = base / "Strata"
68        touch(old, DATA + APP)
69        return old
70
71    def test_migration_removes_only_the_old_app_files_and_keeps_every_bit_of_data(self):
72        with tempfile.TemporaryDirectory() as tmp:
73            base = Path(tmp)
74            old = self.layout(base)
75            new = base / "Programs" / "Strata"
76            self.run_nsis(f'!insertmacro StrataMigrateOldInstall "{old}" "{new}"', base)
77            for name in DATA:
78                self.assertTrue((old / name).is_file(), f"data kept: {name}")
79            for name in APP:
80                self.assertFalse((old / name).exists(), f"app file removed: {name}")
81            for folder in ("host", "node", "control"):
82                self.assertFalse((old / folder).exists())
83
84    def test_migration_does_nothing_when_old_and_new_are_the_same_or_there_is_no_old_app(self):
85        with tempfile.TemporaryDirectory() as tmp:
86            base = Path(tmp)
87            old = self.layout(base)
88            self.run_nsis(f'!insertmacro StrataMigrateOldInstall "{old}" "{old}"', base)
89            for name in DATA + APP:
90                self.assertTrue((old / name).is_file(), name)
91        with tempfile.TemporaryDirectory() as tmp:
92            base = Path(tmp)
93            touch(base / "Strata", DATA)                   # data only: no strata-desktop.exe
94            self.run_nsis(f'!insertmacro StrataMigrateOldInstall "{base / "Strata"}" "{base / "Programs" / "Strata"}"', base)
95            for name in DATA:
96                self.assertTrue((base / "Strata" / name).is_file(), name)
97
98    def test_an_uninstall_of_the_template_kind_leaves_data_in_a_shared_folder(self):
99        """The uninstaller deletes named files and uses non-recursive RMDir: in a folder that also holds data (a legacy install) the
100        data and so the folder stay."""
101        with tempfile.TemporaryDirectory() as tmp:
102            base = Path(tmp)
103            old = self.layout(base)
104            lines = [f'Delete "{old}{BS}{n.replace("/", BS)}"' for n in APP]
105            lines += [f'RMDir "{old}{BS}{d}"' for d in ("host" + BS + "server", "host", "node", "control" + BS + "python", "control")]
106            lines += [f'RMDir "{old}"']
107            self.run_nsis("\n".join(lines), base)
108            for name in DATA:
109                self.assertTrue((old / name).is_file(), name)
110            self.assertFalse((old / "strata-desktop.exe").exists())
111
112
113    def test_the_uninstaller_stops_only_the_processes_started_from_the_install_folder(self):
114        ping = Path(os.environ.get("SystemRoot", r"C:\Windows")) / "System32" / "PING.EXE"
115        if not ping.is_file():
116            self.skipTest("no PING.EXE to stand in for a running Strata process")
117        with tempfile.TemporaryDirectory() as tmp:
118            base = Path(tmp)
119            inst, other = base / "Programs" / "Strata", base / "Elsewhere"
120            for folder in (inst / "node", other):
121                folder.mkdir(parents=True)
122            mine = inst / "node" / "node.exe"
123            theirs = other / "node.exe"
124            for target in (mine, theirs):
125                target.write_bytes(ping.read_bytes())
126            procs = [subprocess.Popen([str(p), "-t", "127.0.0.1"], stdout=subprocess.DEVNULL) for p in (mine, theirs)]
127            try:
128                self.run_nsis(f'!insertmacro StrataStopOwnProcesses "{inst}"', base)
129                procs[0].wait(timeout=20)
130                self.assertIsNotNone(procs[0].poll(), "the process from the install folder was stopped")
131                self.assertIsNone(procs[1].poll(), "a process of the same name elsewhere is left running")
132            finally:
133                for proc in procs:
134                    if proc.poll() is None:
135                        proc.kill()
136                    proc.wait()
137
138
139    def test_files_the_app_made_in_its_own_folders_are_removed_and_the_data_beside_them_is_not(self):
140        """Strix, standard user: after the app had run, Python bytecode caches under control\\ kept the program folder alive."""
141        with tempfile.TemporaryDirectory() as tmp:
142            base = Path(tmp)
143            inst = base / "Programs" / "Strata"
144            touch(inst, ["strata-desktop.exe", "control/python/python.exe", "control/python/Lib/__pycache__/argparse.cpython-312.pyc",
145                         "control/serve/__pycache__/server.cpython-312.pyc", "host/server/index.mjs", "host/logs/made-at-run.txt", "node/node.exe",
146                         "harness/BUNDLE.json", "components/engine/keep.txt", "runtime/keep.json"])
147            self.run_nsis(f'!insertmacro StrataRemoveAppFolders "{inst}"', base)
148            for folder in ("control", "host", "node", "harness"):
149                self.assertFalse((inst / folder).exists(), folder)
150            for name in ("components/engine/keep.txt", "runtime/keep.json", "strata-desktop.exe"):
151                self.assertTrue((inst / name).is_file(), f"kept: {name}")
152
153    def test_the_uninstaller_clears_those_folders_before_the_last_rmdir(self):
154        text = TEMPLATE.read_text(encoding="utf-8")
155        uninstall = text[text.index("Section Uninstall"):]
156        self.assertIn('!insertmacro StrataRemoveAppFolders "$INSTDIR"', uninstall)
157        self.assertLess(uninstall.index("StrataRemoveAppFolders"), uninstall.index('RMDir "$INSTDIR"'))
158        self.assertNotRegex(uninstall, r'RMDir /r "\$INSTDIR"')
159
160
161class StopOrderTests(unittest.TestCase):
162    def test_the_uninstaller_stops_them_before_it_removes_files(self):
163        text = TEMPLATE.read_text(encoding="utf-8")
164        uninstall = text[text.index("Section Uninstall"):]
165        self.assertLess(uninstall.index("StrataStopOwnProcesses"), uninstall.index(r'Delete "$INSTDIR\${MAINBINARYNAME}.exe"'))
166
167
168if __name__ == "__main__":
169    unittest.main()