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
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
444933b004
commit
d3b232f0ee
@@ -0,0 +1,167 @@
|
||||
import "dart:io";
|
||||
|
||||
import "package:flutter_test/flutter_test.dart";
|
||||
import "package:garage_updates/core.dart";
|
||||
|
||||
import "support/fake_server.dart";
|
||||
|
||||
void main() {
|
||||
late FakeServer server;
|
||||
late UpdateClient client;
|
||||
|
||||
setUp(() async {
|
||||
server = await FakeServer.start(const []);
|
||||
client = UpdateClient(project: "proj_1", apiBase: "${server.base}/", httpClient: HttpClient());
|
||||
});
|
||||
|
||||
tearDown(() async {
|
||||
client.close();
|
||||
await server.close();
|
||||
});
|
||||
|
||||
Future<UpdateInfo> check() => client.check(platform: "windows", arch: "x64", build: 12);
|
||||
|
||||
Map<String, dynamic> latest({Object? build = 13}) => {
|
||||
"label": "v2610-1",
|
||||
"build": build,
|
||||
"notes": "Fixed the thing",
|
||||
"published_at": "2026-10-01T10:00:00Z",
|
||||
"asset": {
|
||||
"url": "https://cdn.example.com/app.zip",
|
||||
"filename": "app.zip",
|
||||
"format": "zip",
|
||||
"size": 1234,
|
||||
"sha256": "ABCDEF",
|
||||
},
|
||||
};
|
||||
|
||||
test("asks the right url", () async {
|
||||
server.updateBody = {"status": "current", "minimum_build": null, "latest": null};
|
||||
await check();
|
||||
|
||||
expect(server.log.single, "GET /v1/updates/proj_1");
|
||||
final uri = client.checkUri(platform: "macos", arch: "arm64", build: 7);
|
||||
expect(uri.queryParameters, {"platform": "macos", "arch": "arm64", "build": "7"});
|
||||
// the trailing slash on apiBase didnt double up
|
||||
expect(uri.path, "/v1/updates/proj_1");
|
||||
});
|
||||
|
||||
test("current", () async {
|
||||
server.updateBody = {"status": "current", "minimum_build": 4, "latest": null};
|
||||
final info = await check();
|
||||
|
||||
expect(info.status, UpdateStatus.current);
|
||||
expect(info.minimumBuild, 4);
|
||||
expect(info.latest, isNull);
|
||||
expect(info.hasUpdate, isFalse);
|
||||
});
|
||||
|
||||
test("available", () async {
|
||||
server.updateBody = {"status": "available", "minimum_build": null, "latest": latest()};
|
||||
final info = await check();
|
||||
|
||||
expect(info.status, UpdateStatus.available);
|
||||
expect(info.hasUpdate, isTrue);
|
||||
expect(info.isRequired, isFalse);
|
||||
|
||||
final l = info.latest!;
|
||||
expect(l.label, "v2610-1");
|
||||
expect(l.build, 13);
|
||||
expect(l.notes, "Fixed the thing");
|
||||
expect(l.publishedAt, DateTime.utc(2026, 10, 1, 10));
|
||||
expect(l.asset.url, "https://cdn.example.com/app.zip");
|
||||
expect(l.asset.filename, "app.zip");
|
||||
expect(l.asset.format, "zip");
|
||||
expect(l.asset.size, 1234);
|
||||
// lower cased, its compared against our own hex
|
||||
expect(l.asset.sha256, "abcdef");
|
||||
});
|
||||
|
||||
test("required", () async {
|
||||
server.updateBody = {"status": "required", "minimum_build": 13, "latest": latest()};
|
||||
final info = await check();
|
||||
|
||||
expect(info.status, UpdateStatus.required);
|
||||
expect(info.isRequired, isTrue);
|
||||
expect(info.minimumBuild, 13);
|
||||
});
|
||||
|
||||
test("unknown", () async {
|
||||
server.updateBody = {"status": "unknown", "minimum_build": null, "latest": null};
|
||||
expect((await check()).status, UpdateStatus.unknown);
|
||||
});
|
||||
|
||||
test("a status we've never heard of is unknown", () async {
|
||||
server.updateBody = {"status": "sideways", "latest": latest()};
|
||||
expect((await check()).status, UpdateStatus.unknown);
|
||||
});
|
||||
|
||||
test("numbers as strings, missing keys and the wrong types are put up with", () async {
|
||||
final l = latest(build: "13");
|
||||
(l["asset"] as Map)["size"] = "1234";
|
||||
(l["asset"] as Map).remove("format");
|
||||
l["notes"] = 42;
|
||||
l.remove("published_at");
|
||||
server.updateBody = {"status": "available", "minimum_build": "9", "latest": l};
|
||||
|
||||
final info = await check();
|
||||
expect(info.minimumBuild, 9);
|
||||
expect(info.latest!.build, 13);
|
||||
expect(info.latest!.notes, "");
|
||||
expect(info.latest!.publishedAt, isNull);
|
||||
expect(info.latest!.asset.size, 1234);
|
||||
// worked out from the filename
|
||||
expect(info.latest!.asset.format, "zip");
|
||||
});
|
||||
|
||||
test("available with nothing usable to download is unknown", () async {
|
||||
final l = latest();
|
||||
l.remove("asset");
|
||||
server.updateBody = {"status": "available", "latest": l};
|
||||
final info = await check();
|
||||
|
||||
expect(info.status, UpdateStatus.unknown);
|
||||
expect(info.hasUpdate, isFalse);
|
||||
});
|
||||
|
||||
test("a body that isnt json, or isnt an object, is unknown", () async {
|
||||
server.updateBody = "<html>bad gateway</html>";
|
||||
expect((await check()).status, UpdateStatus.unknown);
|
||||
|
||||
server.updateBody = [1, 2, 3];
|
||||
expect((await check()).status, UpdateStatus.unknown);
|
||||
});
|
||||
|
||||
test("a relative asset url is resolved against the api", () async {
|
||||
final l = latest();
|
||||
(l["asset"] as Map)["url"] = "/v1/updates/proj_1/download/a1";
|
||||
server.updateBody = {"status": "available", "latest": l};
|
||||
|
||||
final info = await check();
|
||||
expect(info.latest!.asset.url, "${server.base}/v1/updates/proj_1/download/a1");
|
||||
});
|
||||
|
||||
test("an error status throws the store api's code", () async {
|
||||
server.updateStatus = 404;
|
||||
server.updateBody = {"error": "not_found", "message": "No such project"};
|
||||
|
||||
await expectLater(
|
||||
check(),
|
||||
throwsA(isA<UpdateError>()
|
||||
.having((e) => e.code, "code", "not_found")
|
||||
.having((e) => e.message, "message", "No such project")),
|
||||
);
|
||||
});
|
||||
|
||||
test("an error status with no json body still throws", () async {
|
||||
server.updateStatus = 502;
|
||||
server.updateBody = "bad gateway";
|
||||
|
||||
await expectLater(check(), throwsA(isA<UpdateError>().having((e) => e.code, "code", "http_502")));
|
||||
});
|
||||
|
||||
test("a server that isnt there throws network", () async {
|
||||
await server.close();
|
||||
await expectLater(check(), throwsA(isA<UpdateError>().having((e) => e.code, "code", "network")));
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
// Not a flutter test, a plain dart program:
|
||||
//
|
||||
// dart run test/core_headless.dart
|
||||
//
|
||||
// It imports core and nothing else and runs on the standalone vm, which has
|
||||
// no dart:ui. If core ever picked up a flutter import this wouldnt compile.
|
||||
|
||||
import "dart:io";
|
||||
|
||||
import "package:garage_updates/core.dart";
|
||||
|
||||
Future<void> main() async {
|
||||
final engine = UpdateEngine.detect(project: "proj_headless", build: 1);
|
||||
|
||||
// `dart run` is the jit, so this is a dev copy and the engine must sit still
|
||||
if (engine.installed) {
|
||||
stderr.writeln("FAIL: a dart run was taken for an install");
|
||||
exit(1);
|
||||
}
|
||||
engine.reportIfNotInstalled();
|
||||
|
||||
final info = await engine.check();
|
||||
if (info.status != UpdateStatus.unknown) {
|
||||
stderr.writeln("FAIL: an engine with no install asked the server");
|
||||
exit(1);
|
||||
}
|
||||
|
||||
final state = StateFile(File("${Directory.systemTemp.path}/garage_updates_headless_missing.json"));
|
||||
if (state.read() != null) {
|
||||
stderr.writeln("FAIL: a missing state file read as something");
|
||||
exit(1);
|
||||
}
|
||||
|
||||
engine.close();
|
||||
print("core runs headless: supported=$kUpdatesSupported arch=${currentUpdateArch()} platform=${currentUpdatePlatform()}");
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
import "dart:io";
|
||||
|
||||
import "package:flutter_test/flutter_test.dart";
|
||||
|
||||
// core.dart is for headless dart programs, so nothing it reaches may import
|
||||
// flutter. This walks the imports from lib/core.dart (both sides of every
|
||||
// conditional one) and checks. test/core_headless.dart is the other half: it
|
||||
// actually runs core on the plain dart vm, which has no dart:ui to give.
|
||||
|
||||
final _directive = RegExp(r'''^\s*(?:import|export)\s+([^;]+);''', multiLine: true);
|
||||
final _uri = RegExp(r'''["']([^"']+)["']''');
|
||||
|
||||
Set<String> _walk(File start) {
|
||||
final seen = <String>{};
|
||||
final uris = <String>{};
|
||||
final queue = [start];
|
||||
|
||||
while (queue.isNotEmpty) {
|
||||
final f = queue.removeLast();
|
||||
if (!seen.add(f.absolute.path)) continue;
|
||||
|
||||
for (final d in _directive.allMatches(f.readAsStringSync())) {
|
||||
for (final m in _uri.allMatches(d.group(1)!)) {
|
||||
final uri = m.group(1)!;
|
||||
if (uri.startsWith("dart:") || uri.startsWith("package:")) {
|
||||
uris.add(uri);
|
||||
} else {
|
||||
queue.add(File.fromUri(f.absolute.uri.resolve(uri)));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return uris;
|
||||
}
|
||||
|
||||
void main() {
|
||||
test("core.dart reaches no flutter", () {
|
||||
final uris = _walk(File("lib/core.dart"));
|
||||
|
||||
expect(uris, isNotEmpty);
|
||||
expect(uris.where((u) => u.startsWith("package:flutter")), isEmpty);
|
||||
expect(uris.where((u) => u.startsWith("package:garage_ui")), isEmpty);
|
||||
expect(uris, isNot(contains("dart:ui")));
|
||||
|
||||
// and the only package it leans on at all
|
||||
expect(uris.where((u) => u.startsWith("package:")).toSet(), {"package:crypto/crypto.dart"});
|
||||
});
|
||||
|
||||
test("core's web side reaches no dart:io", () {
|
||||
final uris = {
|
||||
..._walk(File("lib/src/core/models.dart")),
|
||||
..._walk(File("lib/src/core/web.dart")),
|
||||
};
|
||||
expect(uris, isNot(contains("dart:io")));
|
||||
expect(uris, isNot(contains("dart:ffi")));
|
||||
});
|
||||
|
||||
test("the flutter entry point reaches dart:io only behind a conditional import", () {
|
||||
// everything garage_updates.dart can reach on the web: the stub side of
|
||||
// each conditional import, never the io side
|
||||
final seen = <String>{};
|
||||
final uris = <String>{};
|
||||
final queue = [File("lib/garage_updates.dart")];
|
||||
|
||||
while (queue.isNotEmpty) {
|
||||
final f = queue.removeLast();
|
||||
if (!seen.add(f.absolute.path)) continue;
|
||||
|
||||
for (final d in _directive.allMatches(f.readAsStringSync())) {
|
||||
// of a conditional pair the last uri is the one the web gets
|
||||
final uri = _uri.allMatches(d.group(1)!).last.group(1)!;
|
||||
if (uri.startsWith("dart:") || uri.startsWith("package:")) {
|
||||
uris.add(uri);
|
||||
} else {
|
||||
queue.add(File.fromUri(f.absolute.uri.resolve(uri)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
expect(seen.where((p) => p.endsWith("driver_stub.dart")), isNotEmpty);
|
||||
expect(seen.where((p) => p.endsWith("driver_io.dart")), isEmpty);
|
||||
expect(uris, isNot(contains("dart:io")));
|
||||
expect(uris, isNot(contains("dart:ffi")));
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,260 @@
|
||||
import "dart:convert";
|
||||
import "dart:io";
|
||||
|
||||
import "package:flutter_test/flutter_test.dart";
|
||||
import "package:garage_updates/core.dart";
|
||||
|
||||
import "support/fake_server.dart";
|
||||
|
||||
void main() {
|
||||
late FakeServer server;
|
||||
late Directory staging;
|
||||
final data = noise(200 * 1024);
|
||||
|
||||
Downloader make({int retries = 0}) => Downloader(
|
||||
httpClient: HttpClient(),
|
||||
retries: retries,
|
||||
retryPause: const Duration(milliseconds: 10),
|
||||
quietTimeout: const Duration(seconds: 5),
|
||||
);
|
||||
|
||||
setUp(() async {
|
||||
server = await FakeServer.start(data);
|
||||
staging = Directory("${Directory.systemTemp.createTempSync("gu_dl_").path}/staging");
|
||||
});
|
||||
|
||||
tearDown(() async {
|
||||
await server.close();
|
||||
if (staging.parent.existsSync()) staging.parent.deleteSync(recursive: true);
|
||||
});
|
||||
|
||||
test("downloads, verifies and renames", () async {
|
||||
final release = server.release();
|
||||
final seen = <int>[];
|
||||
int? total;
|
||||
|
||||
final file = await make().fetch(
|
||||
release: release,
|
||||
staging: staging,
|
||||
onProgress: (got, t) {
|
||||
seen.add(got);
|
||||
total = t;
|
||||
},
|
||||
);
|
||||
|
||||
expect(file.path, Downloader.finishedFile(staging, release).path);
|
||||
expect(file.path.endsWith("update-13.zip"), isTrue);
|
||||
expect(file.readAsBytesSync(), data);
|
||||
expect(seen.last, data.length);
|
||||
expect(total, data.length);
|
||||
|
||||
// nothing left lying about
|
||||
expect(Downloader.partFile(staging).existsSync(), isFalse);
|
||||
expect(Downloader.metaFile(staging).existsSync(), isFalse);
|
||||
});
|
||||
|
||||
test("a cut connection keeps the part, and the next go resumes with Range", () async {
|
||||
final release = server.release();
|
||||
server.cutsLeft = 1;
|
||||
server.cutAfter = 50 * 1024;
|
||||
|
||||
await expectLater(
|
||||
make().fetch(release: release, staging: staging),
|
||||
throwsA(isA<UpdateError>().having((e) => e.code, "code", "download")),
|
||||
);
|
||||
|
||||
final part = Downloader.partFile(staging);
|
||||
expect(part.existsSync(), isTrue);
|
||||
final had = part.lengthSync();
|
||||
expect(had, greaterThan(0));
|
||||
expect(had, lessThan(data.length));
|
||||
expect(Downloader.metaFile(staging).existsSync(), isTrue);
|
||||
|
||||
int? firstProgress;
|
||||
final file = await make().fetch(
|
||||
release: release,
|
||||
staging: staging,
|
||||
onProgress: (got, _) => firstProgress ??= got,
|
||||
);
|
||||
|
||||
expect(server.log, ["GET /blob", "GET /blob bytes=$had-"]);
|
||||
expect(file.readAsBytesSync(), data);
|
||||
// progress carried on from where it was, not from nought
|
||||
expect(firstProgress, had);
|
||||
});
|
||||
|
||||
test("retries by itself, resuming each time", () async {
|
||||
final release = server.release();
|
||||
server.cutsLeft = 2;
|
||||
server.cutAfter = 30 * 1024;
|
||||
|
||||
final file = await make(retries: 3).fetch(release: release, staging: staging);
|
||||
|
||||
expect(file.readAsBytesSync(), data);
|
||||
expect(server.log.length, 3);
|
||||
expect(server.log[0], "GET /blob");
|
||||
expect(server.log[1], startsWith("GET /blob bytes="));
|
||||
expect(server.log[2], startsWith("GET /blob bytes="));
|
||||
});
|
||||
|
||||
test("a 200 that ignored the range starts the file again", () async {
|
||||
final release = server.release();
|
||||
server.cutsLeft = 1;
|
||||
server.cutAfter = 50 * 1024;
|
||||
await expectLater(make().fetch(release: release, staging: staging), throwsA(isA<UpdateError>()));
|
||||
|
||||
server.ignoreRange = true;
|
||||
final file = await make().fetch(release: release, staging: staging);
|
||||
|
||||
expect(server.log.last, startsWith("GET /blob bytes="));
|
||||
// not the old half with the whole file stuck on the end
|
||||
expect(file.lengthSync(), data.length);
|
||||
expect(file.readAsBytesSync(), data);
|
||||
});
|
||||
|
||||
test("a hosted download follows the 302, and asks the original url again on resume", () async {
|
||||
final release = server.release(path: "/hosted");
|
||||
server.cutsLeft = 1;
|
||||
server.cutAfter = 40 * 1024;
|
||||
|
||||
await expectLater(make().fetch(release: release, staging: staging), throwsA(isA<UpdateError>()));
|
||||
final had = Downloader.partFile(staging).lengthSync();
|
||||
|
||||
// the first presigned url is dead by now. going straight back to it would 403
|
||||
final file = await make().fetch(release: release, staging: staging);
|
||||
|
||||
expect(server.log, [
|
||||
"GET /hosted",
|
||||
"GET /blob",
|
||||
"GET /hosted bytes=$had-",
|
||||
"GET /blob bytes=$had-",
|
||||
]);
|
||||
expect(file.readAsBytesSync(), data);
|
||||
});
|
||||
|
||||
test("a checksum mismatch deletes the download and fails", () async {
|
||||
final release = server.release(sha256: "0" * 64);
|
||||
|
||||
await expectLater(
|
||||
make(retries: 3).fetch(release: release, staging: staging),
|
||||
throwsA(isA<UpdateError>().having((e) => e.code, "code", "checksum_mismatch")),
|
||||
);
|
||||
|
||||
expect(Downloader.partFile(staging).existsSync(), isFalse);
|
||||
expect(Downloader.metaFile(staging).existsSync(), isFalse);
|
||||
expect(Downloader.finishedFile(staging, release).existsSync(), isFalse);
|
||||
// and it wasnt retried, the same bytes would come back
|
||||
expect(server.log.length, 1);
|
||||
});
|
||||
|
||||
test("a stale part for another build is thrown away", () async {
|
||||
staging.createSync(recursive: true);
|
||||
Downloader.partFile(staging).writeAsBytesSync(noise(10 * 1024, seed: 99));
|
||||
Downloader.metaFile(staging).writeAsStringSync(jsonEncode({"build": 12, "sha256": "f" * 64}));
|
||||
|
||||
final file = await make().fetch(release: server.release(), staging: staging);
|
||||
|
||||
// no Range, it didnt try to carry on from someone elses bytes
|
||||
expect(server.log, ["GET /blob"]);
|
||||
expect(file.readAsBytesSync(), data);
|
||||
});
|
||||
|
||||
test("a part for the same build but another sha is stale too", () async {
|
||||
staging.createSync(recursive: true);
|
||||
Downloader.partFile(staging).writeAsBytesSync(noise(10 * 1024, seed: 99));
|
||||
Downloader.metaFile(staging).writeAsStringSync(jsonEncode({"build": 13, "sha256": "f" * 64}));
|
||||
|
||||
await make().fetch(release: server.release(), staging: staging);
|
||||
expect(server.log, ["GET /blob"]);
|
||||
});
|
||||
|
||||
test("a part with no note beside it is stale", () async {
|
||||
staging.createSync(recursive: true);
|
||||
Downloader.partFile(staging).writeAsBytesSync(noise(10 * 1024, seed: 99));
|
||||
|
||||
final file = await make().fetch(release: server.release(), staging: staging);
|
||||
expect(server.log, ["GET /blob"]);
|
||||
expect(file.readAsBytesSync(), data);
|
||||
});
|
||||
|
||||
test("a part that is allready whole only gets verified", () async {
|
||||
final release = server.release();
|
||||
staging.createSync(recursive: true);
|
||||
Downloader.partFile(staging).writeAsBytesSync(data);
|
||||
Downloader.metaFile(staging)
|
||||
.writeAsStringSync(jsonEncode({"build": release.build, "sha256": release.asset.sha256}));
|
||||
|
||||
final file = await make().fetch(release: release, staging: staging);
|
||||
expect(server.log, isEmpty);
|
||||
expect(file.readAsBytesSync(), data);
|
||||
});
|
||||
|
||||
test("a finished download is reused, and other builds' are swept", () async {
|
||||
final release = server.release();
|
||||
await make().fetch(release: release, staging: staging);
|
||||
File("${staging.path}/update-9.zip").writeAsStringSync("old");
|
||||
server.log.clear();
|
||||
|
||||
await make().fetch(release: release, staging: staging);
|
||||
expect(server.log, isEmpty);
|
||||
|
||||
// asking for a newer one clears the old finished files out
|
||||
server.data = server.data.sublist(0, 1000);
|
||||
final next = server.release(build: 14);
|
||||
await make().fetch(release: next, staging: staging);
|
||||
expect(File("${staging.path}/update-9.zip").existsSync(), isFalse);
|
||||
expect(Downloader.finishedFile(staging, release).existsSync(), isFalse);
|
||||
expect(Downloader.finishedFile(staging, next).existsSync(), isTrue);
|
||||
});
|
||||
|
||||
test("a 404 fails without retrying", () async {
|
||||
await expectLater(
|
||||
make(retries: 3).fetch(release: server.release(path: "/gone"), staging: staging),
|
||||
throwsA(isA<UpdateError>().having((e) => e.code, "code", "http_404")),
|
||||
);
|
||||
expect(server.log.length, 1);
|
||||
});
|
||||
|
||||
test("a release with no checksum is refused", () async {
|
||||
await expectLater(
|
||||
make().fetch(release: server.release(sha256: ""), staging: staging),
|
||||
throwsA(isA<UpdateError>().having((e) => e.code, "code", "no_checksum")),
|
||||
);
|
||||
expect(server.log, isEmpty);
|
||||
});
|
||||
|
||||
test("a line that goes quiet times out", () async {
|
||||
// accepts the connection and then says nothing at all
|
||||
final silent = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
|
||||
final held = <Socket>[];
|
||||
silent.listen(held.add);
|
||||
|
||||
final release = UpdateRelease(
|
||||
label: "v13",
|
||||
build: 13,
|
||||
asset: UpdateAsset(
|
||||
url: "http://127.0.0.1:${silent.port}/blob",
|
||||
filename: "app.zip",
|
||||
format: "zip",
|
||||
size: data.length,
|
||||
sha256: server.sha,
|
||||
),
|
||||
);
|
||||
|
||||
final d = Downloader(
|
||||
httpClient: HttpClient(),
|
||||
retries: 0,
|
||||
quietTimeout: const Duration(milliseconds: 300),
|
||||
);
|
||||
await expectLater(
|
||||
d.fetch(release: release, staging: staging),
|
||||
throwsA(isA<UpdateError>().having((e) => e.code, "code", "download")),
|
||||
);
|
||||
|
||||
d.close();
|
||||
for (final s in held) {
|
||||
s.destroy();
|
||||
}
|
||||
await silent.close();
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
import "dart:convert";
|
||||
import "dart:io";
|
||||
|
||||
import "package:flutter_test/flutter_test.dart";
|
||||
import "package:garage_updates/core.dart";
|
||||
|
||||
import "support/fake_install.dart";
|
||||
import "support/fake_server.dart";
|
||||
|
||||
// the engine end to end against the pretend windows install: a real check, a
|
||||
// real download off the fake server, the fake stub doing the installing
|
||||
|
||||
void main() {
|
||||
late FakeServer server;
|
||||
late FakeWindowsInstall fake;
|
||||
late UpdateEngine engine;
|
||||
final exits = <int>[];
|
||||
|
||||
Map<String, dynamic> answer(String status, {int build = 13, int? minimum}) => {
|
||||
"status": status,
|
||||
"minimum_build": minimum,
|
||||
"latest": server.release(build: build).toJson(),
|
||||
};
|
||||
|
||||
setUp(() async {
|
||||
exits.clear();
|
||||
server = await FakeServer.start(noise(64 * 1024));
|
||||
fake = FakeWindowsInstall.create();
|
||||
|
||||
final found = WindowsInstaller.locate(fake.exe.path, environment: const {});
|
||||
engine = UpdateEngine(
|
||||
project: "proj_1",
|
||||
build: 12,
|
||||
installer: found.installer,
|
||||
client: UpdateClient(project: "proj_1", apiBase: server.base, httpClient: HttpClient()),
|
||||
downloader: Downloader(httpClient: HttpClient(), retries: 0),
|
||||
arch: "x64",
|
||||
exitProcess: exits.add,
|
||||
);
|
||||
});
|
||||
|
||||
tearDown(() async {
|
||||
engine.close();
|
||||
await server.close();
|
||||
fake.dispose();
|
||||
});
|
||||
|
||||
test("check, download, install, restart", () async {
|
||||
server.updateBody = answer("available");
|
||||
final order = <String>[];
|
||||
engine.onBeforeRestart = () async {
|
||||
// the stub has allready been run by the time the app is asked to tidy up
|
||||
order.add("before restart, stub runs so far: ${fake.runs.length}");
|
||||
};
|
||||
|
||||
final info = await engine.check();
|
||||
expect(info.status, UpdateStatus.available);
|
||||
expect(server.log.single, "GET /v1/updates/proj_1");
|
||||
|
||||
final latest = info.latest!;
|
||||
expect(await engine.isDownloaded(latest), isFalse);
|
||||
await engine.download(latest);
|
||||
expect(await engine.isDownloaded(latest), isTrue);
|
||||
|
||||
final zip = "${fake.root.path}/staging/update-13.zip";
|
||||
expect(File(zip).existsSync(), isTrue);
|
||||
|
||||
await engine.install(latest);
|
||||
expect(exits, isEmpty, reason: "installing must not restart by itself");
|
||||
|
||||
await engine.restart(args: ["--route=/x"]);
|
||||
expect(exits, [0]);
|
||||
expect(order, ["before restart, stub runs so far: 1"]);
|
||||
|
||||
for (var i = 0; i < 100 && fake.runs.length < 2; i++) {
|
||||
await Future<void>.delayed(const Duration(milliseconds: 50));
|
||||
}
|
||||
expect(fake.runs, [
|
||||
["--garage-apply", zip, "13"],
|
||||
["--route=/x"],
|
||||
]);
|
||||
// the stub was handed the bytes the server sent
|
||||
expect(File("${fake.root.path}/app-13/unpacked-from.zip").readAsBytesSync(), server.data);
|
||||
});
|
||||
|
||||
test("an onBeforeRestart that throws doesnt stop the restart", () async {
|
||||
engine.onBeforeRestart = () => throw StateError("the agent wouldnt stop");
|
||||
await engine.restart();
|
||||
expect(exits, [0]);
|
||||
});
|
||||
|
||||
test("a build that failed to start here is never offered again", () async {
|
||||
// 11 is in the fake installs blocked list
|
||||
server.updateBody = answer("available", build: 11);
|
||||
engine = UpdateEngine(
|
||||
project: "proj_1",
|
||||
build: 9,
|
||||
installer: engine.installer,
|
||||
client: engine.client,
|
||||
downloader: engine.downloader,
|
||||
arch: "x64",
|
||||
exitProcess: exits.add,
|
||||
);
|
||||
|
||||
final lines = await printsOf(() async {
|
||||
final first = await engine.check();
|
||||
expect(first.status, UpdateStatus.current);
|
||||
expect(first.latest, isNull);
|
||||
expect(first.hasUpdate, isFalse);
|
||||
await engine.check();
|
||||
});
|
||||
// said once, not every six hours for ever
|
||||
expect(lines.where((l) => l.contains("failed to start on this machine")).length, 1);
|
||||
});
|
||||
|
||||
test("a build that failed for this user on a read only install isnt offered to them again", () async {
|
||||
// the stub went back to 12 for them. root still says 13 and blocks nothing
|
||||
Directory("${fake.root.path}/app-13").createSync();
|
||||
fake.stateFile.writeAsStringSync('{ "exe": "garage_stash.exe", "current": 13, "previous": 12, "failed_starts": 0, "blocked": [] }');
|
||||
for (var i = 0; i < 4; i++) {
|
||||
fake.plainLaunch(readOnly: true);
|
||||
}
|
||||
|
||||
server.updateBody = answer("available", build: 13);
|
||||
engine = UpdateEngine(
|
||||
project: "proj_1",
|
||||
build: 12,
|
||||
installer: fake.installer(readOnly: true),
|
||||
client: engine.client,
|
||||
downloader: engine.downloader,
|
||||
arch: "x64",
|
||||
exitProcess: exits.add,
|
||||
);
|
||||
|
||||
final info = await engine.check();
|
||||
expect(info.status, UpdateStatus.current);
|
||||
expect(info.hasUpdate, isFalse);
|
||||
|
||||
// the one after it is
|
||||
server.updateBody = answer("available", build: 14);
|
||||
expect((await engine.check()).latest!.build, 14);
|
||||
});
|
||||
|
||||
test("a blocked build that is also required stays required, with nothing to install", () async {
|
||||
server.updateBody = answer("required", build: 11, minimum: 11);
|
||||
engine = UpdateEngine(
|
||||
project: "proj_1",
|
||||
build: 9,
|
||||
installer: engine.installer,
|
||||
client: engine.client,
|
||||
downloader: engine.downloader,
|
||||
arch: "x64",
|
||||
);
|
||||
|
||||
final info = await engine.check();
|
||||
expect(info.status, UpdateStatus.required);
|
||||
expect(info.latest, isNull);
|
||||
});
|
||||
|
||||
test("an answer offering our own build, or an older one, is current", () async {
|
||||
server.updateBody = answer("available", build: 12);
|
||||
expect((await engine.check()).status, UpdateStatus.current);
|
||||
|
||||
server.updateBody = answer("available", build: 5);
|
||||
expect((await engine.check()).hasUpdate, isFalse);
|
||||
});
|
||||
|
||||
test("install before download says so", () async {
|
||||
await expectLater(
|
||||
engine.install(server.release()),
|
||||
throwsA(isA<UpdateError>().having((e) => e.code, "code", "not_downloaded")),
|
||||
);
|
||||
expect(fake.runs, isEmpty);
|
||||
});
|
||||
|
||||
test("markHealthy reaches the state file", () async {
|
||||
await engine.markHealthy();
|
||||
expect((jsonDecode(fake.stateFile.readAsStringSync()) as Map)["failed_starts"], 0);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,296 @@
|
||||
@TestOn("mac-os")
|
||||
library;
|
||||
|
||||
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 Directory tmp;
|
||||
late Directory apps;
|
||||
late Directory bundle;
|
||||
late MacInstaller mac;
|
||||
|
||||
setUp(() {
|
||||
// resolved, /var is a symlink to /private/var and the paths get compared
|
||||
tmp = Directory(Directory.systemTemp.createTempSync("gu_mac_").resolveSymbolicLinksSync());
|
||||
apps = Directory("${tmp.path}/Applications")..createSync();
|
||||
bundle = makeApp(apps, marker: "build 12");
|
||||
mac = MacInstaller(
|
||||
bundle: bundle,
|
||||
bundleId: "net.imbenji.foo",
|
||||
support: Directory("${tmp.path}/Library/Application Support/net.imbenji.foo/garage_updates"),
|
||||
);
|
||||
});
|
||||
|
||||
tearDown(() {
|
||||
Process.runSync("/bin/chmod", ["-R", "u+w", tmp.path]);
|
||||
tmp.deleteSync(recursive: true);
|
||||
});
|
||||
|
||||
// a zip of build [build], sitting in staging the way the downloader leaves it
|
||||
File stagedZip(int build, {String id = "net.imbenji.foo", String name = "Foo.app"}) {
|
||||
final src = Directory("${tmp.path}/src-$build")..createSync();
|
||||
final app = makeApp(src, marker: "build $build", id: id, name: name);
|
||||
mac.staging.createSync(recursive: true);
|
||||
return zipApp(app, File("${mac.staging.path}/update-$build.zip"));
|
||||
}
|
||||
|
||||
group("finding the install", () {
|
||||
test("an exe inside a bundle finds it, its id and where the state goes", () {
|
||||
final found = MacInstaller.locate("${bundle.path}/Contents/MacOS/Foo", environment: {"HOME": tmp.path});
|
||||
expect(found.reason, isNull);
|
||||
|
||||
final m = found.installer as MacInstaller;
|
||||
expect(m.bundle.path, bundle.path);
|
||||
expect(m.bundleId, "net.imbenji.foo");
|
||||
expect(m.support.path, "${tmp.path}/Library/Application Support/net.imbenji.foo/garage_updates");
|
||||
expect(m.state.file.path, endsWith("garage_updates/state.json"));
|
||||
expect(m.previousApp.path, endsWith("garage_updates/previous.app"));
|
||||
});
|
||||
|
||||
test("a helper nested in the bundle belongs to the outer app", () {
|
||||
final helper = "${bundle.path}/Contents/Library/LoginItems/Helper.app/Contents/MacOS/Helper";
|
||||
final found = MacInstaller.locate(helper, environment: {"HOME": tmp.path});
|
||||
expect((found.installer as MacInstaller).bundle.path, bundle.path);
|
||||
});
|
||||
|
||||
test("a bare executable is not an install", () {
|
||||
final found = MacInstaller.locate("${tmp.path}/bin/dart", environment: {"HOME": tmp.path});
|
||||
expect(found.installer, isNull);
|
||||
expect(found.reason, contains("app bundle"));
|
||||
});
|
||||
|
||||
test("a translocated bundle is not an install", () {
|
||||
final found = MacInstaller.locate(
|
||||
"/private/var/folders/xx/T/AppTranslocation/ABCD-1234/d/Foo.app/Contents/MacOS/Foo",
|
||||
environment: {"HOME": tmp.path},
|
||||
);
|
||||
expect(found.installer, isNull);
|
||||
expect(found.reason, contains("translocated"));
|
||||
});
|
||||
|
||||
test("a build folder is not an install", () {
|
||||
final found = MacInstaller.locate(
|
||||
"${tmp.path}/proj/build/macos/Build/Products/Release/Foo.app/Contents/MacOS/Foo",
|
||||
environment: {"HOME": tmp.path},
|
||||
);
|
||||
expect(found.installer, isNull);
|
||||
expect(found.reason, contains("build folder"));
|
||||
});
|
||||
|
||||
test("a bundle in a folder we cant write to is not an install", () {
|
||||
Process.runSync("/bin/chmod", ["555", apps.path]);
|
||||
final found = MacInstaller.locate("${bundle.path}/Contents/MacOS/Foo", environment: {"HOME": tmp.path});
|
||||
expect(found.installer, isNull);
|
||||
expect(found.reason, contains("can't be replaced"));
|
||||
});
|
||||
|
||||
test("reads the bundle id out of a binary plist too", () {
|
||||
final plist = "${bundle.path}/Contents/Info.plist";
|
||||
final res = Process.runSync("/usr/bin/plutil", ["-convert", "binary1", plist]);
|
||||
expect(res.exitCode, 0, reason: "${res.stderr}");
|
||||
expect(readBundleId(bundle), "net.imbenji.foo");
|
||||
});
|
||||
});
|
||||
|
||||
group("the swap", () {
|
||||
test("unpacks with ditto, keeps the old bundle as previous.app, puts the new one in place", () async {
|
||||
final zip = stagedZip(13);
|
||||
await mac.noteStart(12);
|
||||
|
||||
await mac.apply(zip, _release(13), runningBuild: 12);
|
||||
|
||||
expect(markerOf(bundle), "build 13");
|
||||
expect(markerOf(mac.previousApp), "build 12");
|
||||
// still a bundle someone could run
|
||||
expect(File("${bundle.path}/Contents/MacOS/Foo").existsSync(), isTrue);
|
||||
expect(readBundleId(bundle), "net.imbenji.foo");
|
||||
|
||||
final s = mac.state.read()!;
|
||||
expect(s.current, 13);
|
||||
expect(s.previous, 12);
|
||||
expect(s.failedStarts, 0);
|
||||
|
||||
expect(zip.existsSync(), isFalse);
|
||||
expect(Directory("${mac.support.path}/unpack").existsSync(), isFalse);
|
||||
// and nothing else turned up beside the app
|
||||
expect(apps.listSync().map((e) => e.uri.pathSegments.where((s) => s.isNotEmpty).last), ["Foo.app"]);
|
||||
});
|
||||
|
||||
test("a second update replaces previous.app", () async {
|
||||
await mac.apply(stagedZip(13), _release(13), runningBuild: 12);
|
||||
await mac.apply(stagedZip(14), _release(14), runningBuild: 13);
|
||||
|
||||
expect(markerOf(bundle), "build 14");
|
||||
expect(markerOf(mac.previousApp), "build 13");
|
||||
expect(mac.state.read()!.previous, 13);
|
||||
});
|
||||
|
||||
test("an update for some other app is refused and nothing moves", () async {
|
||||
final zip = stagedZip(13, id: "com.someone.else");
|
||||
|
||||
await expectLater(
|
||||
mac.apply(zip, _release(13), runningBuild: 12),
|
||||
throwsA(isA<UpdateError>().having((e) => e.code, "code", "wrong_app")),
|
||||
);
|
||||
expect(markerOf(bundle), "build 12");
|
||||
expect(mac.previousApp.existsSync(), isFalse);
|
||||
});
|
||||
|
||||
test("a zip with no app in it is refused and nothing moves", () async {
|
||||
final junk = Directory("${tmp.path}/junk")..createSync();
|
||||
File("${junk.path}/readme.txt").writeAsStringSync("hello");
|
||||
mac.staging.createSync(recursive: true);
|
||||
final zip = File("${mac.staging.path}/update-13.zip");
|
||||
Process.runSync("/usr/bin/ditto", ["-c", "-k", junk.path, zip.path]);
|
||||
|
||||
await expectLater(
|
||||
mac.apply(zip, _release(13), runningBuild: 12),
|
||||
throwsA(isA<UpdateError>().having((e) => e.code, "code", "no_app")),
|
||||
);
|
||||
expect(markerOf(bundle), "build 12");
|
||||
});
|
||||
|
||||
test("a file that isnt a zip at all fails cleanly", () async {
|
||||
mac.staging.createSync(recursive: true);
|
||||
final zip = File("${mac.staging.path}/update-13.zip")..writeAsStringSync("not a zip");
|
||||
|
||||
await expectLater(
|
||||
mac.apply(zip, _release(13), runningBuild: 12),
|
||||
throwsA(isA<UpdateError>()),
|
||||
);
|
||||
expect(markerOf(bundle), "build 12");
|
||||
});
|
||||
|
||||
test("the app inside can be one folder down, and named differently", () async {
|
||||
final src = Directory("${tmp.path}/src/Foo 13")..createSync(recursive: true);
|
||||
makeApp(src, marker: "build 13", name: "Foo Renamed.app");
|
||||
mac.staging.createSync(recursive: true);
|
||||
final zip = File("${mac.staging.path}/update-13.zip");
|
||||
Process.runSync("/usr/bin/ditto", ["-c", "-k", "--keepParent", src.path, zip.path]);
|
||||
|
||||
await mac.apply(zip, _release(13), runningBuild: 12);
|
||||
|
||||
// it goes where the running bundle was, under the running bundles name
|
||||
expect(markerOf(bundle), "build 13");
|
||||
});
|
||||
|
||||
test("a dmg is mounted, copied out of and detached", () async {
|
||||
final src = Directory("${tmp.path}/dmgsrc")..createSync();
|
||||
makeApp(src, marker: "build 13");
|
||||
mac.staging.createSync(recursive: true);
|
||||
final dmg = File("${mac.staging.path}/update-13.dmg");
|
||||
final made = Process.runSync(
|
||||
"/usr/bin/hdiutil",
|
||||
["create", "-srcfolder", src.path, "-volname", "Foo", "-format", "UDZO", "-ov", dmg.path],
|
||||
);
|
||||
expect(made.exitCode, 0, reason: "${made.stderr}");
|
||||
|
||||
await mac.apply(dmg, _release(13, format: "dmg"), runningBuild: 12);
|
||||
|
||||
expect(markerOf(bundle), "build 13");
|
||||
expect(markerOf(mac.previousApp), "build 12");
|
||||
expect(Directory("${mac.support.path}/mount").existsSync(), isFalse);
|
||||
});
|
||||
});
|
||||
|
||||
group("the fallback", () {
|
||||
test("three starts with no markHealthy and the fourth goes back", () async {
|
||||
await mac.noteStart(12);
|
||||
await mac.markHealthy();
|
||||
await mac.apply(stagedZip(13), _release(13), runningBuild: 12);
|
||||
|
||||
expect(await mac.noteStart(13), isFalse);
|
||||
expect(await mac.noteStart(13), isFalse);
|
||||
expect(await mac.noteStart(13), isFalse);
|
||||
expect(mac.state.read()!.failedStarts, 3);
|
||||
expect(markerOf(bundle), "build 13");
|
||||
|
||||
expect(await mac.noteStart(13), isTrue);
|
||||
|
||||
expect(markerOf(bundle), "build 12");
|
||||
expect(mac.previousApp.existsSync(), isFalse);
|
||||
expect(Directory("${mac.support.path}/failed.app").existsSync(), isFalse);
|
||||
|
||||
final s = mac.state.read()!;
|
||||
expect(s.current, 12);
|
||||
expect(s.previous, isNull);
|
||||
expect(s.failedStarts, 0);
|
||||
expect(s.blocked, [13]);
|
||||
expect(mac.blockedBuilds(), [13]);
|
||||
});
|
||||
|
||||
test("markHealthy stops the count", () async {
|
||||
await mac.apply(stagedZip(13), _release(13), runningBuild: 12);
|
||||
|
||||
for (var i = 0; i < 6; i++) {
|
||||
expect(await mac.noteStart(13), isFalse);
|
||||
await mac.markHealthy();
|
||||
}
|
||||
expect(markerOf(bundle), "build 13");
|
||||
expect(mac.state.read()!.failedStarts, 0);
|
||||
expect(mac.state.read()!.blocked, isEmpty);
|
||||
});
|
||||
|
||||
test("with no previous.app theres nowhere to go back to", () async {
|
||||
for (var i = 0; i < 6; i++) {
|
||||
expect(await mac.noteStart(12), isFalse);
|
||||
}
|
||||
expect(markerOf(bundle), "build 12");
|
||||
expect(mac.state.read()!.blocked, isEmpty);
|
||||
});
|
||||
|
||||
test("a build put there by hand starts its count from nought", () async {
|
||||
mac.state.write(UpdateState(current: 12, previous: 9, failedStarts: 3));
|
||||
|
||||
// 13 was dragged into Applications, the file knows nothing about it
|
||||
expect(await mac.noteStart(13), isFalse);
|
||||
|
||||
final s = mac.state.read()!;
|
||||
expect(s.current, 13);
|
||||
expect(s.failedStarts, 1);
|
||||
// no previous.app on disk, so no previous
|
||||
expect(s.previous, isNull);
|
||||
});
|
||||
|
||||
test("a damaged state file is started again rather than trusted", () async {
|
||||
mac.support.createSync(recursive: true);
|
||||
mac.state.file.writeAsStringSync('{ "current": 1');
|
||||
|
||||
expect(await mac.noteStart(12), isFalse);
|
||||
expect(mac.state.read()!.current, 12);
|
||||
expect(mac.state.read()!.failedStarts, 1);
|
||||
});
|
||||
});
|
||||
|
||||
test("relaunch is open -n on the bundle, arguments after --args", () async {
|
||||
final calls = <List<String>>[];
|
||||
final m = MacInstaller(
|
||||
bundle: bundle,
|
||||
bundleId: "net.imbenji.foo",
|
||||
support: mac.support,
|
||||
run: (exe, args) async {
|
||||
calls.add([exe, ...args]);
|
||||
return ProcessResult(1, 0, "", "");
|
||||
},
|
||||
);
|
||||
|
||||
await m.relaunch(const []);
|
||||
await m.relaunch(["--route=/settings"]);
|
||||
|
||||
expect(calls, [
|
||||
["/usr/bin/open", "-n", bundle.path],
|
||||
["/usr/bin/open", "-n", bundle.path, "--args", "--route=/settings"],
|
||||
]);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
import "dart:io";
|
||||
|
||||
import "package:flutter_test/flutter_test.dart";
|
||||
import "package:garage_updates/core.dart";
|
||||
|
||||
import "support/fake_install.dart";
|
||||
import "support/fake_server.dart";
|
||||
|
||||
// the rule: a copy the updater didnt put there is left completly alone. no
|
||||
// check, no download, nothing swapped, one line on the console.
|
||||
|
||||
void main() {
|
||||
group("detecting", () {
|
||||
test("this very test run is not an install", () {
|
||||
// flutter_tester off the jit, exactly the dev case
|
||||
final found = detectInstall();
|
||||
expect(found.installer, isNull);
|
||||
expect(found.reason, isNotNull);
|
||||
});
|
||||
|
||||
test("a debug build is never an install, wherever it sits", () {
|
||||
final fake = FakeWindowsInstall.create();
|
||||
addTearDown(fake.dispose);
|
||||
|
||||
final found = detectInstall(executable: fake.exe.path, platform: "windows", product: false);
|
||||
expect(found.installer, isNull);
|
||||
expect(found.reason, contains("release build"));
|
||||
|
||||
// the same place as a release build is one
|
||||
expect(detectInstall(executable: fake.exe.path, platform: "windows", product: true).installer, isNotNull);
|
||||
});
|
||||
|
||||
test("flutter run on windows", () {
|
||||
final found = detectInstall(
|
||||
executable: r"C:\src\app\build\windows\x64\runner\Debug\app.exe",
|
||||
platform: "windows",
|
||||
product: true,
|
||||
);
|
||||
expect(found.installer, isNull);
|
||||
expect(found.reason, contains("app-<build>"));
|
||||
});
|
||||
|
||||
test("a release exe run out of the build folder on windows", () {
|
||||
final tmp = Directory.systemTemp.createTempSync("gu_dev_");
|
||||
addTearDown(() => tmp.deleteSync(recursive: true));
|
||||
final release = Directory("${tmp.path}/build/windows/x64/runner/Release")..createSync(recursive: true);
|
||||
|
||||
final found = detectInstall(executable: "${release.path}/app.exe", platform: "windows", product: true);
|
||||
expect(found.installer, isNull);
|
||||
});
|
||||
|
||||
test("dart run / a bare binary on the mac", () {
|
||||
final found = detectInstall(
|
||||
executable: "/opt/homebrew/Cellar/dart/3.8.1/libexec/bin/dart",
|
||||
platform: "macos",
|
||||
product: true,
|
||||
environment: const {"HOME": "/Users/someone"},
|
||||
);
|
||||
expect(found.installer, isNull);
|
||||
expect(found.reason, contains("app bundle"));
|
||||
});
|
||||
|
||||
test("flutter run on the mac", () {
|
||||
final found = detectInstall(
|
||||
executable: "/Users/someone/app/build/macos/Build/Products/Debug/App.app/Contents/MacOS/App",
|
||||
platform: "macos",
|
||||
product: true,
|
||||
environment: const {"HOME": "/Users/someone"},
|
||||
);
|
||||
expect(found.installer, isNull);
|
||||
expect(found.reason, contains("build folder"));
|
||||
});
|
||||
|
||||
test("a platform core has no installer for", () {
|
||||
final found = detectInstall(executable: "/usr/bin/app", platform: "linux", product: true);
|
||||
expect(found.installer, isNull);
|
||||
expect(found.reason, contains("linux"));
|
||||
});
|
||||
});
|
||||
|
||||
group("an engine with no install", () {
|
||||
late FakeServer server;
|
||||
late UpdateEngine engine;
|
||||
final exits = <int>[];
|
||||
|
||||
setUp(() async {
|
||||
exits.clear();
|
||||
server = await FakeServer.start(noise(1024));
|
||||
server.updateBody = {"status": "required", "minimum_build": 99, "latest": server.release().toJson()};
|
||||
engine = UpdateEngine(
|
||||
project: "proj_1",
|
||||
build: 12,
|
||||
notInstalledReason: "this isn't a release build",
|
||||
client: UpdateClient(project: "proj_1", apiBase: server.base, httpClient: HttpClient()),
|
||||
downloader: Downloader(httpClient: HttpClient(), retries: 0),
|
||||
arch: "arm64",
|
||||
exitProcess: exits.add,
|
||||
);
|
||||
});
|
||||
|
||||
tearDown(() async {
|
||||
engine.close();
|
||||
await server.close();
|
||||
});
|
||||
|
||||
test("says why once, and never asks the server", () async {
|
||||
expect(engine.installed, isFalse);
|
||||
expect(engine.notInstalledReason, "this isn't a release build");
|
||||
|
||||
final lines = await printsOf(() async {
|
||||
expect((await engine.check()).status, UpdateStatus.unknown);
|
||||
expect((await engine.check()).hasUpdate, isFalse);
|
||||
expect(engine.reportIfNotInstalled(), isFalse);
|
||||
});
|
||||
|
||||
expect(lines, ["[garage_updates] not updating this copy: this isn't a release build"]);
|
||||
expect(server.log, isEmpty);
|
||||
});
|
||||
|
||||
test("wont download, install or restart", () async {
|
||||
final release = server.release();
|
||||
final notInstalled = throwsA(isA<UpdateError>().having((e) => e.code, "code", "not_installed"));
|
||||
|
||||
await expectLater(engine.download(release), notInstalled);
|
||||
await expectLater(engine.install(release), notInstalled);
|
||||
await expectLater(engine.restart(), notInstalled);
|
||||
|
||||
expect(server.log, isEmpty);
|
||||
expect(exits, isEmpty);
|
||||
});
|
||||
|
||||
test("counting starts and markHealthy are quiet no-ops", () async {
|
||||
expect(await engine.noteStart(), isFalse);
|
||||
await engine.markHealthy();
|
||||
expect(await engine.isDownloaded(server.release()), isFalse);
|
||||
});
|
||||
|
||||
test("detect() off a test run gives exactly this engine", () {
|
||||
final e = UpdateEngine.detect(project: "proj_1", build: 12);
|
||||
addTearDown(e.close);
|
||||
expect(e.installed, isFalse);
|
||||
expect(e.installer, isNull);
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
import "package:flutter/widgets.dart";
|
||||
import "package:flutter_test/flutter_test.dart";
|
||||
import "package:garage_ui/garage_ui.dart";
|
||||
import "package:garage_updates/garage_updates.dart";
|
||||
|
||||
void main() {
|
||||
const branding = UpdaterBranding(
|
||||
name: "Garage Stash",
|
||||
logo: SizedBox(key: Key("logo")),
|
||||
);
|
||||
|
||||
Future<SplashController> pumpSplash(WidgetTester t, {UpdaterBranding b = branding, VoidCallback? onGone}) async {
|
||||
final c = SplashController();
|
||||
await t.pumpWidget(UpdateSplashApp(branding: b, controller: c, onGone: onGone));
|
||||
return c;
|
||||
}
|
||||
|
||||
double? bar(WidgetTester t) => t.widget<LinearProgressIndicator>(find.byType(LinearProgressIndicator)).value;
|
||||
|
||||
testWidgets("the logo, the name, one status line and a bar", (t) async {
|
||||
await pumpSplash(t);
|
||||
|
||||
expect(find.byKey(const Key("logo")), findsOneWidget);
|
||||
expect(find.text("Garage Stash"), findsOneWidget);
|
||||
expect(find.text("Checking for updates"), findsOneWidget);
|
||||
expect(find.byType(LinearProgressIndicator), findsOneWidget);
|
||||
// nothing known yet, so the bar just sweeps
|
||||
expect(bar(t), isNull);
|
||||
|
||||
expect(find.text("Retry"), findsNothing);
|
||||
expect(find.byType(Button), findsNothing);
|
||||
});
|
||||
|
||||
testWidgets("each stage has its line", (t) async {
|
||||
final c = await pumpSplash(t);
|
||||
|
||||
c.show(SplashStage.downloading, progress: 0);
|
||||
await t.pump();
|
||||
expect(find.text("Downloading update"), findsOneWidget);
|
||||
expect(find.text("Checking for updates"), findsNothing);
|
||||
expect(bar(t), 0);
|
||||
|
||||
c.progress = 0.4;
|
||||
await t.pump();
|
||||
expect(bar(t), 0.4);
|
||||
|
||||
c.show(SplashStage.installing);
|
||||
await t.pump();
|
||||
expect(find.text("Installing"), findsOneWidget);
|
||||
expect(bar(t), isNull);
|
||||
|
||||
c.show(SplashStage.starting);
|
||||
await t.pump();
|
||||
expect(find.text("Starting"), findsOneWidget);
|
||||
expect(find.text("Installing"), findsNothing);
|
||||
});
|
||||
|
||||
testWidgets("a failure shows why and a Retry, and Retry clears it", (t) async {
|
||||
final c = await pumpSplash(t);
|
||||
c.show(SplashStage.downloading, progress: 0.3);
|
||||
|
||||
var retried = false;
|
||||
c.fail("The download didn't match its checksum").then((_) => retried = true);
|
||||
await t.pump();
|
||||
|
||||
expect(find.text("The download didn't match its checksum"), findsOneWidget);
|
||||
expect(find.text("Retry"), findsOneWidget);
|
||||
// the stage it failed at is still what the status line says
|
||||
expect(find.text("Downloading update"), findsOneWidget);
|
||||
expect(bar(t), 0.3);
|
||||
expect(retried, isFalse);
|
||||
|
||||
await t.tap(find.text("Retry"));
|
||||
await t.pump();
|
||||
|
||||
expect(retried, isTrue);
|
||||
expect(find.text("Retry"), findsNothing);
|
||||
expect(find.text("The download didn't match its checksum"), findsNothing);
|
||||
});
|
||||
|
||||
testWidgets("a failure with nothing measured stops the bar sweeping", (t) async {
|
||||
final c = await pumpSplash(t);
|
||||
c.show(SplashStage.installing);
|
||||
c.fail("The update could not be installed.");
|
||||
await t.pump();
|
||||
|
||||
expect(bar(t), 0);
|
||||
});
|
||||
|
||||
testWidgets("no logo is fine", (t) async {
|
||||
await pumpSplash(t, b: const UpdaterBranding(name: "Plain"));
|
||||
expect(find.text("Plain"), findsOneWidget);
|
||||
expect(find.byType(LinearProgressIndicator), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets("its drawn with the garage theme, carbon unless the developer says otherwise", (t) async {
|
||||
await pumpSplash(t);
|
||||
var theme = GarageTheme.of(t.element(find.byType(UpdateSplash)));
|
||||
expect(theme.colorScheme, GarageSchemes.carbon);
|
||||
|
||||
final light = ThemeData(colorScheme: GarageSchemes.light);
|
||||
await t.pumpWidget(const SizedBox());
|
||||
await pumpSplash(t, b: UpdaterBranding(name: "Light", theme: light));
|
||||
theme = GarageTheme.of(t.element(find.byType(UpdateSplash)));
|
||||
expect(theme.colorScheme, GarageSchemes.light);
|
||||
});
|
||||
|
||||
testWidgets("the host app taking over is noticed", (t) async {
|
||||
var gone = 0;
|
||||
await pumpSplash(t, onGone: () => gone++);
|
||||
expect(gone, 0);
|
||||
|
||||
// what the apps own runApp does to us
|
||||
await t.pumpWidget(const SizedBox());
|
||||
expect(gone, 1);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
import "dart:convert";
|
||||
import "dart:io";
|
||||
|
||||
import "package:flutter_test/flutter_test.dart";
|
||||
import "package:garage_updates/core.dart";
|
||||
|
||||
void main() {
|
||||
late Directory dir;
|
||||
late StateFile state;
|
||||
|
||||
setUp(() {
|
||||
dir = Directory.systemTemp.createTempSync("gu_state_");
|
||||
state = StateFile(File("${dir.path}/garage_updates.json"));
|
||||
});
|
||||
|
||||
tearDown(() => dir.deleteSync(recursive: true));
|
||||
|
||||
test("a missing file reads as null", () {
|
||||
expect(state.read(), isNull);
|
||||
});
|
||||
|
||||
test("reads what the stub writes", () {
|
||||
state.file.writeAsStringSync(
|
||||
'{ "exe": "garage_stash.exe", "current": 12, "previous": 9, "failed_starts": 2, "blocked": [11] }',
|
||||
);
|
||||
final s = state.read()!;
|
||||
|
||||
expect(s.exe, "garage_stash.exe");
|
||||
expect(s.current, 12);
|
||||
expect(s.previous, 9);
|
||||
expect(s.failedStarts, 2);
|
||||
expect(s.blocked, [11]);
|
||||
});
|
||||
|
||||
test("a half written file reads as null rather than throwing", () {
|
||||
state.file.writeAsStringSync('{ "exe": "garage_stash.exe", "curr');
|
||||
expect(state.read(), isNull);
|
||||
|
||||
state.file.writeAsStringSync("");
|
||||
expect(state.read(), isNull);
|
||||
|
||||
state.file.writeAsStringSync("[1, 2]");
|
||||
expect(state.read(), isNull);
|
||||
});
|
||||
|
||||
test("missing and mistyped fields get sane defaults", () {
|
||||
state.file.writeAsStringSync('{ "current": "12", "blocked": [11, "x", 11, 10.0], "failed_starts": null }');
|
||||
final s = state.read()!;
|
||||
|
||||
expect(s.exe, isNull);
|
||||
expect(s.current, 12);
|
||||
expect(s.previous, isNull);
|
||||
expect(s.failedStarts, 0);
|
||||
expect(s.blocked, [11, 10]);
|
||||
});
|
||||
|
||||
test("writing keeps the keys we dont know about", () {
|
||||
state.file.writeAsStringSync('{ "exe": "a.exe", "current": 12, "app_id": "net.imbenji.stash", "later": {"x": 1} }');
|
||||
|
||||
expect(state.update((s) => s.failedStarts = 0), isTrue);
|
||||
|
||||
final j = jsonDecode(state.file.readAsStringSync()) as Map;
|
||||
expect(j["app_id"], "net.imbenji.stash");
|
||||
expect(j["later"], {"x": 1});
|
||||
expect(j["exe"], "a.exe");
|
||||
expect(j["current"], 12);
|
||||
expect(j["previous"], isNull);
|
||||
expect(j["failed_starts"], 0);
|
||||
expect(j["blocked"], isEmpty);
|
||||
});
|
||||
|
||||
test("the write is a replace, no temp file is left", () {
|
||||
state.write(UpdateState(exe: "a.exe", current: 1));
|
||||
state.write(UpdateState(exe: "a.exe", current: 2, previous: 1, blocked: [3]));
|
||||
|
||||
expect(dir.listSync().map((e) => e.uri.pathSegments.last), ["garage_updates.json"]);
|
||||
final s = state.read()!;
|
||||
expect(s.current, 2);
|
||||
expect(s.previous, 1);
|
||||
expect(s.blocked, [3]);
|
||||
});
|
||||
|
||||
test("update wont write over a file it couldnt read", () {
|
||||
state.file.writeAsStringSync('{ "exe": "garage_stash.exe", "curr');
|
||||
expect(state.update((s) => s.failedStarts = 0), isFalse);
|
||||
expect(state.file.readAsStringSync(), '{ "exe": "garage_stash.exe", "curr');
|
||||
});
|
||||
|
||||
test("update can start a file that isnt there", () {
|
||||
state = StateFile(File("${dir.path}/deeper/still/state.json"));
|
||||
expect(state.update((s) => s.current = 5, createIfMissing: true), isTrue);
|
||||
expect(state.read()!.current, 5);
|
||||
});
|
||||
|
||||
group("the users file", () {
|
||||
late UserStateFile mine;
|
||||
|
||||
setUp(() => mine = UserStateFile(File("${dir.path}/local/garage_updates.json")));
|
||||
|
||||
test("reads what the stub writes", () {
|
||||
mine.file.parent.createSync();
|
||||
mine.file.writeAsStringSync('{\n "failed_starts": 2,\n "blocked": [13, 13],\n "for_current": 14,\n "run_instead": null\n}\n');
|
||||
final u = mine.read()!;
|
||||
|
||||
expect(u.failedStarts, 2);
|
||||
expect(u.blocked, [13]);
|
||||
expect(u.forCurrent, 14);
|
||||
expect(u.runInstead, isNull);
|
||||
});
|
||||
|
||||
test("missing, empty and half written all read as null", () {
|
||||
expect(mine.read(), isNull);
|
||||
|
||||
mine.file.parent.createSync();
|
||||
mine.file.writeAsStringSync("");
|
||||
expect(mine.read(), isNull);
|
||||
|
||||
mine.file.writeAsStringSync('{ "failed_starts": 2, "bl');
|
||||
expect(mine.read(), isNull);
|
||||
// and isnt written over
|
||||
expect(mine.update((u) => u.failedStarts = 0), isFalse);
|
||||
expect(mine.file.readAsStringSync(), '{ "failed_starts": 2, "bl');
|
||||
});
|
||||
|
||||
test("update doesnt start a file unless its told to", () {
|
||||
expect(mine.update((u) => u.failedStarts = 0), isFalse);
|
||||
expect(mine.file.existsSync(), isFalse);
|
||||
|
||||
expect(mine.update((u) => u.failedStarts = 1, createIfMissing: true), isTrue);
|
||||
expect(mine.file.parent.listSync().map((e) => e.uri.pathSegments.last), ["garage_updates.json"]);
|
||||
expect(jsonDecode(mine.file.readAsStringSync()), {
|
||||
"failed_starts": 1,
|
||||
"blocked": [],
|
||||
"for_current": null,
|
||||
"run_instead": null,
|
||||
});
|
||||
});
|
||||
|
||||
test("the count is only good for the current it was made against", () {
|
||||
final u = UserState(failedStarts: 2, blocked: [13], forCurrent: 13, runInstead: 12);
|
||||
|
||||
u.settleFor(13);
|
||||
expect(u.failedStarts, 2);
|
||||
expect(u.runInstead, 12);
|
||||
|
||||
u.settleFor(14);
|
||||
expect(u.failedStarts, 0);
|
||||
expect(u.runInstead, isNull);
|
||||
expect(u.forCurrent, 14);
|
||||
expect(u.blocked, [13]);
|
||||
});
|
||||
});
|
||||
|
||||
test("a write that cant happen says false", () {
|
||||
// a folder where the file should be
|
||||
Directory(state.file.path).createSync();
|
||||
expect(state.write(UpdateState(current: 1)), isFalse);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
import "dart:io";
|
||||
|
||||
import "package:garage_updates/core.dart";
|
||||
|
||||
// A pretend windows install in a temp folder. The "stub" is a shell script
|
||||
// with the stubs name: it writes down the arguments it was given, and for
|
||||
// --garage-apply does the bookkeeping the real one would.
|
||||
|
||||
const _stubScript = r'''#!/bin/sh
|
||||
dir="$(cd "$(dirname "$0")" && pwd)"
|
||||
printf '%s\n' "$@" >> "$dir/stub-args.txt"
|
||||
echo "--" >> "$dir/stub-args.txt"
|
||||
|
||||
if [ "$1" = "--garage-apply" ]; then
|
||||
if [ -f "$dir/stub-exit" ]; then
|
||||
exit "$(cat "$dir/stub-exit")"
|
||||
fi
|
||||
if [ ! -f "$dir/stub-lazy" ]; then
|
||||
mkdir -p "$dir/app-$3"
|
||||
cp "$2" "$dir/app-$3/unpacked-from.zip"
|
||||
printf '{ "exe": "garage_stash.exe", "current": %s, "previous": 12, "failed_starts": 0, "blocked": [] }' "$3" > "$dir/garage_updates.json"
|
||||
fi
|
||||
fi
|
||||
exit 0
|
||||
''';
|
||||
|
||||
class FakeWindowsInstall {
|
||||
FakeWindowsInstall._(this.tmp);
|
||||
|
||||
final Directory tmp;
|
||||
|
||||
Directory get root => Directory("${tmp.path}/Garage Stash");
|
||||
Directory get versionFolder => Directory("${root.path}/app-12");
|
||||
File get stub => File("${root.path}/garage_stash.exe");
|
||||
File get exe => File("${versionFolder.path}/garage_stash.exe");
|
||||
File get stateFile => File("${root.path}/garage_updates.json");
|
||||
File get argsFile => File("${root.path}/stub-args.txt");
|
||||
|
||||
static FakeWindowsInstall create({String? state}) {
|
||||
final f = FakeWindowsInstall._(Directory.systemTemp.createTempSync("gu_win_"));
|
||||
f.versionFolder.createSync(recursive: true);
|
||||
f.exe.writeAsStringSync("the real app, build 12");
|
||||
File("${f.versionFolder.path}/stash-agent.exe").writeAsStringSync("the agent");
|
||||
|
||||
f.stub.writeAsStringSync(_stubScript);
|
||||
Process.runSync("/bin/chmod", ["+x", f.stub.path]);
|
||||
|
||||
f.stateFile.writeAsStringSync(
|
||||
state ?? '{ "exe": "garage_stash.exe", "current": 12, "previous": 9, "failed_starts": 1, "blocked": [11] }',
|
||||
);
|
||||
return f;
|
||||
}
|
||||
|
||||
/// what LOCALAPPDATA is for an installer made by [installer]
|
||||
Directory get local => Directory("${tmp.path}/Local");
|
||||
File get userStateFile => File("${local.path}/Garage Stash/garage_updates.json");
|
||||
|
||||
/// `readOnly` is an install in Program Files. Nothing is chmodded, the
|
||||
/// installer is just told it cant write, and [plainLaunch] behaves the same
|
||||
WindowsInstaller installer({bool readOnly = false}) => WindowsInstaller(
|
||||
root: root,
|
||||
stub: stub,
|
||||
runningFolderBuild: 12,
|
||||
environment: {"LOCALAPPDATA": local.path},
|
||||
rootWritable: () => !readOnly,
|
||||
);
|
||||
|
||||
/// The stub being started with no flags, as far as the counting goes: the
|
||||
/// same sums garage_stub.cpp does, in root when it can write there and in
|
||||
/// the users own file when it cant. Returns the build it would start.
|
||||
int plainLaunch({bool readOnly = false}) {
|
||||
final state = StateFile(stateFile);
|
||||
final s = state.read()!;
|
||||
bool there(int? build) => build != null && Directory("${root.path}/app-$build").existsSync();
|
||||
|
||||
if (!readOnly) {
|
||||
if (s.failedStarts >= 3 && there(s.previous)) {
|
||||
if (!s.blocked.contains(s.current)) s.blocked.add(s.current!);
|
||||
s.current = s.previous;
|
||||
s.previous = null;
|
||||
s.failedStarts = 0;
|
||||
}
|
||||
s.failedStarts++;
|
||||
state.write(s);
|
||||
return s.current!;
|
||||
}
|
||||
|
||||
final mine = UserStateFile(userStateFile);
|
||||
final u = mine.read() ?? UserState();
|
||||
u.settleFor(s.current);
|
||||
|
||||
if (u.runInstead != null) {
|
||||
if (u.runInstead != s.current && there(u.runInstead)) return u.runInstead!;
|
||||
u.runInstead = null;
|
||||
u.failedStarts = 0;
|
||||
}
|
||||
|
||||
var run = s.current!;
|
||||
if (u.failedStarts >= 3 && there(s.previous) && s.previous != s.current && !u.blocked.contains(s.previous)) {
|
||||
if (!u.blocked.contains(s.current)) u.blocked.add(s.current!);
|
||||
u.runInstead = s.previous;
|
||||
u.failedStarts = 0;
|
||||
run = s.previous!;
|
||||
}
|
||||
if (run == s.current) u.failedStarts++;
|
||||
mine.write(u);
|
||||
return run;
|
||||
}
|
||||
|
||||
|
||||
/// every run of the stub, as the list of arguments it got
|
||||
List<List<String>> get runs {
|
||||
if (!argsFile.existsSync()) return [];
|
||||
final out = <List<String>>[];
|
||||
var cur = <String>[];
|
||||
for (final line in argsFile.readAsLinesSync()) {
|
||||
if (line == "--") {
|
||||
out.add(cur);
|
||||
cur = <String>[];
|
||||
} else {
|
||||
cur.add(line);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
void dispose() {
|
||||
// a test may have made the root read only
|
||||
Process.runSync("/bin/chmod", ["-R", "u+w", tmp.path]);
|
||||
tmp.deleteSync(recursive: true);
|
||||
}
|
||||
}
|
||||
|
||||
/// A pretend mac app. `Foo.app/Contents/{Info.plist, MacOS/Foo}` with a
|
||||
/// marker file so a test can tell which build is sitting where.
|
||||
Directory makeApp(Directory parent, {String name = "Foo.app", String id = "net.imbenji.foo", required String marker}) {
|
||||
final app = Directory("${parent.path}/$name");
|
||||
Directory("${app.path}/Contents/MacOS").createSync(recursive: true);
|
||||
Directory("${app.path}/Contents/Resources").createSync(recursive: true);
|
||||
|
||||
File("${app.path}/Contents/Info.plist").writeAsStringSync('''<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>CFBundleExecutable</key>
|
||||
<string>Foo</string>
|
||||
<key>CFBundleIdentifier</key>
|
||||
<string>$id</string>
|
||||
</dict>
|
||||
</plist>
|
||||
''');
|
||||
File("${app.path}/Contents/MacOS/Foo").writeAsStringSync("#!/bin/sh\necho $marker\n");
|
||||
File("${app.path}/Contents/Resources/marker.txt").writeAsStringSync(marker);
|
||||
return app;
|
||||
}
|
||||
|
||||
String markerOf(Directory app) => File("${app.path}/Contents/Resources/marker.txt").readAsStringSync();
|
||||
|
||||
/// zips [app] the way a release would be, with the .app at the top
|
||||
File zipApp(Directory app, File to) {
|
||||
final res = Process.runSync("/usr/bin/ditto", ["-c", "-k", "--keepParent", app.path, to.path]);
|
||||
if (res.exitCode != 0) throw StateError("ditto couldnt zip ${app.path}: ${res.stderr}");
|
||||
return to;
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
import "dart:async";
|
||||
import "dart:convert";
|
||||
import "dart:io";
|
||||
import "dart:typed_data";
|
||||
|
||||
import "package:crypto/crypto.dart";
|
||||
import "package:garage_updates/core.dart";
|
||||
|
||||
/// A file server on loopback that can be told to misbehave.
|
||||
class FakeServer {
|
||||
FakeServer._(this._server, this.data);
|
||||
|
||||
final HttpServer _server;
|
||||
Uint8List data;
|
||||
|
||||
/// "GET /blob bytes=100-" for every request, in order
|
||||
final List<String> log = [];
|
||||
|
||||
/// send a plain 200 with the whole file whatever Range says
|
||||
bool ignoreRange = false;
|
||||
|
||||
/// how many of the next downloads to cut dead, and after how many bytes
|
||||
int cutsLeft = 0;
|
||||
int cutAfter = 0;
|
||||
|
||||
/// the json `/v1/updates/<pid>` answers with, and the status it uses
|
||||
Object? updateBody;
|
||||
int updateStatus = 200;
|
||||
|
||||
/// a /blob request without this sig gets a 403, like an expired presign
|
||||
String? wantSig;
|
||||
int _sig = 0;
|
||||
|
||||
String get base => "http://127.0.0.1:${_server.port}";
|
||||
|
||||
static Future<FakeServer> start(List<int> data) async {
|
||||
final s = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
|
||||
final fake = FakeServer._(s, Uint8List.fromList(data));
|
||||
s.listen(fake._handle);
|
||||
return fake;
|
||||
}
|
||||
|
||||
Future<void> close() => _server.close(force: true);
|
||||
|
||||
String get sha => sha256.convert(data).toString();
|
||||
|
||||
UpdateRelease release({int build = 13, String path = "/blob", String format = "zip", String? sha256}) {
|
||||
return UpdateRelease(
|
||||
label: "v$build",
|
||||
build: build,
|
||||
notes: "notes for $build",
|
||||
asset: UpdateAsset(
|
||||
url: "$base$path",
|
||||
filename: "app.$format",
|
||||
format: format,
|
||||
size: data.length,
|
||||
sha256: sha256 ?? sha,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _handle(HttpRequest req) async {
|
||||
final range = req.headers.value(HttpHeaders.rangeHeader);
|
||||
log.add("${req.method} ${req.uri.path}${range == null ? "" : " $range"}");
|
||||
|
||||
if (req.uri.path.startsWith("/v1/updates/")) {
|
||||
req.response.statusCode = updateStatus;
|
||||
req.response.headers.contentType = ContentType.json;
|
||||
final body = updateBody;
|
||||
req.response.write(body is String ? body : jsonEncode(body));
|
||||
await req.response.close();
|
||||
return;
|
||||
}
|
||||
|
||||
if (req.uri.path == "/hosted") {
|
||||
// a fresh "presigned" url every time, the old ones stop working
|
||||
wantSig = "s${++_sig}";
|
||||
req.response.statusCode = HttpStatus.found;
|
||||
req.response.headers.set(HttpHeaders.locationHeader, "/blob?sig=$wantSig");
|
||||
await req.response.close();
|
||||
return;
|
||||
}
|
||||
|
||||
if (req.uri.path == "/gone") {
|
||||
req.response.statusCode = HttpStatus.notFound;
|
||||
await req.response.close();
|
||||
return;
|
||||
}
|
||||
|
||||
if (wantSig != null && req.uri.queryParameters["sig"] != wantSig) {
|
||||
req.response.statusCode = HttpStatus.forbidden;
|
||||
await req.response.close();
|
||||
return;
|
||||
}
|
||||
|
||||
var start = 0;
|
||||
var status = "200 OK";
|
||||
final extra = <String>[];
|
||||
if (range != null && !ignoreRange) {
|
||||
start = int.parse(RegExp(r"bytes=(\d+)-").firstMatch(range)!.group(1)!);
|
||||
if (start >= data.length) {
|
||||
req.response.statusCode = HttpStatus.requestedRangeNotSatisfiable;
|
||||
await req.response.close();
|
||||
return;
|
||||
}
|
||||
status = "206 Partial Content";
|
||||
extra.add("Content-Range: bytes $start-${data.length - 1}/${data.length}");
|
||||
}
|
||||
|
||||
final body = Uint8List.sublistView(data, start);
|
||||
|
||||
// written by hand on the raw socket so it can be dropped mid body
|
||||
final socket = await req.response.detachSocket(writeHeaders: false);
|
||||
socket.write("HTTP/1.1 $status\r\n"
|
||||
"Content-Length: ${body.length}\r\n"
|
||||
"${extra.map((h) => "$h\r\n").join()}"
|
||||
"Connection: close\r\n\r\n");
|
||||
|
||||
if (cutsLeft > 0) {
|
||||
cutsLeft--;
|
||||
socket.add(Uint8List.sublistView(body, 0, cutAfter.clamp(0, body.length)));
|
||||
await socket.flush();
|
||||
socket.destroy();
|
||||
return;
|
||||
}
|
||||
|
||||
socket.add(body);
|
||||
await socket.flush();
|
||||
await socket.close();
|
||||
}
|
||||
}
|
||||
|
||||
/// some bytes that arent all the same
|
||||
List<int> noise(int length, {int seed = 7}) {
|
||||
var x = seed;
|
||||
return List<int>.generate(length, (_) {
|
||||
x = (x * 1103515245 + 12345) & 0x7fffffff;
|
||||
return x & 0xff;
|
||||
});
|
||||
}
|
||||
|
||||
/// runs [body] and hands back everything it printed
|
||||
Future<List<String>> printsOf(Future<void> Function() body) async {
|
||||
final lines = <String>[];
|
||||
await runZonedPrints(body, lines);
|
||||
return lines;
|
||||
}
|
||||
|
||||
Future<void> runZonedPrints(Future<void> Function() body, List<String> into) {
|
||||
return runZoned(
|
||||
body,
|
||||
zoneSpecification: ZoneSpecification(print: (self, parent, zone, line) => into.add(line)),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,415 @@
|
||||
import "dart:async";
|
||||
|
||||
import "package:flutter/foundation.dart";
|
||||
import "package:flutter/widgets.dart";
|
||||
import "package:flutter_test/flutter_test.dart";
|
||||
import "package:garage_ui/garage_ui.dart" show LinearProgressIndicator;
|
||||
import "package:garage_updates/garage_updates.dart";
|
||||
|
||||
// GarageUpdater.launch against a driver that does whatever the test says
|
||||
|
||||
class FakeDriver implements UpdateDriver {
|
||||
FakeDriver({this.installed = true});
|
||||
|
||||
@override
|
||||
bool installed;
|
||||
|
||||
@override
|
||||
String? get notInstalledReason => installed ? null : "this isn't a release build";
|
||||
|
||||
@override
|
||||
FutureOr<void> Function()? onBeforeRestart;
|
||||
|
||||
final calls = <String>[];
|
||||
|
||||
/// what check() answers. a Completer to answer late, an error to throw
|
||||
Object? answer;
|
||||
|
||||
bool startsKeepFailing = false;
|
||||
Object? downloadError;
|
||||
Object? installError;
|
||||
Completer<void>? downloadGate;
|
||||
|
||||
@override
|
||||
Future<bool> noteStart() async {
|
||||
calls.add("noteStart");
|
||||
return startsKeepFailing;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<UpdateInfo> check() async {
|
||||
calls.add("check");
|
||||
final a = answer;
|
||||
if (a is Completer<UpdateInfo>) return a.future;
|
||||
if (a is UpdateInfo) return a;
|
||||
throw a ?? StateError("no answer set");
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> download(UpdateRelease release, {DownloadProgress? onProgress}) async {
|
||||
calls.add("download ${release.build}");
|
||||
onProgress?.call(50, 100);
|
||||
await downloadGate?.future;
|
||||
final e = downloadError;
|
||||
if (e != null) throw e;
|
||||
onProgress?.call(100, 100);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> install(UpdateRelease release) async {
|
||||
calls.add("install ${release.build}");
|
||||
final e = installError;
|
||||
if (e != null) throw e;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> restart({List<String> args = const []}) async {
|
||||
await onBeforeRestart?.call();
|
||||
calls.add("restart ${args.join(" ")}".trim());
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> markHealthy() async => calls.add("markHealthy");
|
||||
}
|
||||
|
||||
const _release = UpdateRelease(
|
||||
label: "v13",
|
||||
build: 13,
|
||||
notes: "Fixed the thing",
|
||||
asset: UpdateAsset(url: "http://x/app.zip", filename: "app.zip", format: "zip", size: 100, sha256: "aa"),
|
||||
);
|
||||
|
||||
const _current = UpdateInfo(status: UpdateStatus.current);
|
||||
const _available = UpdateInfo(status: UpdateStatus.available, latest: _release);
|
||||
const _required = UpdateInfo(status: UpdateStatus.required, minimumBuild: 13, latest: _release);
|
||||
|
||||
// the updater leaves a 6 hourly timer running, as it should. flutter_test
|
||||
// counts timers the moment the body returns, before any tearDown, so the
|
||||
// tidying has to happen in here
|
||||
void updaterTest(
|
||||
String name,
|
||||
Future<void> Function(WidgetTester t) body, {
|
||||
TargetPlatform platform = TargetPlatform.macOS,
|
||||
}) {
|
||||
testWidgets(name, (t) async {
|
||||
GarageUpdater.reset();
|
||||
// a flutter test says its android unless told otherwise
|
||||
debugDefaultTargetPlatformOverride = platform;
|
||||
try {
|
||||
await body(t);
|
||||
} finally {
|
||||
// take the splash down first, that schedules the markHealthy timer
|
||||
await t.pumpWidget(const SizedBox());
|
||||
await t.pump();
|
||||
GarageUpdater.reset();
|
||||
debugDefaultTargetPlatformOverride = null;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
void main() {
|
||||
|
||||
// starts the updater the way launch() does, with the splash going to the
|
||||
// tester instead of runApp
|
||||
({Future<void> done, bool Function() finished, Widget? Function() splash}) start(
|
||||
FakeDriver driver, {
|
||||
UpdateMode mode = UpdateMode.silent,
|
||||
List<String> args = const ["--route=/x"],
|
||||
}) {
|
||||
Widget? shown;
|
||||
var finished = false;
|
||||
final done = GarageUpdater.instance
|
||||
.start(
|
||||
args: args,
|
||||
project: "proj_1",
|
||||
build: 12,
|
||||
label: "v12",
|
||||
branding: const UpdaterBranding(name: "Garage Stash"),
|
||||
mode: mode,
|
||||
driver: driver,
|
||||
show: (w) => shown = w,
|
||||
)
|
||||
.then((_) => finished = true);
|
||||
return (done: done, finished: () => finished, splash: () => shown);
|
||||
}
|
||||
|
||||
updaterTest("up to date: the splash shows, then the app carries on", (t) async {
|
||||
final d = FakeDriver()..answer = _current;
|
||||
final run = start(d);
|
||||
await t.pump();
|
||||
|
||||
expect(run.splash(), isA<UpdateSplashApp>());
|
||||
await t.pumpWidget(run.splash()!);
|
||||
await t.pump();
|
||||
|
||||
expect(run.finished(), isTrue);
|
||||
expect(find.text("Starting"), findsOneWidget);
|
||||
expect(d.calls, ["noteStart", "check"]);
|
||||
expect(GarageUpdater.instance.ready.value, isNull);
|
||||
expect(GarageUpdater.instance.label, "v12");
|
||||
});
|
||||
|
||||
updaterTest("no answer in 2 seconds: the app starts, and the late answer is dealt with behind it", (t) async {
|
||||
final late = Completer<UpdateInfo>();
|
||||
final d = FakeDriver()..answer = late;
|
||||
final run = start(d);
|
||||
await t.pump();
|
||||
await t.pumpWidget(run.splash()!);
|
||||
|
||||
await t.pump(const Duration(milliseconds: 1900));
|
||||
expect(run.finished(), isFalse);
|
||||
expect(find.text("Checking for updates"), findsOneWidget);
|
||||
|
||||
await t.pump(const Duration(milliseconds: 200));
|
||||
expect(run.finished(), isTrue);
|
||||
expect(d.calls, ["noteStart", "check"]);
|
||||
|
||||
final heard = <UpdateInfo>[];
|
||||
GarageUpdater.instance.readyStream.listen(heard.add);
|
||||
|
||||
// the server finally answers, the app is long since up
|
||||
late.complete(_available);
|
||||
await t.pump();
|
||||
await t.pump();
|
||||
|
||||
expect(d.calls, ["noteStart", "check", "download 13"]);
|
||||
expect(GarageUpdater.instance.ready.value, same(_available));
|
||||
expect(heard, [_available]);
|
||||
expect(GarageUpdater.instance.notes, "Fixed the thing");
|
||||
// downloaded, not installed. thats the apps call now
|
||||
expect(d.calls.where((c) => c.startsWith("install")), isEmpty);
|
||||
});
|
||||
|
||||
updaterTest("a check that fails lets the app start", (t) async {
|
||||
final d = FakeDriver()..answer = UpdateError("network", "Couldn't reach the update server");
|
||||
final run = start(d);
|
||||
await t.pump();
|
||||
await t.pumpWidget(run.splash()!);
|
||||
await t.pump();
|
||||
|
||||
expect(run.finished(), isTrue);
|
||||
expect(find.text("Retry"), findsNothing);
|
||||
});
|
||||
|
||||
updaterTest("silent + available: downloaded, installed and restarted behind the splash", (t) async {
|
||||
final gate = Completer<void>();
|
||||
final d = FakeDriver()
|
||||
..answer = _available
|
||||
..downloadGate = gate;
|
||||
final stopped = <String>[];
|
||||
GarageUpdater.instance.onBeforeRestart = () => stopped.add("agent stopped");
|
||||
|
||||
final run = start(d);
|
||||
await t.pump();
|
||||
await t.pumpWidget(run.splash()!);
|
||||
await t.pump();
|
||||
await t.pump();
|
||||
|
||||
expect(find.text("Downloading update"), findsOneWidget);
|
||||
expect(t.widget<LinearProgressIndicator>(find.byType(LinearProgressIndicator)).value, 0.5);
|
||||
expect(run.finished(), isFalse);
|
||||
|
||||
gate.complete();
|
||||
await t.pump();
|
||||
await t.pump();
|
||||
|
||||
expect(d.calls, ["noteStart", "check", "download 13", "install 13", "restart --route=/x"]);
|
||||
expect(stopped, ["agent stopped"]);
|
||||
});
|
||||
|
||||
updaterTest("silent + available that fails: the old build starts anyway", (t) async {
|
||||
final d = FakeDriver()
|
||||
..answer = _available
|
||||
..installError = UpdateError("install_failed", "The update could not be installed (3)");
|
||||
final run = start(d);
|
||||
await t.pump();
|
||||
await t.pumpWidget(run.splash()!);
|
||||
await t.pump();
|
||||
await t.pump();
|
||||
|
||||
expect(run.finished(), isTrue);
|
||||
expect(find.text("Retry"), findsNothing);
|
||||
expect(d.calls.where((c) => c.startsWith("restart")), isEmpty);
|
||||
});
|
||||
|
||||
updaterTest("prompt + available: nothing is installed, ready fires, restartToUpdate applies it", (t) async {
|
||||
final d = FakeDriver()..answer = _available;
|
||||
final run = start(d, mode: UpdateMode.prompt);
|
||||
await t.pump();
|
||||
await t.pumpWidget(run.splash()!);
|
||||
await t.pump();
|
||||
await t.pump();
|
||||
|
||||
expect(run.finished(), isTrue);
|
||||
expect(d.calls, ["noteStart", "check", "download 13"]);
|
||||
expect(GarageUpdater.instance.ready.value?.latest?.build, 13);
|
||||
|
||||
await GarageUpdater.instance.restartToUpdate();
|
||||
expect(d.calls, ["noteStart", "check", "download 13", "install 13", "restart --route=/x"]);
|
||||
});
|
||||
|
||||
updaterTest("android never installs at launch unless it has to, its installer always asks", (t) async {
|
||||
final d = FakeDriver()..answer = _available;
|
||||
final run = start(d);
|
||||
await t.pump();
|
||||
await t.pumpWidget(run.splash()!);
|
||||
await t.pump();
|
||||
await t.pump();
|
||||
|
||||
expect(run.finished(), isTrue);
|
||||
expect(d.calls, ["noteStart", "check", "download 13"]);
|
||||
expect(GarageUpdater.instance.ready.value?.latest?.build, 13);
|
||||
}, platform: TargetPlatform.android);
|
||||
|
||||
updaterTest("required: the app is kept out, a failure offers Retry, and Retry goes again", (t) async {
|
||||
final d = FakeDriver()
|
||||
..answer = _required
|
||||
..downloadError = UpdateError("checksum_mismatch", "The download didn't match its checksum");
|
||||
final run = start(d);
|
||||
await t.pump();
|
||||
await t.pumpWidget(run.splash()!);
|
||||
await t.pump();
|
||||
await t.pump();
|
||||
|
||||
expect(run.finished(), isFalse);
|
||||
expect(find.text("The download didn't match its checksum"), findsOneWidget);
|
||||
expect(find.text("Retry"), findsOneWidget);
|
||||
|
||||
// still out, however long its left
|
||||
await t.pump(const Duration(minutes: 10));
|
||||
expect(run.finished(), isFalse);
|
||||
expect(d.calls.where((c) => c.startsWith("install")), isEmpty);
|
||||
|
||||
d.downloadError = null;
|
||||
await t.tap(find.text("Retry"));
|
||||
await t.pump();
|
||||
await t.pump();
|
||||
await t.pump();
|
||||
|
||||
expect(d.calls, [
|
||||
"noteStart",
|
||||
"check",
|
||||
"download 13",
|
||||
"check",
|
||||
"download 13",
|
||||
"install 13",
|
||||
"restart --route=/x",
|
||||
]);
|
||||
// a real restart ends the process. the fake comes back, which is androids
|
||||
// case: the system installer is up and the app still must not start
|
||||
expect(run.finished(), isFalse);
|
||||
expect(find.text("Install the update to continue."), findsOneWidget);
|
||||
});
|
||||
|
||||
updaterTest("required is required in prompt mode too", (t) async {
|
||||
final d = FakeDriver()..answer = _required;
|
||||
final run = start(d, mode: UpdateMode.prompt);
|
||||
await t.pump();
|
||||
await t.pumpWidget(run.splash()!);
|
||||
await t.pump();
|
||||
await t.pump();
|
||||
|
||||
expect(d.calls, contains("install 13"));
|
||||
expect(run.finished(), isFalse);
|
||||
});
|
||||
|
||||
updaterTest("required with nothing installable says so and keeps the app out", (t) async {
|
||||
final d = FakeDriver()..answer = const UpdateInfo(status: UpdateStatus.required, minimumBuild: 13);
|
||||
final run = start(d);
|
||||
await t.pump();
|
||||
await t.pumpWidget(run.splash()!);
|
||||
await t.pump();
|
||||
|
||||
expect(run.finished(), isFalse);
|
||||
expect(find.text("Retry"), findsOneWidget);
|
||||
expect(d.calls.where((c) => c.startsWith("download")), isEmpty);
|
||||
});
|
||||
|
||||
updaterTest("not installed in the layout: no splash, no check, nothing", (t) async {
|
||||
final d = FakeDriver(installed: false);
|
||||
final run = start(d);
|
||||
await t.pump();
|
||||
|
||||
expect(run.finished(), isTrue);
|
||||
expect(run.splash(), isNull);
|
||||
expect(d.calls, isEmpty);
|
||||
|
||||
// and the rest of the surface is safe to call
|
||||
await GarageUpdater.instance.markHealthy();
|
||||
await GarageUpdater.instance.restartToUpdate();
|
||||
expect(await GarageUpdater.instance.checkNow(), isNull);
|
||||
expect(d.calls, isEmpty);
|
||||
expect(GarageUpdater.instance.ready.value, isNull);
|
||||
expect(GarageUpdater.instance.notes, isNull);
|
||||
});
|
||||
|
||||
updaterTest("a start that put the old build back restarts before anything else", (t) async {
|
||||
final d = FakeDriver()
|
||||
..startsKeepFailing = true
|
||||
..answer = _current;
|
||||
start(d);
|
||||
await t.pump();
|
||||
|
||||
expect(d.calls.take(2), ["noteStart", "restart --route=/x"]);
|
||||
});
|
||||
|
||||
updaterTest("markHealthy is called a few seconds after the host apps first frame", (t) async {
|
||||
final d = FakeDriver()..answer = _current;
|
||||
final run = start(d);
|
||||
await t.pump();
|
||||
await t.pumpWidget(run.splash()!);
|
||||
await t.pump();
|
||||
expect(run.finished(), isTrue);
|
||||
|
||||
// sat on the splash, the app hasnt drawn anything of its own yet
|
||||
await t.pump(const Duration(seconds: 10));
|
||||
expect(d.calls, isNot(contains("markHealthy")));
|
||||
|
||||
await t.pumpWidget(const SizedBox(key: Key("the host app")));
|
||||
await t.pump(const Duration(seconds: 2));
|
||||
expect(d.calls, isNot(contains("markHealthy")));
|
||||
|
||||
await t.pump(const Duration(seconds: 2));
|
||||
expect(d.calls, contains("markHealthy"));
|
||||
});
|
||||
|
||||
updaterTest("checks again every 6 hours while the app runs", (t) async {
|
||||
final d = FakeDriver()..answer = _current;
|
||||
final run = start(d);
|
||||
await t.pump();
|
||||
await t.pumpWidget(run.splash()!);
|
||||
await t.pump();
|
||||
await t.pumpWidget(const SizedBox());
|
||||
|
||||
expect(d.calls.where((c) => c == "check").length, 1);
|
||||
|
||||
await t.pump(const Duration(hours: 5, minutes: 59));
|
||||
expect(d.calls.where((c) => c == "check").length, 1);
|
||||
|
||||
d.answer = _available;
|
||||
await t.pump(const Duration(minutes: 2));
|
||||
await t.pump();
|
||||
|
||||
expect(d.calls.where((c) => c == "check").length, 2);
|
||||
expect(d.calls, contains("download 13"));
|
||||
expect(GarageUpdater.instance.ready.value?.latest?.build, 13);
|
||||
|
||||
// the same build again in another 6 hours isnt fetched twice
|
||||
await t.pump(const Duration(hours: 6, minutes: 1));
|
||||
await t.pump();
|
||||
expect(d.calls.where((c) => c == "download 13").length, 1);
|
||||
});
|
||||
|
||||
updaterTest("launch twice is ignored the second time", (t) async {
|
||||
final d = FakeDriver()..answer = _current;
|
||||
final run = start(d);
|
||||
await t.pump();
|
||||
await t.pumpWidget(run.splash()!);
|
||||
await t.pump();
|
||||
|
||||
final again = start(FakeDriver()..answer = _required);
|
||||
await t.pump();
|
||||
expect(again.finished(), isTrue);
|
||||
expect(again.splash(), isNull);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,440 @@
|
||||
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);
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user