using AsbCloudApp.Data; using AsbCloudApp.Data.SAUB; using AsbCloudApp.Repositories; using AsbCloudApp.Requests; using AsbCloudApp.Services; using AsbCloudInfrastructure.Background; using AsbCloudInfrastructure.Services; using AsbCloudInfrastructure.Services.SAUB; using Microsoft.Extensions.DependencyInjection; using NSubstitute; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Threading; using System.Threading.Tasks; using Xunit; namespace AsbCloudWebApi.Tests.Services; public class BackgroundWorkertest { private IServiceProvider provider; private BackgroundWorker service; public BackgroundWorkertest() { provider = Substitute.For(); var serviceScope = Substitute.For(); var serviceScopeFactory = Substitute.For(); serviceScopeFactory.CreateScope().Returns(serviceScope); ((ISupportRequiredService)provider).GetRequiredService(typeof(IServiceScopeFactory)).Returns(serviceScopeFactory); service = new BackgroundWorker(provider); typeof(BackgroundWorker) .GetField("minDelay", BindingFlags.NonPublic | BindingFlags.Instance)? .SetValue(service, TimeSpan.FromMilliseconds(1)); } [Fact] public async Task Enqueue_n_works() { var workCount = 10; var result = 0; Task workAction(string id, IServiceProvider services, Action callback, CancellationToken token) { result++; return Task.Delay(1); } //act for (int i = 0; i < workCount; i++) { var work = Work.CreateByDelegate(i.ToString(), workAction); service.Enqueue(work); } var waitI = workCount; await Task.Delay(1_000); //while (waitI-- > 0 && service.ExecuteTask is not null && service.ExecuteTask.IsCompleted) // await Task.Delay(4); //assert Assert.Equal(workCount, result); } [Fact] public async Task Enqueue_continues_after_exceptions() { var expectadResult = 42; var result = 0; Task workAction(string id, IServiceProvider services, Action callback, CancellationToken token) { result = expectadResult; return Task.CompletedTask; } Task failAction(string id, IServiceProvider services, Action callback, CancellationToken token) => throw new Exception(); var goodWork = Work.CreateByDelegate("", workAction); var badWork = Work.CreateByDelegate("", failAction); badWork.OnErrorAsync = (id, exception, token) => throw new Exception(); //act service.Enqueue(badWork); service.Enqueue(goodWork); await Task.Delay(1200); //assert Assert.Equal(expectadResult, result); } }