Files
Garage-SDKs/garage_updates/test/windows_installer_test.dart
ImBenjiandClaude Opus 5.5 d3b232f0ee feat(garage_updates): an auto updater for garage apps
Asks Garage for the newest release of a project, downloads it with resume,
checks the sha256, installs it beside the old one and restarts into it.
Splash on garage_ui, a native stub and a first time installer for windows,
bundle swap on mac, the system installer on android. No-op on web.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KHotisA4hV2xmuZsHTksFX
2026-10-12 06:37:02 +01:00

441 lines
16 KiB
Dart

import "dart:convert";
import "dart:io";
import "package:flutter_test/flutter_test.dart";
import "package:garage_updates/core.dart";
import "support/fake_install.dart";
UpdateRelease _release(int build, {String format = "zip"}) => UpdateRelease(
label: "v$build",
build: build,
asset: UpdateAsset(url: "http://x/app.$format", filename: "app.$format", format: format, size: 3, sha256: "aa"),
);
void main() {
late FakeWindowsInstall fake;
setUp(() => fake = FakeWindowsInstall.create());
tearDown(() => fake.dispose());
WindowsInstaller locate([String? exe]) {
final found = WindowsInstaller.locate(exe ?? fake.exe.path, environment: const {});
expect(found.reason, isNull);
return found.installer as WindowsInstaller;
}
File zipIn(Directory staging) {
staging.createSync(recursive: true);
return File("${staging.path}/update-13.zip")..writeAsStringSync("zip");
}
group("finding the install", () {
test("an exe inside app-<build> finds the root, the stub and the build", () {
final w = locate();
expect(w.root.path, fake.root.path);
expect(w.stub.path, fake.stub.path);
expect(w.runningFolderBuild, 12);
expect(w.rootWritable, isTrue);
expect(w.staging.path, "${fake.root.path}/staging");
expect(w.blockedBuilds(), [11]);
// the writable probe cleaned up after itself
expect(File("${fake.root.path}/.garage_updates_probe").existsSync(), isFalse);
});
test("a helper exe finds the stub by the name in the state file", () {
final w = locate("${fake.versionFolder.path}/stash-agent.exe");
expect(w.stub.path, fake.stub.path);
});
test("the stub is still found when the state file is half written", () {
fake.stateFile.writeAsStringSync('{ "exe": "garage_st');
final w = locate();
expect(w.stub.path, fake.stub.path);
expect(w.blockedBuilds(), isEmpty);
});
test("a folder that isnt app-<build> is not an install", () {
final dev = Directory("${fake.tmp.path}/build/windows/x64/runner/Release")..createSync(recursive: true);
final found = WindowsInstaller.locate("${dev.path}/garage_stash.exe");
expect(found.installer, isNull);
expect(found.reason, contains("app-<build>"));
});
test("app-<build> with no state file beside it is not an install", () {
fake.stateFile.deleteSync();
final found = WindowsInstaller.locate(fake.exe.path);
expect(found.installer, isNull);
expect(found.reason, contains("garage_updates.json"));
});
test("an old stub left in root by an update isnt taken for the stub", () {
// nothing to go on but whats in the folder: the state wont read and
// the stub isnt named after the exe that is asking
fake.stub.renameSync("${fake.root.path}/launcher.exe");
File("${fake.root.path}/launcher.exe.old").writeAsStringSync("the stub before this one");
File("${fake.root.path}/launcher.exe.old-412-99").writeAsStringSync("and one that wouldnt delete");
fake.stateFile.writeAsStringSync('{ "exe": "garage_st');
final w = locate("${fake.versionFolder.path}/stash-agent.exe");
expect(w.stub.path, "${fake.root.path}/launcher.exe");
});
test("no stub, not an install", () {
fake.stub.deleteSync();
final found = WindowsInstaller.locate(fake.exe.path);
expect(found.installer, isNull);
expect(found.reason, contains("stub"));
});
});
group("applying", () {
test("runs the stub directly when the root is writable", () async {
final w = locate();
final zip = zipIn(w.staging);
await w.apply(zip, _release(13), runningBuild: 12);
expect(fake.runs, [
["--garage-apply", zip.path, "13"],
]);
expect(Directory("${fake.root.path}/app-13").existsSync(), isTrue);
expect(w.state.read()!.current, 13);
// the zip is spent
expect(zip.existsSync(), isFalse);
});
test("a path with spaces reaches the stub as one argument", () async {
final w = locate();
// the root is "Garage Stash", so the zip path has a space in it allready
final zip = zipIn(w.staging);
expect(zip.path, contains(" "));
await w.apply(zip, _release(13), runningBuild: 12);
expect(fake.runs.single[1], zip.path);
});
test("a stub that exits non zero fails the install and keeps the zip", () async {
File("${fake.root.path}/stub-exit").writeAsStringSync("3");
final w = locate();
final zip = zipIn(w.staging);
await expectLater(
w.apply(zip, _release(13), runningBuild: 12),
throwsA(isA<UpdateError>().having((e) => e.code, "code", "install_failed")),
);
expect(zip.existsSync(), isTrue);
expect(w.state.read()!.current, 12);
});
test("a stub that says 0 without moving current is still a failure", () async {
File("${fake.root.path}/stub-lazy").writeAsStringSync("");
final w = locate();
await expectLater(
w.apply(zipIn(w.staging), _release(13), runningBuild: 12),
throwsA(isA<UpdateError>().having((e) => e.code, "code", "install_failed")),
);
});
test("anything but a zip is refused before the stub is run", () async {
final w = locate();
await expectLater(
w.apply(zipIn(w.staging), _release(13, format: "dmg"), runningBuild: 12),
throwsA(isA<UpdateError>().having((e) => e.code, "code", "format")),
);
expect(fake.runs, isEmpty);
});
});
group("a root we cant write to", () {
test("a read only root is noticed", () {
Process.runSync("/bin/chmod", ["555", fake.root.path]);
final w = locate();
expect(w.rootWritable, isFalse);
});
test("staging moves to LOCALAPPDATA, under app_id when the state has one", () {
final local = "${fake.tmp.path}/Local";
var w = WindowsInstaller(
root: fake.root,
stub: fake.stub,
runningFolderBuild: 12,
environment: {"LOCALAPPDATA": local},
rootWritable: () => false,
);
// no app_id in the file, so the folders name
expect(w.staging.path, "$local/Garage Stash/staging");
fake.stateFile.writeAsStringSync('{ "exe": "garage_stash.exe", "current": 12, "app_id": "net.imbenji.stash" }');
w = WindowsInstaller(
root: fake.root,
stub: fake.stub,
runningFolderBuild: 12,
environment: {"LOCALAPPDATA": local},
rootWritable: () => false,
);
expect(w.staging.path, "$local/net.imbenji.stash/staging");
});
test("the stub is run elevated, through powershell", () async {
String? ranExe;
List<String>? ranArgs;
final w = WindowsInstaller(
root: fake.root,
stub: fake.stub,
runningFolderBuild: 12,
environment: {"LOCALAPPDATA": "${fake.tmp.path}/Local"},
rootWritable: () => false,
run: (exe, args) async {
ranExe = exe;
ranArgs = args;
// the elevated stub did its job
fake.stateFile.writeAsStringSync(jsonEncode({"exe": "garage_stash.exe", "current": 13, "previous": 12}));
return ProcessResult(1, 0, "", "");
},
);
final zip = zipIn(w.staging);
await w.apply(zip, _release(13), runningBuild: 12);
expect(ranExe, "powershell");
expect(ranArgs!.sublist(0, ranArgs!.length - 1),
["-NoProfile", "-ExecutionPolicy", "Bypass", "-WindowStyle", "Hidden", "-Command"]);
final script = ranArgs!.last;
expect(script, contains("Start-Process -FilePath '${fake.stub.path}'"));
expect(script, contains("-Verb RunAs"));
expect(script, contains("-Wait"));
// the zip path has a space, so its quoted inside the argument list
expect(script, contains("-ArgumentList '--garage-apply \"${zip.path}\" 13'"));
expect(script, contains("exit \$p.ExitCode"));
// the stub itself was never run unelevated
expect(fake.runs, isEmpty);
});
test("a UAC prompt turned down is its own error", () async {
final w = WindowsInstaller(
root: fake.root,
stub: fake.stub,
runningFolderBuild: 12,
environment: const {},
rootWritable: () => false,
run: (exe, args) async => ProcessResult(1, kElevationRefused, "", "The operation was canceled by the user."),
);
await expectLater(
w.apply(zipIn(Directory("${fake.tmp.path}/st")), _release(13), runningBuild: 12),
throwsA(isA<UpdateError>().having((e) => e.code, "code", "elevation_refused")),
);
});
});
group("starts counted for the user", () {
const state13 = '{ "exe": "garage_stash.exe", "current": 13, "previous": 12, "failed_starts": 0, "blocked": [11] }';
Map userJson() => jsonDecode(fake.userStateFile.readAsStringSync()) as Map;
setUp(() {
Directory("${fake.root.path}/app-13").createSync();
fake.stateFile.writeAsStringSync(state13);
});
test("the count goes in the users file, root is left as it was", () {
final w = fake.installer(readOnly: true);
expect(w.userState!.file.path, fake.userStateFile.path);
expect(fake.plainLaunch(readOnly: true), 13);
expect(fake.plainLaunch(readOnly: true), 13);
expect(userJson(), {"failed_starts": 2, "blocked": [], "for_current": 13, "run_instead": null});
expect(fake.stateFile.readAsStringSync(), state13);
expect(w.startsBuild, 13);
expect(w.blockedBuilds(), [11]);
});
test("the users file goes under app_id when the state has one", () {
fake.stateFile.writeAsStringSync('{ "exe": "garage_stash.exe", "current": 13, "app_id": "net.imbenji.stash" }');
final w = fake.installer(readOnly: true);
expect(w.userState!.file.path, "${fake.local.path}/net.imbenji.stash/garage_updates.json");
// one that couldnt be a folder name is the same as none, as in the stub
fake.stateFile.writeAsStringSync('{ "exe": "garage_stash.exe", "current": 13, "app_id": "net:imbenji" }');
expect(w.userState!.file.path, fake.userStateFile.path);
});
test("markHealthy zeroes the users count and nothing else", () async {
final w = fake.installer(readOnly: true);
fake.plainLaunch(readOnly: true);
fake.plainLaunch(readOnly: true);
await w.markHealthy();
expect(userJson(), {"failed_starts": 0, "blocked": [], "for_current": 13, "run_instead": null});
expect(fake.stateFile.readAsStringSync(), state13);
expect(fake.local.listSync(recursive: true).whereType<File>().map((f) => f.path), [fake.userStateFile.path]);
});
test("three starts that never got healthy: blocked for the user, the previous build runs instead", () {
final w = fake.installer(readOnly: true);
for (var i = 0; i < 3; i++) {
expect(fake.plainLaunch(readOnly: true), 13);
}
expect(w.startsBuild, 13);
expect(fake.plainLaunch(readOnly: true), 12);
expect(userJson(), {
"failed_starts": 0,
"blocked": [13],
"for_current": 13,
"run_instead": 12,
});
// and it stays there
expect(fake.plainLaunch(readOnly: true), 12);
expect(w.startsBuild, 12);
expect(w.blockedBuilds(), [11, 13]);
// nobody else on the machine was moved
expect(fake.stateFile.readAsStringSync(), state13);
});
test("a build to run instead that has gone is not what we say is started", () {
fake.userStateFile.parent.createSync(recursive: true);
fake.userStateFile.writeAsStringSync('{ "failed_starts": 0, "blocked": [13], "for_current": 13, "run_instead": 10 }');
final w = fake.installer(readOnly: true);
expect(w.startsBuild, 13);
expect(fake.plainLaunch(readOnly: true), 13);
expect(userJson()["run_instead"], isNull);
});
test("an update going in starts the count again, what was blocked stays", () {
final w = fake.installer(readOnly: true);
for (var i = 0; i < 4; i++) {
fake.plainLaunch(readOnly: true);
}
expect(w.startsBuild, 12);
// the elevated apply
Directory("${fake.root.path}/app-14").createSync();
fake.stateFile.writeAsStringSync('{ "exe": "garage_stash.exe", "current": 14, "previous": 13, "failed_starts": 0, "blocked": [] }');
// before the stub has even been started again
expect(w.startsBuild, 14);
expect(w.blockedBuilds(), [13]);
expect(fake.plainLaunch(readOnly: true), 14);
expect(userJson(), {"failed_starts": 1, "blocked": [13], "for_current": 14, "run_instead": null});
});
test("a previous that allready failed the user is not gone back to", () {
fake.userStateFile.parent.createSync(recursive: true);
fake.userStateFile.writeAsStringSync('{ "failed_starts": 3, "blocked": [12], "for_current": 13, "run_instead": null }');
expect(fake.plainLaunch(readOnly: true), 13);
expect(userJson()["run_instead"], isNull);
expect(userJson()["blocked"], [12]);
});
test("a users file that is half written is read as none", () async {
fake.userStateFile.parent.createSync(recursive: true);
fake.userStateFile.writeAsStringSync('{ "failed_sta');
final w = fake.installer(readOnly: true);
expect(w.blockedBuilds(), [11]);
expect(w.startsBuild, 13);
await w.markHealthy();
expect(fake.userStateFile.readAsStringSync(), '{ "failed_sta');
});
test("a root that can be written never gets a users file", () async {
final w = fake.installer();
expect(fake.plainLaunch(), 13);
expect(fake.plainLaunch(), 13);
expect(w.state.read()!.failedStarts, 2);
expect(w.blockedBuilds(), [11]);
expect(w.startsBuild, 13);
await w.markHealthy();
expect(w.state.read()!.failedStarts, 0);
expect(fake.userStateFile.existsSync(), isFalse);
expect(fake.local.existsSync(), isFalse);
// and falling back there is still the root file changing
for (var i = 0; i < 3; i++) {
fake.plainLaunch();
}
expect(fake.plainLaunch(), 12);
final s = w.state.read()!;
expect(s.current, 12);
expect(s.blocked, [11, 13]);
expect(w.startsBuild, 12);
expect(fake.local.existsSync(), isFalse);
});
});
group("quoting", () {
test("windows arguments", () {
expect(windowsQuoteArg("--garage-apply"), "--garage-apply");
expect(windowsQuoteArg("13"), "13");
expect(windowsQuoteArg(""), '""');
expect(windowsQuoteArg(r"C:\Program Files\App\x.zip"), r'"C:\Program Files\App\x.zip"');
// a trailing backslash would otherwise eat the closing quote
expect(windowsQuoteArg(r"C:\My Apps\"), r'"C:\My Apps\\"');
expect(windowsQuoteArg(r'say "hi"'), r'"say \"hi\""');
expect(windowsQuoteArg(r'a\"b c'), r'"a\\\"b c"');
});
test("powershell strings", () {
expect(powershellQuote(r"C:\Users\O'Brien\app.exe"), r"'C:\Users\O''Brien\app.exe'");
expect(powershellQuote(r"$env:x `n"), r"'$env:x `n'");
});
test("the elevation script survives a quote in the path", () {
final args = elevationArgs(r"C:\Users\O'Brien\App\app.exe", ["--garage-apply", r"C:\Users\O'Brien\x.zip", "13"]);
expect(args.last, contains(r"-FilePath 'C:\Users\O''Brien\App\app.exe'"));
expect(args.last, contains(r"-ArgumentList '--garage-apply C:\Users\O''Brien\x.zip 13'"));
});
});
test("relaunch starts the stub with the apps own arguments", () async {
final w = locate();
await w.relaunch(["--route=/settings", "two words"]);
// its detached, give it a moment to run
for (var i = 0; i < 100 && fake.runs.isEmpty; i++) {
await Future<void>.delayed(const Duration(milliseconds: 50));
}
expect(fake.runs, [
["--route=/settings", "two words"],
]);
});
test("markHealthy zeroes failed_starts and nothing else", () async {
final w = locate();
await w.markHealthy();
final j = jsonDecode(fake.stateFile.readAsStringSync()) as Map;
expect(j["failed_starts"], 0);
expect(j["current"], 12);
expect(j["previous"], 9);
expect(j["blocked"], [11]);
expect(j["exe"], "garage_stash.exe");
});
test("markHealthy leaves a half written state file alone", () async {
fake.stateFile.writeAsStringSync('{ "exe": "garage_st');
await locate().markHealthy();
expect(fake.stateFile.readAsStringSync(), '{ "exe": "garage_st');
});
test("the stub counts starts on windows, not us", () async {
final w = locate();
expect(await w.noteStart(12), isFalse);
expect(w.state.read()!.failedStarts, 1);
});
}