fix(app): resumable, cancellable update download; portable copies get the portable zip

- UpdateFlow owns the update notice (check, download, cancel) as a plain class;
  AboutViewModel only maps it to text and commands.
- A portable copy downloads and verifies Titano-win-x64-portable-<v>.zip instead
  of the setup; a release without the package or SHA256SUMS opens its page.
- The download fails after 60 s without data instead of after 30 minutes,
  keeps its .part file and resumes it with a range request; Cancel stops it.
- Older release folders under %TEMP%\Titano\updates are removed after a
  verified download; an unexpected exception never leaves "Downloading".
- Tooltips show the package size; stale machine translations of the three
  rewritten tooltips are removed so they fall back to English.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
Claude committed 2026-10-03 10:00:54 +00:00
1 parent aac2539276
commit ffa05d9f69
36 files changed
+828 -298

No files matched your search

@@ -1,6 +1,7 @@
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Cryptography;
using System.Text;
using Titano.App.About;
@@ -10,10 +11,13 @@ namespace Titano.App.Tests.About;
public sealed class UpdateDownloadTests(TestContext context)
{
private const string SetupUrl = "https://github.com/o/r/releases/download/v1.0.0/Titano-Setup-1.0.0.exe";
private const string SumsUrl = "https://github.com/o/r/releases/download/v1.0.0/SHA256SUMS";
private const string Base = "https://github.com/o/r/releases/download/v1.0.0/";
private const string SetupName = "Titano-Setup-1.0.0.exe";
private const string PortableName = "Titano-win-x64-portable-1.0.0.zip";
private static readonly TimeSpan Idle = TimeSpan.FromSeconds(30);
private static readonly byte[] Setup = Encoding.ASCII.GetBytes(string.Concat(Enumerable.Repeat("MZ setup payload ", 20_000)));
private static readonly byte[] Portable = Encoding.ASCII.GetBytes(string.Concat(Enumerable.Repeat("PK portable zip ", 9_000)));
[Test]
public void ChecksumLinesOfBothSha256sumModesAreRead()
@@ -27,116 +31,295 @@ public sealed class UpdateDownloadTests(TestContext context)
}
[Test]
public void TheDesktopSetupAndTheChecksumsAreFoundAmongTheAssets()
public void ThePackageForEachKindOfCopyAndTheChecksumsAreFoundAmongTheAssets()
{
var release = UpdateCheck.Parse($$"""
{ "tag_name": "v1.0.0", "html_url": "https://github.com/o/r/releases/tag/v1.0.0", "assets": [
{ "name": "Titano-Uploader-Setup-1.0.0.exe", "browser_download_url": "https://github.com/o/r/releases/download/v1.0.0/Titano-Uploader-Setup-1.0.0.exe", "size": 10 },
{ "name": "Titano-Setup-1.0.0.exe", "browser_download_url": "{{SetupUrl}}", "size": {{Setup.Length}} },
{ "name": "SHA256SUMS", "browser_download_url": "{{SumsUrl}}", "size": 300 },
{ "name": "Titano-Uploader-Setup-1.0.0.exe", "browser_download_url": "{{Base}}Titano-Uploader-Setup-1.0.0.exe", "size": 10 },
{ "name": "{{SetupName}}", "browser_download_url": "{{Base}}{{SetupName}}", "size": {{Setup.Length}} },
{ "name": "{{PortableName}}", "browser_download_url": "{{Base}}{{PortableName}}", "size": {{Portable.Length}} },
{ "name": "SHA256SUMS", "browser_download_url": "{{Base}}SHA256SUMS", "size": 300 },
{ "name": "evil.exe", "browser_download_url": "http://example.com/evil.exe", "size": 1 }
] }
""")!;
Assert.Equal(3, release.Assets.Count);
Assert.Equal("Titano-Setup-1.0.0.exe", UpdateDownload.Installer(release)!.Name);
Assert.Equal(SumsUrl, UpdateDownload.Checksums(release)!.DownloadUrl);
Assert.True(UpdateDownload.CanDownload(release));
Assert.False(UpdateDownload.CanDownload(release with { Assets = [.. release.Assets.Where(a => a.Name != "SHA256SUMS")] }));
Assert.True(UpdateDownload.Folder(Path.GetTempPath(), release).EndsWith(Path.Combine("Titano", "updates", "v1.0.0"), StringComparison.Ordinal));
Assert.Equal(4, release.Assets.Count);
Assert.Equal(SetupName, UpdateDownload.Package(release, portable: false)!.Name);
Assert.Equal(PortableName, UpdateDownload.Package(release, portable: true)!.Name);
Assert.Equal(Base + "SHA256SUMS", UpdateDownload.Checksums(release)!.DownloadUrl);
Assert.True(UpdateDownload.CanDownload(release, portable: false));
Assert.True(UpdateDownload.CanDownload(release, portable: true));
Assert.False(UpdateDownload.CanDownload(release with { Assets = [.. release.Assets.Where(a => a.Name != "SHA256SUMS")] }, portable: false));
Assert.False(UpdateDownload.CanDownload(release with { Assets = [.. release.Assets.Where(a => a.Name != PortableName)] }, portable: true));
var root = UpdateDownload.Root(Path.GetTempPath());
Assert.True(root.EndsWith(Path.Combine("Titano", "updates"), StringComparison.Ordinal), root);
Assert.Equal(Path.Combine(root, "v1.0.0"), UpdateDownload.Folder(root, release));
}
[Test]
public async Task AVerifiedSetupIsKeptAndReusedWithoutDownloadingAgain()
{
var folder = context.CreateTempDirectory();
var server = new FakeReleases(Sums(Setup), Setup);
var root = context.CreateTempDirectory();
var server = new FakeReleases(Setup);
using var http = new HttpClient(server);
var reported = new List<double>();
var path = await UpdateDownload.DownloadAsync(http, Release(), folder, "0.1.0", new SyncProgress(reported.Add), CancellationToken.None);
Assert.Equal(Path.Combine(folder, "Titano-Setup-1.0.0.exe"), path);
var path = await DownloadAsync(http, root, progress: new SyncProgress(reported.Add));
Assert.Equal(Path.Combine(root, "v1.0.0", SetupName), path);
Assert.SequenceEqual(Setup, await File.ReadAllBytesAsync(path));
Assert.Equal(1.0, reported[^1]);
Assert.Equal(1, server.SetupRequests);
Assert.SequenceEqual(new[] { "Titano-Setup-1.0.0.exe" }, Directory.GetFiles(folder).Select(f => Path.GetFileName(f)));
Assert.Equal(1, server.PackageRequests);
Assert.SequenceEqual(new[] { SetupName }, Directory.GetFiles(Path.GetDirectoryName(path)!).Select(f => Path.GetFileName(f)));
await UpdateDownload.DownloadAsync(http, Release(), folder, "0.1.0", null, CancellationToken.None);
Assert.Equal(1, server.SetupRequests);
await DownloadAsync(http, root);
Assert.Equal(1, server.PackageRequests);
}
[Test]
public async Task APortableCopyGetsThePortableZipNeverTheSetup()
{
var root = context.CreateTempDirectory();
var server = new FakeReleases(Setup);
using var http = new HttpClient(server);
var path = await DownloadAsync(http, root, portable: true);
Assert.Equal(PortableName, Path.GetFileName(path));
Assert.SequenceEqual(Portable, await File.ReadAllBytesAsync(path));
Assert.SequenceEqual(new[] { Base + PortableName }, server.PackageUrls);
}
[Test]
public async Task ASetupThatDoesNotMatchItsChecksumIsDeleted()
{
var folder = context.CreateTempDirectory();
var root = context.CreateTempDirectory();
var tampered = Setup.ToArray();
tampered[^1] ^= 1;
using var http = new HttpClient(new FakeReleases(Sums(Setup), tampered));
var error = await Assert.ThrowsAsync<UpdateVerificationException>(() =>
UpdateDownload.DownloadAsync(http, Release(), folder, "0.1.0", null, CancellationToken.None));
using var http = new HttpClient(new FakeReleases(Setup) { Served = tampered });
var error = await Assert.ThrowsAsync<UpdateVerificationException>(() => DownloadAsync(http, root));
Assert.Contains("does not match", error.Message);
Assert.Empty(Directory.GetFiles(folder));
Assert.Empty(Directory.GetFiles(root, "*", SearchOption.AllDirectories));
}
[Test]
public async Task ACorruptedSetupLeftFromBeforeIsReplacedByAFreshDownload()
{
var root = context.CreateTempDirectory();
var server = new FakeReleases(Setup);
using var http = new HttpClient(server);
var target = Path.Combine(root, "v1.0.0", SetupName);
Directory.CreateDirectory(Path.GetDirectoryName(target)!);
await File.WriteAllBytesAsync(target, Setup[..1000]);
Assert.Equal(target, await DownloadAsync(http, root));
Assert.SequenceEqual(Setup, await File.ReadAllBytesAsync(target));
Assert.Equal(1, server.PackageRequests);
}
[Test]
public async Task ASetupWithoutAChecksumLineIsNeverDownloaded()
{
var folder = context.CreateTempDirectory();
var server = new FakeReleases($"{new string('0', 64)} Titano-Uploader-Setup-1.0.0.exe\n", Setup);
var root = context.CreateTempDirectory();
var server = new FakeReleases(Setup) { Sums = $"{new string('0', 64)} Titano-Uploader-Setup-1.0.0.exe\n" };
using var http = new HttpClient(server);
await Assert.ThrowsAsync<UpdateVerificationException>(() => UpdateDownload.DownloadAsync(http, Release(), folder, "0.1.0", null, CancellationToken.None));
Assert.Equal(0, server.SetupRequests);
Assert.Empty(Directory.GetFiles(folder));
await Assert.ThrowsAsync<UpdateVerificationException>(() => DownloadAsync(http, root));
Assert.Equal(0, server.PackageRequests);
Assert.Empty(Directory.GetFiles(root, "*", SearchOption.AllDirectories));
}
[Test]
public async Task MoreBytesThanTheReleaseAnnouncedAreRefused()
{
var folder = context.CreateTempDirectory();
var root = context.CreateTempDirectory();
var longer = Setup.Concat(new byte[100]).ToArray();
using var http = new HttpClient(new FakeReleases(Sums(longer), longer));
await Assert.ThrowsAsync<UpdateVerificationException>(() => UpdateDownload.DownloadAsync(http, Release(), folder, "0.1.0", null, CancellationToken.None));
Assert.Empty(Directory.GetFiles(folder));
using var http = new HttpClient(new FakeReleases(Setup) { Served = longer, Sums = Sums(longer, Portable) });
await Assert.ThrowsAsync<UpdateVerificationException>(() => DownloadAsync(http, root));
Assert.Empty(Directory.GetFiles(root, "*", SearchOption.AllDirectories));
}
[Test]
public async Task AFailedRequestLeavesNoPartialFile()
public async Task AFailedRequestLeavesNoFile()
{
var folder = context.CreateTempDirectory();
using var http = new HttpClient(new FakeReleases(Sums(Setup), null));
await Assert.ThrowsAsync<HttpRequestException>(() => UpdateDownload.DownloadAsync(http, Release(), folder, "0.1.0", null, CancellationToken.None));
Assert.Empty(Directory.GetFiles(folder));
var root = context.CreateTempDirectory();
using var http = new HttpClient(new FakeReleases(Setup) { Fail = true });
await Assert.ThrowsAsync<HttpRequestException>(() => DownloadAsync(http, root));
Assert.Empty(Directory.GetFiles(root, "*", SearchOption.AllDirectories));
}
[Test]
public async Task ATransferCutShortIsResumedWhereItStopped()
{
var root = context.CreateTempDirectory();
var server = new FakeReleases(Setup) { CutAfter = 100_000 };
using var http = new HttpClient(server);
await Assert.ThrowsAsync<IOException>(() => DownloadAsync(http, root));
var part = Path.Combine(root, "v1.0.0", SetupName + ".part");
Assert.Equal(100_000L, new FileInfo(part).Length);
server.CutAfter = null;
var path = await DownloadAsync(http, root);
Assert.SequenceEqual(Setup, await File.ReadAllBytesAsync(path));
Assert.SequenceEqual(new long?[] { null, 100_000 }, server.Ranges);
Assert.FileMissing(part);
}
[Test]
public async Task AServerThatIgnoresTheRangeStartsTheFileAgain()
{
var root = context.CreateTempDirectory();
var server = new FakeReleases(Setup) { CutAfter = 50_000 };
using var http = new HttpClient(server);
await Assert.ThrowsAsync<IOException>(() => DownloadAsync(http, root));
server.CutAfter = null;
server.HonourRange = false;
var path = await DownloadAsync(http, root);
Assert.SequenceEqual(Setup, await File.ReadAllBytesAsync(path));
}
[Test]
public async Task ACancelledDownloadKeepsItsPartialFileForTheNextAttempt()
{
var root = context.CreateTempDirectory();
var server = new FakeReleases(Setup) { StallAfter = 64 * 1024 };
using var http = new HttpClient(server);
using var cts = new CancellationTokenSource();
var reported = new List<double>();
var download = DownloadAsync(http, root, progress: new SyncProgress(f =>
{
reported.Add(f);
cts.Cancel();
}), ct: cts.Token);
await Assert.ThrowsAsync<OperationCanceledException>(() => download);
var part = Path.Combine(root, "v1.0.0", SetupName + ".part");
Assert.Equal(64L * 1024, new FileInfo(part).Length);
server.StallAfter = null;
Assert.SequenceEqual(Setup, await File.ReadAllBytesAsync(await DownloadAsync(http, root)));
Assert.Equal(64L * 1024, server.Ranges[^1]);
}
[Test]
public async Task ATransferThatStallsFailsAfterTheIdleTimeout()
{
var root = context.CreateTempDirectory();
using var http = new HttpClient(new FakeReleases(Setup) { StallAfter = 10_000 });
var started = DateTime.UtcNow;
var error = await Assert.ThrowsAsync<TimeoutException>(() => DownloadAsync(http, root, idle: TimeSpan.FromMilliseconds(300)));
Assert.Contains("No data received", error.Message);
Assert.Less((DateTime.UtcNow - started).TotalSeconds, 20);
Assert.FileExists(Path.Combine(root, "v1.0.0", SetupName + ".part"));
}
[Test]
public async Task AnAssetOfUnknownSizeIsStillVerified()
{
var root = context.CreateTempDirectory();
using var http = new HttpClient(new FakeReleases(Setup));
var release = Release() with { Assets = [new ReleaseAsset(SetupName, Base + SetupName, -1), new ReleaseAsset("SHA256SUMS", Base + "SHA256SUMS", -1)] };
var reported = new List<double>();
var path = await UpdateDownload.DownloadAsync(http, release, false, root, "0.1.0", new SyncProgress(reported.Add), Idle, CancellationToken.None);
Assert.SequenceEqual(Setup, await File.ReadAllBytesAsync(path));
Assert.Empty(reported);
}
[Test]
public async Task AVerifiedDownloadRemovesTheFoldersOfOtherReleases()
{
var root = context.CreateTempDirectory();
var old = Directory.CreateDirectory(Path.Combine(root, "v0.9.0")).FullName;
await File.WriteAllTextAsync(Path.Combine(old, "Titano-Setup-0.9.0.exe"), "old setup");
using var http = new HttpClient(new FakeReleases(Setup));
await DownloadAsync(http, root);
Assert.SequenceEqual(new[] { "v1.0.0" }, Directory.GetDirectories(root).Select(d => Path.GetFileName(d)));
}
private static Task<string> DownloadAsync(HttpClient http, string root, bool portable = false, IProgress<double>? progress = null, TimeSpan? idle = null,
CancellationToken ct = default) =>
UpdateDownload.DownloadAsync(http, Release(), portable, root, "0.1.0", progress, idle ?? Idle, ct);
private static ReleaseInfo Release() => new(new Version(1, 0, 0), "v1.0.0", "https://github.com/o/r/releases/tag/v1.0.0")
{
Assets =
[
new ReleaseAsset("Titano-Setup-1.0.0.exe", SetupUrl, Setup.Length),
new ReleaseAsset("SHA256SUMS", SumsUrl, 200),
new ReleaseAsset(SetupName, Base + SetupName, Setup.Length),
new ReleaseAsset(PortableName, Base + PortableName, Portable.Length),
new ReleaseAsset("SHA256SUMS", Base + "SHA256SUMS", 300),
],
};
private static string Sums(byte[] setup) =>
$"{new string('1', 64)} Titano-Uploader-Setup-1.0.0.exe\n{Convert.ToHexStringLower(SHA256.HashData(setup))} Titano-Setup-1.0.0.exe\n";
private static string Sums(byte[] setup, byte[] portable) =>
$"{new string('1', 64)} Titano-Uploader-Setup-1.0.0.exe\n{Hash(setup)} {SetupName}\n{Hash(portable)} *{PortableName}\n";
/// <summary>Serves SHA256SUMS and the setup (null: the setup answers 500).</summary>
private sealed class FakeReleases(string sums, byte[]? setup) : HttpMessageHandler
private static string Hash(byte[] bytes) => Convert.ToHexStringLower(SHA256.HashData(bytes));
/// <summary>
/// Serves SHA256SUMS, the setup and the portable zip like GitHub's release downloads: honours single open-ended
/// ranges, and can fail, end a transfer early or stall in the middle of it.
/// </summary>
private sealed class FakeReleases(byte[] setup) : HttpMessageHandler
{
public int SetupRequests { get; private set; }
public string Sums { get; set; } = UpdateDownloadTests.Sums(setup, Portable);
/// <summary>The setup bytes actually served (tampered or longer ones); the real setup by default.</summary>
public byte[] Served { get; set; } = setup;
public bool Fail { get; set; }
public bool HonourRange { get; set; } = true;
public int? CutAfter { get; set; }
public int? StallAfter { get; set; }
public int PackageRequests => PackageUrls.Count;
public List<string> PackageUrls { get; } = [];
public List<long?> Ranges { get; } = [];
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
Assert.True(request.Headers.UserAgent.ToString().StartsWith("Titano/", StringComparison.Ordinal), "GitHub requires a User-Agent");
var url = request.RequestUri!.AbsoluteUri;
if (url == SumsUrl) return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(sums) });
Assert.Equal(SetupUrl, url);
SetupRequests++;
return Task.FromResult(setup is null
? new HttpResponseMessage(HttpStatusCode.InternalServerError)
: new HttpResponseMessage(HttpStatusCode.OK) { Content = new ByteArrayContent(setup) });
if (url == Base + "SHA256SUMS") return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(Sums) });
var bytes = url == Base + SetupName ? Served : url == Base + PortableName ? Portable : throw new AssertionException("Unexpected request " + url);
PackageUrls.Add(url);
var from = request.Headers.Range?.Ranges.Single().From;
Ranges.Add(from);
if (Fail) return Task.FromResult(new HttpResponseMessage(HttpStatusCode.InternalServerError));
var offset = HonourRange && from is { } start ? (int)start : 0;
var end = CutAfter is { } cut ? System.Math.Min(bytes.Length, offset + cut) : bytes.Length;
var body = new StreamContent(new Body(bytes[offset..end], StallAfter));
var response = new HttpResponseMessage(offset > 0 ? HttpStatusCode.PartialContent : HttpStatusCode.OK) { Content = body };
if (offset > 0) body.Headers.ContentRange = new ContentRangeHeaderValue(offset, bytes.Length - 1, bytes.Length);
return Task.FromResult(response);
}
}
/// <summary>A non-seekable body (no Content-Length) that waits for cancellation once <paramref name="stallAfter"/> bytes are read.</summary>
private sealed class Body(byte[] bytes, int? stallAfter) : Stream
{
private int _position;
public override bool CanRead => true;
public override bool CanSeek => false;
public override bool CanWrite => false;
public override long Length => throw new NotSupportedException();
public override long Position { get => _position; set => throw new NotSupportedException(); }
public override async ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default)
{
if (_position == stallAfter) await Task.Delay(Timeout.Infinite, cancellationToken);
var limit = stallAfter is { } stall && _position < stall ? stall : bytes.Length;
var count = System.Math.Min(buffer.Length, limit - _position);
bytes.AsMemory(_position, count).CopyTo(buffer);
_position += count;
return count;
}
public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) =>
ReadAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask();
public override int Read(byte[] buffer, int offset, int count) => ReadAsync(buffer, offset, count, CancellationToken.None).GetAwaiter().GetResult();
public override void Flush() => throw new NotSupportedException();
public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
public override void SetLength(long value) => throw new NotSupportedException();
public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException();
}
/// <summary>Reports synchronously (<see cref="Progress{T}"/> would post to the thread pool).</summary>
private sealed class SyncProgress(Action<double> report) : IProgress<double>
{
@@ -0,0 +1,208 @@
using System.IO;
using Titano.App.About;
using Titano.Testing;
using Titano.Ui.Mvvm;
namespace Titano.App.Tests.About;
/// <summary>The update notice: start-up opt-out, capture runs, portable copies, failures and cancellation of the download.</summary>
[Serial] // AsyncRelayCommand.Failed is a static event
public sealed class UpdateFlowTests(TestContext context)
{
private const string Page = "https://github.com/o/r/releases/tag/v1.0.0";
[Test]
public async Task TheStartUpCheckFollowsTheOptOut()
{
var host = new Host();
var flow = host.Flow();
Assert.Null(await flow.CheckOnStartAsync(enabled: false));
Assert.Equal(0, host.Checks);
Assert.Equal(UpdateState.Unknown, flow.State);
Assert.Equal("v1.0.0", (await flow.CheckOnStartAsync(enabled: true))?.Tag);
Assert.Equal(1, host.Checks);
Assert.Equal(UpdateState.Available, flow.State);
}
[Test]
public async Task ACaptureRunNeverTouchesTheNetwork()
{
var host = new Host { IsCapture = true };
var flow = host.Flow();
Assert.Null(await flow.CheckOnStartAsync(enabled: true));
Assert.Null(await flow.CheckAsync(CancellationToken.None));
Assert.Equal(0, host.Checks);
flow.SetResult(Release(withSetup: true, withZip: true, withSums: true));
await RunAsync(flow.Download);
Assert.Equal(0, host.Downloads);
Assert.Empty(host.Opened);
}
[Test]
public async Task ADownloadedSetupIsShownAndOfferedUntilANewerReleaseAppears()
{
var host = new Host { Downloaded = Path.Combine(context.CreateTempDirectory(), "Titano-Setup-1.0.0.exe") };
File.WriteAllText(host.Downloaded, "setup");
var flow = host.Flow();
flow.SetResult(Release(withSetup: true, withZip: false, withSums: true));
Assert.Equal("Titano-Setup-1.0.0.exe", flow.Package?.Name);
await RunAsync(flow.Download);
Assert.Equal((UpdateState.Downloaded, host.Downloaded), (flow.State, flow.PackagePath));
Assert.SequenceEqual(new[] { host.Downloaded }, host.Revealed);
Assert.False(flow.IsDownloadOffered);
flow.SetResult(Release(withSetup: true, withZip: false, withSums: true));
Assert.Equal(UpdateState.Downloaded, flow.State);
flow.SetResult(Release(withSetup: true, withZip: false, withSums: true) with { Version = new Version(1, 1, 0), Tag = "v1.1.0" });
Assert.Equal((UpdateState.Available, (string?)null), (flow.State, flow.PackagePath));
}
[Test]
public async Task APortableCopyNeverDownloadsTheSetup()
{
var host = new Host { IsPortable = true };
var flow = host.Flow();
flow.SetResult(Release(withSetup: true, withZip: false, withSums: true));
Assert.Null(flow.Package);
await RunAsync(flow.Download);
Assert.Equal(0, host.Downloads);
Assert.SequenceEqual(new[] { Page }, host.Opened);
flow.SetResult(Release(withSetup: true, withZip: true, withSums: true));
Assert.Equal("Titano-win-x64-portable-1.0.0.zip", flow.Package?.Name);
await RunAsync(flow.Download);
Assert.Equal(1, host.Downloads);
Assert.Equal(UpdateState.Downloaded, flow.State);
}
[Test]
public async Task AReleaseWithoutChecksumsOnlyOpensItsPage()
{
var host = new Host();
var flow = host.Flow();
flow.SetResult(Release(withSetup: true, withZip: true, withSums: false));
await RunAsync(flow.Download);
Assert.Equal(0, host.Downloads);
Assert.SequenceEqual(new[] { Page }, host.Opened);
Assert.Equal(UpdateState.Available, flow.State);
}
[Test]
public async Task ARefusedDownloadIsReportedAndCanBeRetried()
{
var host = new Host { Failure = new UpdateVerificationException("SHA-256 mismatch") };
var flow = host.Flow();
flow.SetResult(Release(withSetup: true, withZip: false, withSums: true));
await RunAsync(flow.Download);
Assert.Equal(UpdateState.NotVerified, flow.State);
Assert.True(flow.IsDownloadOffered);
Assert.True(flow.Download.CanExecute(null));
Assert.True(flow.Check.CanExecute(null));
}
[Test]
public async Task AStalledDownloadFailsAndCanBeRetried()
{
var host = new Host { Failure = new TimeoutException("No data received for 60 s.") };
var flow = host.Flow();
flow.SetResult(Release(withSetup: true, withZip: false, withSums: true));
await RunAsync(flow.Download);
Assert.Equal(UpdateState.DownloadFailed, flow.State);
Assert.True(flow.IsDownloadOffered);
}
[Test]
public async Task AnUnexpectedFailureIsReportedAndNeverLeavesTheNoticeDownloading()
{
var host = new Host { Failure = new UriFormatException("bad asset link") };
var flow = host.Flow();
flow.SetResult(Release(withSetup: true, withZip: false, withSums: true));
var reported = new List<Exception>();
AsyncRelayCommand.Failed += reported.Add;
try
{
await RunAsync(flow.Download);
}
finally
{
AsyncRelayCommand.Failed -= reported.Add;
}
Assert.True(reported.Single() is UriFormatException, reported.Single().GetType().Name);
Assert.Equal(UpdateState.DownloadFailed, flow.State);
Assert.True(flow.Check.CanExecute(null));
Assert.True(flow.Download.CanExecute(null));
}
[Test]
public async Task CancellingADownloadOffersItAgain()
{
var host = new Host { Stall = true };
var flow = host.Flow();
flow.SetResult(Release(withSetup: true, withZip: false, withSums: true));
flow.Download.Execute(null);
await host.Started.Task.WaitAsync(TimeSpan.FromSeconds(10));
Assert.Equal(UpdateState.Downloading, flow.State);
Assert.False(flow.Check.CanExecute(null));
flow.CancelDownload();
await WaitAsync(flow.Download);
Assert.Equal(UpdateState.Available, flow.State);
Assert.True(flow.IsDownloadOffered);
Assert.True(flow.Check.CanExecute(null));
}
private static ReleaseInfo Release(bool withSetup, bool withZip, bool withSums)
{
const string Base = "https://github.com/o/r/releases/download/v1.0.0/";
var assets = new List<ReleaseAsset>();
if (withSetup) assets.Add(new ReleaseAsset("Titano-Setup-1.0.0.exe", Base + "Titano-Setup-1.0.0.exe", 1000));
if (withZip) assets.Add(new ReleaseAsset("Titano-win-x64-portable-1.0.0.zip", Base + "Titano-win-x64-portable-1.0.0.zip", 900));
if (withSums) assets.Add(new ReleaseAsset("SHA256SUMS", Base + "SHA256SUMS", 300));
return new ReleaseInfo(new Version(1, 0, 0), "v1.0.0", Page) { Assets = assets };
}
private static async Task RunAsync(AsyncRelayCommand command)
{
command.Execute(null);
await WaitAsync(command);
}
private static async Task WaitAsync(AsyncRelayCommand command)
{
for (var i = 0; i < 500 && command.IsRunning; i++) await Task.Delay(10);
Assert.False(command.IsRunning, "the command did not finish");
}
private sealed class Host
{
public bool IsCapture { get; init; }
public bool IsPortable { get; init; }
public Exception? Failure { get; init; }
public bool Stall { get; init; }
public string Downloaded { get; init; } = "Titano-Setup-1.0.0.exe";
public int Checks { get; private set; }
public int Downloads { get; private set; }
public List<string> Opened { get; } = [];
public List<string> Revealed { get; } = [];
public TaskCompletionSource Started { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
public UpdateFlow Flow() => new(new UpdateHost(new Version(0, 9, 0), IsCapture, IsPortable,
_ =>
{
Checks++;
return Task.FromResult<ReleaseInfo?>(Release(withSetup: true, withZip: true, withSums: true));
},
async (_, _, ct) =>
{
Downloads++;
Started.TrySetResult();
if (Stall) await Task.Delay(Timeout.Infinite, ct);
await Task.Yield();
return Failure is null ? Downloaded : throw Failure;
},
Opened.Add, Revealed.Add));
}
}