From 4f0d37a7586d544de72196aea7c00ae36fb132ae Mon Sep 17 00:00:00 2001 From: Jack Kendall Date: Sun, 31 May 2026 14:01:06 +0100 Subject: [PATCH] Proper API tests --- Octans.Client/Program.cs | 9 +- Octans.Client/ServiceCollectionExtensions.cs | 6 +- Octans.Core/Http/DownloadServiceExtensions.cs | 13 ++- Octans.Core/ServiceCollectionExtensions.cs | 60 ++++++++++-- .../Infrastructure/OctansApiFactory.cs | 98 +++++++++++++++++++ .../Infrastructure/OctansApiFactoryTests.cs | 48 +++++++++ 6 files changed, 218 insertions(+), 16 deletions(-) create mode 100644 Octans.Tests/Infrastructure/OctansApiFactory.cs create mode 100644 Octans.Tests/Infrastructure/OctansApiFactoryTests.cs diff --git a/Octans.Client/Program.cs b/Octans.Client/Program.cs index 9d4bd0d1..0fd0d2ee 100644 --- a/Octans.Client/Program.cs +++ b/Octans.Client/Program.cs @@ -26,7 +26,12 @@ builder.AddOctansObservability(); builder.Services.AddOctansClient(); builder.Services.AddInfrastructure(); -builder.Services.AddOctansServices(); +var registerBackgroundWorkers = builder.Configuration.GetValue("Octans:BackgroundWorkers:Enabled", true); +builder.Services.AddOctansServices(options => +{ + options.RegisterBackgroundWorkers = registerBackgroundWorkers; + options.RegisterDownloadBackgroundWorker = registerBackgroundWorkers; +}); builder.Services.AddViewmodels(); builder.Services.AddDatabase(); @@ -40,7 +45,7 @@ { options.MaxConcurrentDownloads = 5; options.MaxConcurrentDownloadsPerDomain = 2; -}); +}, registerBackgroundWorkers); builder.SetupConfiguration(); diff --git a/Octans.Client/ServiceCollectionExtensions.cs b/Octans.Client/ServiceCollectionExtensions.cs index 7b3e9686..5810ed43 100644 --- a/Octans.Client/ServiceCollectionExtensions.cs +++ b/Octans.Client/ServiceCollectionExtensions.cs @@ -39,9 +39,11 @@ public static void AddKeyProtection(this WebApplicationBuilder builder) #pragma warning restore RS0030 } - public static IServiceCollection AddOctansServices(this IServiceCollection services) + public static IServiceCollection AddOctansServices( + this IServiceCollection services, + Action? configure = null) { - return services.AddOctansCoreServices(); + return services.AddOctansCoreServices(configure); } public static void AddDatabase(this IServiceCollection services) diff --git a/Octans.Core/Http/DownloadServiceExtensions.cs b/Octans.Core/Http/DownloadServiceExtensions.cs index 5146abbc..251d5cb2 100644 --- a/Octans.Core/Http/DownloadServiceExtensions.cs +++ b/Octans.Core/Http/DownloadServiceExtensions.cs @@ -21,7 +21,8 @@ public static class DownloadServiceExtensions /// public static IServiceCollection AddDownloadManager( this IServiceCollection services, - Action? configure = null) + Action? configure = null, + bool registerBackgroundService = true) { services.RemoveAll(); services.AddOptions() @@ -42,7 +43,10 @@ public static IServiceCollection AddDownloadManager( services.TryAddSingleton(); services.TryAddSingleton(); services.TryAddSingleton(); - services.TryAddEnumerable(ServiceDescriptor.Singleton()); + if (registerBackgroundService) + { + services.TryAddEnumerable(ServiceDescriptor.Singleton()); + } services.AddHttpClient("DownloadClient", client => client.Timeout = Timeout.InfiniteTimeSpan) .ConfigurePrimaryHttpMessageHandler(provider => @@ -141,12 +145,13 @@ private static TimeSpan Double(TimeSpan value) public static IServiceCollection AddDownloadManager( this IServiceCollection services, IConfiguration configuration, - Action? configure = null) + Action? configure = null, + bool registerBackgroundService = true) { return services.AddDownloadManager(options => { configuration.Bind(options); configure?.Invoke(options); - }); + }, registerBackgroundService); } } diff --git a/Octans.Core/ServiceCollectionExtensions.cs b/Octans.Core/ServiceCollectionExtensions.cs index b201598e..1403cc14 100644 --- a/Octans.Core/ServiceCollectionExtensions.cs +++ b/Octans.Core/ServiceCollectionExtensions.cs @@ -24,20 +24,38 @@ namespace Octans.Core; public static class ServiceCollectionExtensions { - public static IServiceCollection AddOctansCoreServices(this IServiceCollection services) + private static readonly HashSet OctansBackgroundWorkerTypes = + [ + typeof(ImportFolderBackgroundService), + typeof(ImportProcessorService), + typeof(SubscriptionBackgroundService), + typeof(RepositoryChangeBackgroundService), + typeof(DownloadBackgroundService), + typeof(ThumbnailCreationBackgroundService) + ]; + + public static IServiceCollection AddOctansCoreServices( + this IServiceCollection services, + Action? configure = null) { + var options = new OctansCoreServiceOptions(); + configure?.Invoke(options); + services.AddOctansChannels(); - services.AddHostedService(); - services.AddHostedService(); - services.AddHostedService(); - services.AddHostedService(); + if (options.RegisterBackgroundWorkers) + { + services.AddHostedService(); + services.AddHostedService(); + services.AddHostedService(); + services.AddHostedService(); + } services.AddSingleton(); services.AddScoped(); services.AddSingleton(); - services.AddBusinessServices(); + services.AddBusinessServices(options.RegisterDownloadBackgroundWorker); return services; } @@ -63,7 +81,27 @@ public static IServiceCollection AddOctansChannels(this IServiceCollection servi return services; } - public static IServiceCollection AddBusinessServices(this IServiceCollection services) + public static IServiceCollection RemoveOctansBackgroundWorkers(this IServiceCollection services) + { + for (var i = services.Count - 1; i >= 0; i--) + { + var descriptor = services[i]; + if (descriptor.ServiceType != typeof(IHostedService) || + descriptor.ImplementationType is not { } implementationType || + !OctansBackgroundWorkerTypes.Contains(implementationType)) + { + continue; + } + + services.RemoveAt(i); + } + + return services; + } + + public static IServiceCollection AddBusinessServices( + this IServiceCollection services, + bool registerDownloadBackgroundWorker = true) { // Imports services.AddScoped(); @@ -100,7 +138,7 @@ public static IServiceCollection AddBusinessServices(this IServiceCollection ser services.AddSingleton(TimeProvider.System); services.AddSingleton(); services.AddBandwidthLimiter(); - services.AddDownloadManager(); + services.AddDownloadManager(registerBackgroundService: registerDownloadBackgroundWorker); // Queries services.AddScoped(); @@ -130,3 +168,9 @@ public static IServiceCollection AddBusinessServices(this IServiceCollection ser return services; } } + +public sealed class OctansCoreServiceOptions +{ + public bool RegisterBackgroundWorkers { get; set; } = true; + public bool RegisterDownloadBackgroundWorker { get; set; } = true; +} diff --git a/Octans.Tests/Infrastructure/OctansApiFactory.cs b/Octans.Tests/Infrastructure/OctansApiFactory.cs new file mode 100644 index 00000000..1f26445f --- /dev/null +++ b/Octans.Tests/Infrastructure/OctansApiFactory.cs @@ -0,0 +1,98 @@ +using System.IO.Abstractions; +using System.IO.Abstractions.TestingHelpers; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.AspNetCore.TestHost; +using Microsoft.Data.Sqlite; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Time.Testing; +using Octans.Client; +using Octans.Core; +using Octans.Data.Models; +using Octans.Tests.Helpers; +using Xunit.Abstractions; + +namespace Octans.Tests.Infrastructure; + +public sealed class OctansApiFactory : WebApplicationFactory +{ + private readonly SqliteConnection _keepAliveConnection; + private readonly ITestOutputHelper? _output; + + public OctansApiFactory(ITestOutputHelper? output = null) + { + _output = output; + AppRoot = $"/octans-api-{Guid.NewGuid():N}"; + FileSystem = new(); + TimeProvider = new(TestClock.UtcNow); + + var connectionString = $"Data Source=OctansApiFactory-{Guid.NewGuid():N};Mode=Memory;Cache=Shared"; + _keepAliveConnection = new(connectionString); + _keepAliveConnection.Open(); + ConnectionString = connectionString; + } + + public string AppRoot { get; } + public MockFileSystem FileSystem { get; } + public FakeTimeProvider TimeProvider { get; } + public string ConnectionString { get; } + + protected override void ConfigureWebHost(IWebHostBuilder builder) + { + builder.ConfigureAppConfiguration((_, configuration) => + { + configuration.AddInMemoryCollection(new Dictionary + { + ["GlobalSettings:AppRoot"] = AppRoot, + ["Octans:BackgroundWorkers:Enabled"] = "false", + ["ImportFolder:Enabled"] = "false" + }); + }); + + builder.ConfigureTestServices(services => + { + services.RemoveOctansBackgroundWorkers(); + + services.RemoveAll(); + services.RemoveAll>(); + services.RemoveAll>(); + + services.AddDbContextFactory(options => options.UseSqlite(ConnectionString)); + services.AddDbContext( + options => options.UseSqlite(ConnectionString), + optionsLifetime: ServiceLifetime.Singleton); + + services.RemoveAll(); + services.AddSingleton(FileSystem); + + services.RemoveAll(); + services.AddSingleton(TimeProvider); + + services.Configure(settings => settings.AppRoot = AppRoot); + + if (_output is not null) + { + services.AddLogging(logging => logging.AddProvider(new XUnitLoggerProvider(_output))); + } + }); + } + + public AsyncServiceScope CreateAsyncScope() + { + return Services.CreateAsyncScope(); + } + + protected override void Dispose(bool disposing) + { + base.Dispose(disposing); + + if (disposing) + { + _keepAliveConnection.Dispose(); + } + } +} diff --git a/Octans.Tests/Infrastructure/OctansApiFactoryTests.cs b/Octans.Tests/Infrastructure/OctansApiFactoryTests.cs new file mode 100644 index 00000000..ab75d19c --- /dev/null +++ b/Octans.Tests/Infrastructure/OctansApiFactoryTests.cs @@ -0,0 +1,48 @@ +using System.Net.Http.Json; +using FluentAssertions; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Octans.Client; +using Octans.Core; +using Xunit.Abstractions; + +namespace Octans.Tests.Infrastructure; + +public sealed class OctansApiFactoryTests(ITestOutputHelper output) +{ + [Fact] + public async Task Health_ShouldReturnHealthy() + { + using var factory = new OctansApiFactory(output); + var client = factory.CreateClient(); + + var response = await client.GetAsync(new Uri("/health", UriKind.Relative)); + + response.EnsureSuccessStatusCode(); + var body = await response.Content.ReadAsStringAsync(); + body.Should().Be("Healthy"); + } + + [Fact] + public async Task Version_ShouldReturnApiVersion() + { + using var factory = new OctansApiFactory(output); + var client = factory.CreateClient(); + + var version = await client.GetFromJsonAsync(new Uri("/version", UriKind.Relative)); + + version.Should().Be(new OctansVersion("1.0.0")); + } + + [Fact] + public void Factory_ShouldDisableHostedServicesByDefault() + { + using var factory = new OctansApiFactory(output); + _ = factory.CreateClient(); + + factory.Services + .GetServices() + .Should() + .NotContain(service => service.GetType().Assembly == typeof(OctansCoreServiceOptions).Assembly); + } +}