From ca0091c7992dc68ce9f7283209feccefa7c86f3a Mon Sep 17 00:00:00 2001 From: Jack Kendall Date: Sun, 31 May 2026 10:29:58 +0100 Subject: [PATCH 1/2] Centralize test infrastructure helpers --- .../DownloadManagerIntegrationTests.cs | 171 +-------------- Octans.Tests/Downloads/HttpDownloaderTests.cs | 205 +----------------- Octans.Tests/GlobalUsings.cs | 1 + .../Importing/DownloaderFactoryTests.cs | 30 --- .../DownloadManagerHttpMessageHandler.cs | 144 ++++++++++++ .../Infrastructure/DownloadTestContent.cs | 143 ++++++++++++ .../DownloadTestHttpMessageHandler.cs | 42 ++++ .../FakeDownloadDiskSpaceGuard.cs | 26 +++ .../Infrastructure/FakeNavigationManager.cs | 16 ++ .../Infrastructure/OctansClientTests.cs | 23 +- .../SpyChannelWriter.cs | 9 +- .../Infrastructure/StorageServiceTests.cs | 28 --- .../Infrastructure/StubHttpMessageHandler.cs | 60 +++++ .../Infrastructure/ThrowingMockFileSystem.cs | 31 +++ .../TrackingCompletionNotifier.cs | 18 ++ .../Viewmodels/MainToolbarViewmodelTests.cs | 14 -- 16 files changed, 496 insertions(+), 465 deletions(-) create mode 100644 Octans.Tests/Infrastructure/DownloadManagerHttpMessageHandler.cs create mode 100644 Octans.Tests/Infrastructure/DownloadTestContent.cs create mode 100644 Octans.Tests/Infrastructure/DownloadTestHttpMessageHandler.cs create mode 100644 Octans.Tests/Infrastructure/FakeDownloadDiskSpaceGuard.cs create mode 100644 Octans.Tests/Infrastructure/FakeNavigationManager.cs rename Octans.Tests/{Helpers => Infrastructure}/SpyChannelWriter.cs (73%) create mode 100644 Octans.Tests/Infrastructure/StubHttpMessageHandler.cs create mode 100644 Octans.Tests/Infrastructure/ThrowingMockFileSystem.cs create mode 100644 Octans.Tests/Infrastructure/TrackingCompletionNotifier.cs diff --git a/Octans.Tests/Downloads/DownloadManagerIntegrationTests.cs b/Octans.Tests/Downloads/DownloadManagerIntegrationTests.cs index f217954b..3b326812 100644 --- a/Octans.Tests/Downloads/DownloadManagerIntegrationTests.cs +++ b/Octans.Tests/Downloads/DownloadManagerIntegrationTests.cs @@ -1,4 +1,3 @@ -using System.Collections.Concurrent; using System.IO.Abstractions; using System.IO.Abstractions.TestingHelpers; using System.Net; @@ -153,8 +152,8 @@ public async Task DownloadManager_RetriesTransientFailureWithoutRetryingTerminal await harness.StartAsync(); await WaitUntilAsync( - () => harness.Notifier.FinishedDownloads.Length == 2, - () => Task.FromResult($"completed={harness.Notifier.FinishedDownloads.Length}, " + + () => harness.Notifier.FinishedDownloads.Count == 2, + () => Task.FromResult($"completed={harness.Notifier.FinishedDownloads.Count}, " + $"states={DescribeStates(harness.Services, transient, terminal)}")); var stateService = harness.Services.GetRequiredService(); @@ -241,8 +240,8 @@ public async Task DownloadManager_EnforcesPerDomainConcurrencyWhileDrainingQueue harness.HttpHandler.ReleaseResponses(); await WaitUntilAsync( - () => harness.Notifier.FinishedDownloads.Length == 3, - async () => $"completed={harness.Notifier.FinishedDownloads.Length}, " + + () => harness.Notifier.FinishedDownloads.Count == 3, + async () => $"completed={harness.Notifier.FinishedDownloads.Count}, " + $"started={string.Join(", ", harness.HttpHandler.StartedRequests.Select(u => u.ToString()))}, " + $"states={DescribeStates(harness.Services, firstSame, secondSame, other)}, " + $"queued={await harness.Services.GetRequiredService().GetQueuedCountAsync()}"); @@ -285,7 +284,7 @@ public async Task DownloadManager_SkipsOpenHostCircuitAndContinuesHealthyHosts() await WaitUntilAsync( () => harness.Notifier.FinishedDownloads.Any(d => d.DownloadId == deferred), - async () => $"completed={harness.Notifier.FinishedDownloads.Length}, " + + async () => $"completed={harness.Notifier.FinishedDownloads.Count}, " + $"started={string.Join(", ", harness.HttpHandler.StartedRequests.Select(u => u.ToString()))}, " + $"states={DescribeStates(harness.Services, deferred, ready)}, " + $"queued={await harness.Services.GetRequiredService().GetQueuedCountAsync()}"); @@ -382,7 +381,7 @@ private DownloadManagerHarness( SqliteConnection connection, ServiceProvider services, MockFileSystem fileSystem, - IntegrationHttpMessageHandler httpHandler, + DownloadManagerHttpMessageHandler httpHandler, TrackingCompletionNotifier notifier) { _connection = connection; @@ -394,7 +393,7 @@ private DownloadManagerHarness( public ServiceProvider Services { get; } public MockFileSystem FileSystem { get; } - public IntegrationHttpMessageHandler HttpHandler { get; } + public DownloadManagerHttpMessageHandler HttpHandler { get; } public TrackingCompletionNotifier Notifier { get; } public IDownloadHostCircuitRegistry HostCircuitRegistry => Services.GetRequiredService(); @@ -415,7 +414,7 @@ public static async Task Create( TotalFreeSpace = 1024 * 1024 * 1024, TotalSize = 1024L * 1024 * 1024 * 10 }); - var httpHandler = new IntegrationHttpMessageHandler(); + var httpHandler = new DownloadManagerHttpMessageHandler(); var notifier = new TrackingCompletionNotifier(); var timeProvider = new FakeTimeProvider(TestClock.UtcNow); @@ -464,158 +463,4 @@ public async ValueTask DisposeAsync() Services.GetServices().OfType().Single(); } - private sealed class TrackingCompletionNotifier : IDownloadCompletionNotifier - { - private readonly ConcurrentQueue _finishedDownloads = new(); - - public DownloadJobResult[] FinishedDownloads => _finishedDownloads.ToArray(); - - public Task DownloadFinishedAsync(DownloadJobResult result, CancellationToken cancellationToken = default) - { - _finishedDownloads.Enqueue(result); - return Task.CompletedTask; - } - } - - private sealed class IntegrationHttpMessageHandler : HttpMessageHandler - { - private readonly Lock _lock = new(); - private readonly Dictionary _responses = new(); - private readonly Dictionary>> _responseSequences = new(); - private readonly Dictionary _requestCounts = new(); - private readonly Dictionary _activeRequestsByHost = new(StringComparer.OrdinalIgnoreCase); - private readonly Dictionary _maxActiveRequestsByHost = new(StringComparer.OrdinalIgnoreCase); - private readonly HashSet _startedRequests = []; - private readonly TaskCompletionSource _releaseResponses = - new(TaskCreationOptions.RunContinuationsAsynchronously); - - public bool PauseBeforeResponding { get; set; } - - public int ActiveRequestCount - { - get - { - lock (_lock) - { - return _activeRequestCount; - } - } - } - - private int _activeRequestCount; - - public IReadOnlyCollection StartedRequests - { - get - { - lock (_lock) - { - return _startedRequests.ToArray(); - } - } - } - - public void AddResponse(string url, string body) - { - _responses[new(url)] = System.Text.Encoding.UTF8.GetBytes(body); - } - - public void AddResponse(string url, HttpStatusCode statusCode) - { - AddResponseSequence(url, () => new(statusCode)); - } - - public void AddResponseSequence(string url, params Func[] responses) - { - _responseSequences[new(url)] = new(responses); - } - - public int MaxActiveRequestsForHost(string host) - { - lock (_lock) - { - return _maxActiveRequestsByHost.GetValueOrDefault(host); - } - } - - public int RequestCountFor(Uri uri) - { - lock (_lock) - { - return _requestCounts.GetValueOrDefault(uri); - } - } - - public void ReleaseResponses() - { - _releaseResponses.TrySetResult(); - } - - protected override async Task SendAsync( - HttpRequestMessage request, - CancellationToken cancellationToken) - { - var requestUri = request.RequestUri ?? throw new InvalidOperationException("Request URI is required."); - TrackRequestStarted(requestUri); - - try - { - if (PauseBeforeResponding) - { - await _releaseResponses.Task.WaitAsync(cancellationToken); - } - - if (!_responses.TryGetValue(requestUri, out var body)) - { - if (_responseSequences.TryGetValue(requestUri, out var sequence) && sequence.TryDequeue(out var next)) - { - return next(); - } - - return new(HttpStatusCode.NotFound); - } - - return new(HttpStatusCode.OK) - { - Content = new ByteArrayContent(body) - }; - } - finally - { - TrackRequestFinished(requestUri.Host); - } - } - - private void TrackRequestStarted(Uri requestUri) - { - lock (_lock) - { - _activeRequestCount++; - _requestCounts.TryGetValue(requestUri, out var requestCount); - _requestCounts[requestUri] = requestCount + 1; - _startedRequests.Add(requestUri); - _activeRequestsByHost.TryGetValue(requestUri.Host, out var hostCount); - hostCount++; - _activeRequestsByHost[requestUri.Host] = hostCount; - _maxActiveRequestsByHost.TryGetValue(requestUri.Host, out var maxHostCount); - _maxActiveRequestsByHost[requestUri.Host] = Math.Max(maxHostCount, hostCount); - } - } - - private void TrackRequestFinished(string host) - { - lock (_lock) - { - _activeRequestCount--; - _activeRequestsByHost.TryGetValue(host, out var hostCount); - if (hostCount <= 1) - { - _activeRequestsByHost.Remove(host); - return; - } - - _activeRequestsByHost[host] = hostCount - 1; - } - } - } } diff --git a/Octans.Tests/Downloads/HttpDownloaderTests.cs b/Octans.Tests/Downloads/HttpDownloaderTests.cs index c9798847..5aee63a9 100644 --- a/Octans.Tests/Downloads/HttpDownloaderTests.cs +++ b/Octans.Tests/Downloads/HttpDownloaderTests.cs @@ -1,6 +1,5 @@ -using System.IO.Abstractions.TestingHelpers; -using System.Collections.ObjectModel; using System.Net; +using System.IO.Abstractions.TestingHelpers; using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Options; using Microsoft.Extensions.Time.Testing; @@ -26,7 +25,7 @@ public class HttpDownloaderTests private readonly DownloadTelemetry _telemetry = new(); private readonly HttpDownloader _sut; private readonly CancellationTokenSource _cts = new(); - private readonly TestHttpMessageHandler _messageHandler = new(); + private readonly DownloadTestHttpMessageHandler _messageHandler = new(); public HttpDownloaderTests() { @@ -836,203 +835,3 @@ private string GetStagingPath(Guid downloadId, string destinationPath) return _fileSystem.Path.Combine(destinationDirectory, ".octans-downloads", $"{downloadId}.part"); } } - -public sealed class FakeDownloadDiskSpaceGuard : IDownloadDiskSpaceGuard -{ - public long? FailWhenBytesNeededAtLeast { get; set; } - public bool FailNextCheck { get; set; } - public int CheckCount { get; private set; } - - public void EnsureSufficientSpace(string destinationPath, long bytesNeeded) - { - CheckCount++; - - if (FailNextCheck) - { - FailNextCheck = false; - throw new DownloadDiskSpaceException("Insufficient free space for download."); - } - - if (FailWhenBytesNeededAtLeast is { } threshold && bytesNeeded >= threshold) - { - throw new DownloadDiskSpaceException("Insufficient free space for download."); - } - } -} - -public class TestHttpMessageHandler : HttpMessageHandler -{ - public HttpResponseMessage? ResponseToReturn { get; set; } - public Exception? ExceptionToThrow { get; set; } - public TimeSpan DelayBeforeResponse { get; set; } = TimeSpan.Zero; - public bool WaitForCancellation { get; set; } - public TaskCompletionSource RequestStarted { get; } = - new(TaskCreationOptions.RunContinuationsAsynchronously); - public Collection Requests { get; } = []; - - protected override async Task SendAsync( - HttpRequestMessage request, - CancellationToken cancellationToken) - { - Requests.Add(request); - RequestStarted.TrySetResult(); - - if (WaitForCancellation) - { - await Task.Delay(Timeout.InfiniteTimeSpan, cancellationToken); - } - - if (DelayBeforeResponse > TimeSpan.Zero) - { - await Task.Delay(DelayBeforeResponse, cancellationToken); - } - - cancellationToken.ThrowIfCancellationRequested(); - - if (ExceptionToThrow != null) - { - throw ExceptionToThrow; - } - - return ResponseToReturn ?? new HttpResponseMessage(HttpStatusCode.OK); - } -} - -public sealed class PausingReadContent : StreamContent -{ - private readonly PausingReadStream _stream; - - public PausingReadContent(string body) : this(new PausingReadStream(body)) - { - } - - private PausingReadContent(PausingReadStream stream) : base(stream) - { - _stream = stream; - } - - public TaskCompletionSource SecondReadStarted => _stream.SecondReadStarted; - public bool ThrowOnSecondRead - { - get => _stream.ThrowOnSecondRead; - set => _stream.ThrowOnSecondRead = value; - } - - public void ReleaseSecondRead() - { - _stream.ReleaseSecondRead(); - } -} - -public sealed class PausingReadStream(string body) : Stream -{ - private readonly byte[] _bytes = System.Text.Encoding.UTF8.GetBytes(body); - private readonly TaskCompletionSource _continueSecondRead = - new(TaskCreationOptions.RunContinuationsAsynchronously); - private int _position; - private bool _secondReadStarted; - - public TaskCompletionSource SecondReadStarted { get; } = - new(TaskCreationOptions.RunContinuationsAsynchronously); - - public bool ThrowOnSecondRead { get; set; } - - public override bool CanRead => true; - public override bool CanSeek => false; - public override bool CanWrite => false; - public override long Length => _bytes.Length; - - public override long Position - { - get => _position; - set => throw new NotSupportedException(); - } - - public override void Flush() - { - } - - public override int Read(byte[] buffer, int offset, int count) - { - throw new NotSupportedException(); - } - - public override async ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) - { - if (_position >= _bytes.Length) - { - return 0; - } - - if (_position == 0) - { - var firstChunkLength = Math.Min(2, _bytes.Length); - _bytes.AsMemory(0, firstChunkLength).CopyTo(buffer); - _position += firstChunkLength; - return firstChunkLength; - } - - if (!_secondReadStarted) - { - _secondReadStarted = true; - SecondReadStarted.TrySetResult(); - - if (ThrowOnSecondRead) - { - throw new IOException("stream failed after partial body write"); - } - - await _continueSecondRead.Task.WaitAsync(cancellationToken); - } - - var bytesRemaining = _bytes.Length - _position; - var bytesToRead = Math.Min(buffer.Length, bytesRemaining); - _bytes.AsMemory(_position, bytesToRead).CopyTo(buffer); - _position += bytesToRead; - - return bytesToRead; - } - - public override Task ReadAsync( - byte[] buffer, - int offset, - int count, - CancellationToken cancellationToken) - { - return ReadAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask(); - } - - 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(); - } - - public void ReleaseSecondRead() - { - _continueSecondRead.TrySetResult(); - } -} - -public sealed class UnknownLengthContent(byte[] body) : HttpContent -{ - protected override Task SerializeToStreamAsync(Stream stream, TransportContext? context) - { - return stream.WriteAsync(body).AsTask(); - } - - protected override bool TryComputeLength(out long length) - { - length = 0; - return false; - } -} diff --git a/Octans.Tests/GlobalUsings.cs b/Octans.Tests/GlobalUsings.cs index 71e49d2a..c937e3ef 100644 --- a/Octans.Tests/GlobalUsings.cs +++ b/Octans.Tests/GlobalUsings.cs @@ -1,2 +1,3 @@ global using Octans.Tests; +global using Octans.Tests.Infrastructure; global using Xunit; diff --git a/Octans.Tests/Importing/DownloaderFactoryTests.cs b/Octans.Tests/Importing/DownloaderFactoryTests.cs index 9ad341b8..60bb12f0 100644 --- a/Octans.Tests/Importing/DownloaderFactoryTests.cs +++ b/Octans.Tests/Importing/DownloaderFactoryTests.cs @@ -319,34 +319,4 @@ private DownloaderService CreateService( Options.Create(resolverOptions ?? new DownloaderResolverOptions()), NullLogger.Instance); - private sealed class StaticHttpMessageHandler(string content) : HttpMessageHandler - { - protected override Task SendAsync( - HttpRequestMessage request, - CancellationToken cancellationToken) => - Task.FromResult(new HttpResponseMessage - { - Content = new StringContent(content) - }); - } - - private sealed class CancellableHttpMessageHandler : HttpMessageHandler - { - private readonly TaskCompletionSource _started = new(TaskCreationOptions.RunContinuationsAsynchronously); - - public Task WaitUntilStarted() => _started.Task.WaitAsync(TimeSpan.FromSeconds(5)); - - protected override async Task SendAsync( - HttpRequestMessage request, - CancellationToken cancellationToken) - { - _started.SetResult(); - await Task.Delay(TimeSpan.FromMinutes(1), cancellationToken); - - return new() - { - Content = new StringContent("") - }; - } - } } diff --git a/Octans.Tests/Infrastructure/DownloadManagerHttpMessageHandler.cs b/Octans.Tests/Infrastructure/DownloadManagerHttpMessageHandler.cs new file mode 100644 index 00000000..3423a958 --- /dev/null +++ b/Octans.Tests/Infrastructure/DownloadManagerHttpMessageHandler.cs @@ -0,0 +1,144 @@ +using System.Net; + +namespace Octans.Tests.Infrastructure; + +internal sealed class DownloadManagerHttpMessageHandler : HttpMessageHandler +{ + private readonly Lock _lock = new(); + private readonly Dictionary _responses = new(); + private readonly Dictionary>> _responseSequences = new(); + private readonly Dictionary _requestCounts = new(); + private readonly Dictionary _activeRequestsByHost = new(StringComparer.OrdinalIgnoreCase); + private readonly Dictionary _maxActiveRequestsByHost = new(StringComparer.OrdinalIgnoreCase); + private readonly HashSet _startedRequests = []; + private readonly TaskCompletionSource _releaseResponses = + new(TaskCreationOptions.RunContinuationsAsynchronously); + private int _activeRequestCount; + + public bool PauseBeforeResponding { get; set; } + + public int ActiveRequestCount + { + get + { + lock (_lock) + { + return _activeRequestCount; + } + } + } + + public IReadOnlyCollection StartedRequests + { + get + { + lock (_lock) + { + return _startedRequests.ToArray(); + } + } + } + + public void AddResponse(string url, string body) + { + _responses[new(url)] = System.Text.Encoding.UTF8.GetBytes(body); + } + + public void AddResponse(string url, HttpStatusCode statusCode) + { + AddResponseSequence(url, () => new(statusCode)); + } + + public void AddResponseSequence(string url, params Func[] responses) + { + _responseSequences[new(url)] = new(responses); + } + + public int MaxActiveRequestsForHost(string host) + { + lock (_lock) + { + return _maxActiveRequestsByHost.GetValueOrDefault(host); + } + } + + public int RequestCountFor(Uri uri) + { + lock (_lock) + { + return _requestCounts.GetValueOrDefault(uri); + } + } + + public void ReleaseResponses() + { + _releaseResponses.TrySetResult(); + } + + protected override async Task SendAsync( + HttpRequestMessage request, + CancellationToken cancellationToken) + { + var requestUri = request.RequestUri ?? throw new InvalidOperationException("Request URI is required."); + TrackRequestStarted(requestUri); + + try + { + if (PauseBeforeResponding) + { + await _releaseResponses.Task.WaitAsync(cancellationToken); + } + + if (!_responses.TryGetValue(requestUri, out var body)) + { + if (_responseSequences.TryGetValue(requestUri, out var sequence) && sequence.TryDequeue(out var next)) + { + return next(); + } + + return new(HttpStatusCode.NotFound); + } + + return new(HttpStatusCode.OK) + { + Content = new ByteArrayContent(body) + }; + } + finally + { + TrackRequestFinished(requestUri.Host); + } + } + + private void TrackRequestStarted(Uri requestUri) + { + lock (_lock) + { + _activeRequestCount++; + _requestCounts.TryGetValue(requestUri, out var requestCount); + _requestCounts[requestUri] = requestCount + 1; + _startedRequests.Add(requestUri); + _activeRequestsByHost.TryGetValue(requestUri.Host, out var hostCount); + hostCount++; + _activeRequestsByHost[requestUri.Host] = hostCount; + _maxActiveRequestsByHost.TryGetValue(requestUri.Host, out var maxHostCount); + _maxActiveRequestsByHost[requestUri.Host] = Math.Max(maxHostCount, hostCount); + } + } + + private void TrackRequestFinished(string host) + { + lock (_lock) + { + _activeRequestCount--; + _activeRequestsByHost.TryGetValue(host, out var hostCount); + if (hostCount <= 1) + { + _activeRequestsByHost.Remove(host); + return; + } + + _activeRequestsByHost[host] = hostCount - 1; + } + } +} diff --git a/Octans.Tests/Infrastructure/DownloadTestContent.cs b/Octans.Tests/Infrastructure/DownloadTestContent.cs new file mode 100644 index 00000000..dc7c1e9f --- /dev/null +++ b/Octans.Tests/Infrastructure/DownloadTestContent.cs @@ -0,0 +1,143 @@ +using System.Net; + +namespace Octans.Tests.Infrastructure; + +internal sealed class PausingReadContent : StreamContent +{ + private readonly PausingReadStream _stream; + + public PausingReadContent(string body) : this(new PausingReadStream(body)) + { + } + + private PausingReadContent(PausingReadStream stream) : base(stream) + { + _stream = stream; + } + + public TaskCompletionSource SecondReadStarted => _stream.SecondReadStarted; + + public bool ThrowOnSecondRead + { + get => _stream.ThrowOnSecondRead; + set => _stream.ThrowOnSecondRead = value; + } + + public void ReleaseSecondRead() + { + _stream.ReleaseSecondRead(); + } +} + +internal sealed class PausingReadStream(string body) : Stream +{ + private readonly byte[] _bytes = System.Text.Encoding.UTF8.GetBytes(body); + private readonly TaskCompletionSource _continueSecondRead = + new(TaskCreationOptions.RunContinuationsAsynchronously); + private int _position; + private bool _secondReadStarted; + + public TaskCompletionSource SecondReadStarted { get; } = + new(TaskCreationOptions.RunContinuationsAsynchronously); + + public bool ThrowOnSecondRead { get; set; } + + public override bool CanRead => true; + public override bool CanSeek => false; + public override bool CanWrite => false; + public override long Length => _bytes.Length; + + public override long Position + { + get => _position; + set => throw new NotSupportedException(); + } + + public override void Flush() + { + } + + public override int Read(byte[] buffer, int offset, int count) + { + throw new NotSupportedException(); + } + + public override async ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) + { + if (_position >= _bytes.Length) + { + return 0; + } + + if (_position == 0) + { + var firstChunkLength = Math.Min(2, _bytes.Length); + _bytes.AsMemory(0, firstChunkLength).CopyTo(buffer); + _position += firstChunkLength; + return firstChunkLength; + } + + if (!_secondReadStarted) + { + _secondReadStarted = true; + SecondReadStarted.TrySetResult(); + + if (ThrowOnSecondRead) + { + throw new IOException("stream failed after partial body write"); + } + + await _continueSecondRead.Task.WaitAsync(cancellationToken); + } + + var bytesRemaining = _bytes.Length - _position; + var bytesToRead = Math.Min(buffer.Length, bytesRemaining); + _bytes.AsMemory(_position, bytesToRead).CopyTo(buffer); + _position += bytesToRead; + + return bytesToRead; + } + + public override Task ReadAsync( + byte[] buffer, + int offset, + int count, + CancellationToken cancellationToken) + { + return ReadAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask(); + } + + 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(); + } + + public void ReleaseSecondRead() + { + _continueSecondRead.TrySetResult(); + } +} + +internal sealed class UnknownLengthContent(byte[] body) : HttpContent +{ + protected override Task SerializeToStreamAsync(Stream stream, TransportContext? context) + { + return stream.WriteAsync(body).AsTask(); + } + + protected override bool TryComputeLength(out long length) + { + length = 0; + return false; + } +} diff --git a/Octans.Tests/Infrastructure/DownloadTestHttpMessageHandler.cs b/Octans.Tests/Infrastructure/DownloadTestHttpMessageHandler.cs new file mode 100644 index 00000000..b0631321 --- /dev/null +++ b/Octans.Tests/Infrastructure/DownloadTestHttpMessageHandler.cs @@ -0,0 +1,42 @@ +using System.Collections.ObjectModel; +using System.Net; + +namespace Octans.Tests.Infrastructure; + +internal sealed class DownloadTestHttpMessageHandler : HttpMessageHandler +{ + public HttpResponseMessage? ResponseToReturn { get; set; } + public Exception? ExceptionToThrow { get; set; } + public TimeSpan DelayBeforeResponse { get; set; } = TimeSpan.Zero; + public bool WaitForCancellation { get; set; } + public TaskCompletionSource RequestStarted { get; } = + new(TaskCreationOptions.RunContinuationsAsynchronously); + public Collection Requests { get; } = []; + + protected override async Task SendAsync( + HttpRequestMessage request, + CancellationToken cancellationToken) + { + Requests.Add(request); + RequestStarted.TrySetResult(); + + if (WaitForCancellation) + { + await Task.Delay(Timeout.InfiniteTimeSpan, cancellationToken); + } + + if (DelayBeforeResponse > TimeSpan.Zero) + { + await Task.Delay(DelayBeforeResponse, cancellationToken); + } + + cancellationToken.ThrowIfCancellationRequested(); + + if (ExceptionToThrow != null) + { + throw ExceptionToThrow; + } + + return ResponseToReturn ?? new HttpResponseMessage(HttpStatusCode.OK); + } +} diff --git a/Octans.Tests/Infrastructure/FakeDownloadDiskSpaceGuard.cs b/Octans.Tests/Infrastructure/FakeDownloadDiskSpaceGuard.cs new file mode 100644 index 00000000..5971bad7 --- /dev/null +++ b/Octans.Tests/Infrastructure/FakeDownloadDiskSpaceGuard.cs @@ -0,0 +1,26 @@ +using Octans.Core.Http; + +namespace Octans.Tests.Infrastructure; + +internal sealed class FakeDownloadDiskSpaceGuard : IDownloadDiskSpaceGuard +{ + public long? FailWhenBytesNeededAtLeast { get; set; } + public bool FailNextCheck { get; set; } + public int CheckCount { get; private set; } + + public void EnsureSufficientSpace(string destinationPath, long bytesNeeded) + { + CheckCount++; + + if (FailNextCheck) + { + FailNextCheck = false; + throw new DownloadDiskSpaceException("Insufficient free space for download."); + } + + if (FailWhenBytesNeededAtLeast is { } threshold && bytesNeeded >= threshold) + { + throw new DownloadDiskSpaceException("Insufficient free space for download."); + } + } +} diff --git a/Octans.Tests/Infrastructure/FakeNavigationManager.cs b/Octans.Tests/Infrastructure/FakeNavigationManager.cs new file mode 100644 index 00000000..68b8bae1 --- /dev/null +++ b/Octans.Tests/Infrastructure/FakeNavigationManager.cs @@ -0,0 +1,16 @@ +using Microsoft.AspNetCore.Components; + +namespace Octans.Tests.Infrastructure; + +internal sealed class FakeNavigationManager : NavigationManager +{ + public FakeNavigationManager() + { + Initialize("http://localhost/", "http://localhost/"); + } + + protected override void NavigateToCore(string uri, bool forceLoad) + { + Uri = ToAbsoluteUri(uri).ToString(); + } +} diff --git a/Octans.Tests/Infrastructure/OctansClientTests.cs b/Octans.Tests/Infrastructure/OctansClientTests.cs index 887482d8..0ece9b95 100644 --- a/Octans.Tests/Infrastructure/OctansClientTests.cs +++ b/Octans.Tests/Infrastructure/OctansClientTests.cs @@ -1,5 +1,3 @@ -using System.Net; -using System.Text; using FluentAssertions; using Microsoft.Extensions.DependencyInjection; using Octans.Client; @@ -19,7 +17,7 @@ public async Task AddOctansClient_RegistersTypedClient() .Should() .Be(new Uri("https://octans.test/version")); - return JsonResponse("""{"version":"1.2.3"}"""); + return StubHttpResponses.Json("""{"version":"1.2.3"}"""); }); var services = new ServiceCollection(); @@ -48,7 +46,7 @@ public async Task QueryFilesAsync_PostsQueriesToEndpoint() { observedRequest = request; - return JsonResponse("""[{"id":7,"hash":"AQID"}]"""); + return StubHttpResponses.Json("""[{"id":7,"hash":"AQID"}]"""); }); var httpClient = new HttpClient(handler) @@ -104,21 +102,4 @@ public void GetMediaUrl_NormalizesHashUrl() .Be("/media/DEADBEEF"); } - private static HttpResponseMessage JsonResponse(string content) - { - return new(HttpStatusCode.OK) - { - Content = new StringContent(content, Encoding.UTF8, "application/json") - }; - } - - private sealed class StubHttpMessageHandler(Func respond) : HttpMessageHandler - { - protected override Task SendAsync( - HttpRequestMessage request, - CancellationToken cancellationToken) - { - return Task.FromResult(respond(request)); - } - } } diff --git a/Octans.Tests/Helpers/SpyChannelWriter.cs b/Octans.Tests/Infrastructure/SpyChannelWriter.cs similarity index 73% rename from Octans.Tests/Helpers/SpyChannelWriter.cs rename to Octans.Tests/Infrastructure/SpyChannelWriter.cs index 5688d58b..48c962b8 100644 --- a/Octans.Tests/Helpers/SpyChannelWriter.cs +++ b/Octans.Tests/Infrastructure/SpyChannelWriter.cs @@ -1,12 +1,9 @@ using System.Collections.ObjectModel; using System.Threading.Channels; -namespace Octans.Tests.Helpers; +namespace Octans.Tests.Infrastructure; -/// -/// Channel that lets us see what items are written to it for the sake of testing. -/// -public sealed class SpyChannelWriter : ChannelWriter +internal sealed class SpyChannelWriter : ChannelWriter { public Channel Channel { get; } = System.Threading.Channels.Channel.CreateUnbounded(); public ICollection WrittenItems { get; } = new Collection(); @@ -22,4 +19,4 @@ public override ValueTask WaitToWriteAsync(CancellationToken cancellationT { return Channel.Writer.WaitToWriteAsync(cancellationToken); } -} \ No newline at end of file +} diff --git a/Octans.Tests/Infrastructure/StorageServiceTests.cs b/Octans.Tests/Infrastructure/StorageServiceTests.cs index b32fee20..ff0448cd 100644 --- a/Octans.Tests/Infrastructure/StorageServiceTests.cs +++ b/Octans.Tests/Infrastructure/StorageServiceTests.cs @@ -149,32 +149,4 @@ public void GetStorageUsed_ExceptionThrown_ReturnsUnknown() Assert.Equal("Unknown", result); } - // Helper class that throws exceptions for testing error handling - private sealed class ThrowingMockFileSystem : IFileSystem - { - public IFile File => throw new FakeIoException("Test exception"); - public IDirectory Directory => throw new FakeIoException("Test exception"); - public IFileInfoFactory FileInfo => throw new FakeIoException("Test exception"); - public IFileVersionInfoFactory FileVersionInfo => throw new FakeIoException("Test exception"); - public IFileStreamFactory FileStream => throw new FakeIoException("Test exception"); - public IPath Path => throw new FakeIoException("Test exception"); - public IDirectoryInfoFactory DirectoryInfo => throw new FakeIoException("Test exception"); - public IDriveInfoFactory DriveInfo => throw new FakeIoException("Test exception"); - public IFileSystemWatcherFactory FileSystemWatcher => throw new FakeIoException("Test exception"); - } - - private sealed class FakeIoException : Exception - { - public FakeIoException(string message) : base(message) - { - } - - public FakeIoException() - { - } - - public FakeIoException(string message, Exception innerException) : base(message, innerException) - { - } - } } diff --git a/Octans.Tests/Infrastructure/StubHttpMessageHandler.cs b/Octans.Tests/Infrastructure/StubHttpMessageHandler.cs new file mode 100644 index 00000000..c24909fd --- /dev/null +++ b/Octans.Tests/Infrastructure/StubHttpMessageHandler.cs @@ -0,0 +1,60 @@ +using System.Net; +using System.Text; + +namespace Octans.Tests.Infrastructure; + +internal sealed class StubHttpMessageHandler(Func> respond) + : HttpMessageHandler +{ + public StubHttpMessageHandler(Func respond) + : this((request, _) => Task.FromResult(respond(request))) + { + } + + protected override Task SendAsync( + HttpRequestMessage request, + CancellationToken cancellationToken) => + respond(request, cancellationToken); +} + +internal sealed class StaticHttpMessageHandler(string content) : HttpMessageHandler +{ + protected override Task SendAsync( + HttpRequestMessage request, + CancellationToken cancellationToken) => + Task.FromResult(new HttpResponseMessage + { + Content = new StringContent(content) + }); +} + +internal sealed class CancellableHttpMessageHandler : HttpMessageHandler +{ + private readonly TaskCompletionSource _started = new(TaskCreationOptions.RunContinuationsAsynchronously); + + public Task WaitUntilStarted() => _started.Task.WaitAsync(TimeSpan.FromSeconds(5)); + + protected override async Task SendAsync( + HttpRequestMessage request, + CancellationToken cancellationToken) + { + _started.SetResult(); + await Task.Delay(TimeSpan.FromMinutes(1), cancellationToken); + + return new() + { + Content = new StringContent("") + }; + } +} + +internal static class StubHttpResponses +{ + public static HttpResponseMessage Json(string content) + { + return new(HttpStatusCode.OK) + { + Content = new StringContent(content, Encoding.UTF8, "application/json") + }; + } +} diff --git a/Octans.Tests/Infrastructure/ThrowingMockFileSystem.cs b/Octans.Tests/Infrastructure/ThrowingMockFileSystem.cs new file mode 100644 index 00000000..b58e9082 --- /dev/null +++ b/Octans.Tests/Infrastructure/ThrowingMockFileSystem.cs @@ -0,0 +1,31 @@ +using System.IO.Abstractions; + +namespace Octans.Tests.Infrastructure; + +internal sealed class ThrowingMockFileSystem : IFileSystem +{ + public IFile File => throw new FakeIoException("Test exception"); + public IDirectory Directory => throw new FakeIoException("Test exception"); + public IFileInfoFactory FileInfo => throw new FakeIoException("Test exception"); + public IFileVersionInfoFactory FileVersionInfo => throw new FakeIoException("Test exception"); + public IFileStreamFactory FileStream => throw new FakeIoException("Test exception"); + public IPath Path => throw new FakeIoException("Test exception"); + public IDirectoryInfoFactory DirectoryInfo => throw new FakeIoException("Test exception"); + public IDriveInfoFactory DriveInfo => throw new FakeIoException("Test exception"); + public IFileSystemWatcherFactory FileSystemWatcher => throw new FakeIoException("Test exception"); +} + +internal sealed class FakeIoException : Exception +{ + public FakeIoException(string message) : base(message) + { + } + + public FakeIoException() + { + } + + public FakeIoException(string message, Exception innerException) : base(message, innerException) + { + } +} diff --git a/Octans.Tests/Infrastructure/TrackingCompletionNotifier.cs b/Octans.Tests/Infrastructure/TrackingCompletionNotifier.cs new file mode 100644 index 00000000..7ede9570 --- /dev/null +++ b/Octans.Tests/Infrastructure/TrackingCompletionNotifier.cs @@ -0,0 +1,18 @@ +using System.Collections.Concurrent; +using Octans.Core.Http; +using Octans.Core.Http.Models; + +namespace Octans.Tests.Infrastructure; + +internal sealed class TrackingCompletionNotifier : IDownloadCompletionNotifier +{ + private readonly ConcurrentQueue _finishedDownloads = new(); + + public IReadOnlyCollection FinishedDownloads => _finishedDownloads.ToArray(); + + public Task DownloadFinishedAsync(DownloadJobResult result, CancellationToken cancellationToken = default) + { + _finishedDownloads.Enqueue(result); + return Task.CompletedTask; + } +} diff --git a/Octans.Tests/Viewmodels/MainToolbarViewmodelTests.cs b/Octans.Tests/Viewmodels/MainToolbarViewmodelTests.cs index 9035fbbc..e14013aa 100644 --- a/Octans.Tests/Viewmodels/MainToolbarViewmodelTests.cs +++ b/Octans.Tests/Viewmodels/MainToolbarViewmodelTests.cs @@ -1,5 +1,4 @@ using FluentAssertions; -using Microsoft.AspNetCore.Components; using Octans.Client.Components.MainToolbar; namespace Octans.Tests.Viewmodels; @@ -33,17 +32,4 @@ public async Task Navigate_ShouldNavigateToCorrectUrl(Page page, string expected // Assert _navigationManager.Uri.Should().EndWith(expectedUrl); } - - private sealed class FakeNavigationManager : NavigationManager - { - public FakeNavigationManager() - { - Initialize("http://localhost/", "http://localhost/"); - } - - protected override void NavigateToCore(string uri, bool forceLoad) - { - Uri = ToAbsoluteUri(uri).ToString(); - } - } } From 6f01ddb03d90972fdd451344060e7fb058808e5b Mon Sep 17 00:00:00 2001 From: Jack Kendall Date: Sun, 31 May 2026 10:32:17 +0100 Subject: [PATCH 2/2] Document GitHub connector preference --- AGENTS.md | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/AGENTS.md b/AGENTS.md index 9644e769..864ccc2b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -49,6 +49,11 @@ I'm toying with a React frontend instead for simplicity, hence the currently not Use standard `dotnet build` and `dotnet test` to verify your work. +## GitHub + +Use the GitHub connector for GitHub operations such as opening PRs, reading PR metadata, and commenting. +Do not assume `gh` is installed; use the CLI only as a fallback when the connector cannot perform the task. + ## Migrations For EF migrations, use the data project as both the project and startup project so the design-time factory is used: @@ -75,4 +80,4 @@ Use collection expressions where appropriate. They are a new C# feature that loo private readonly List _foo = []; private readonly List _foo2 = ["test"]; var item1 = new HashItem { Hash = [1], PerceptualHash = 0 }; -``` \ No newline at end of file +```