diff --git a/AsbCloudApp/Data/WellOperationDto.cs b/AsbCloudApp/Data/WellOperationDto.cs index 03f55957..725debfd 100644 --- a/AsbCloudApp/Data/WellOperationDto.cs +++ b/AsbCloudApp/Data/WellOperationDto.cs @@ -114,11 +114,6 @@ namespace AsbCloudApp.Data /// public IEnumerable Validate(ValidationContext validationContext) { - if (!(DateStart is DateTimeOffset dateTimeOffset)) - yield return new ValidationResult( - $"{nameof(DateStart)}: дата DateStart указана не в формате DateTimeOffset", - new[] { nameof(DateStart) }); - var gtDate = new DateTimeOffset(2010, 1, 1, 0, 0, 0, TimeSpan.Zero); if (DateStart <= gtDate) yield return new ValidationResult( diff --git a/AsbCloudApp/Requests/ReportParametersRequest.cs b/AsbCloudApp/Requests/ReportParametersRequest.cs index 7a9061a5..57b83e4d 100644 --- a/AsbCloudApp/Requests/ReportParametersRequest.cs +++ b/AsbCloudApp/Requests/ReportParametersRequest.cs @@ -1,32 +1,43 @@ -using AsbCloudApp.Validation; using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; namespace AsbCloudApp.Requests; /// /// Параметры для создания отчёта и получения прогнозируемого количества страниц будущего отчета /// -public class ReportParametersRequest +public class ReportParametersRequest: IValidatableObject { - /// - /// Шаг интервала - /// - public int StepSeconds { get; set; } + /// + /// Шаг интервала + /// + [Range(1, 86400)] + public int StepSeconds { get; set; } /// /// формат отчета (0-PDF, 1-LAS) /// + [Range(0, 1)] public int Format { get; set; } /// /// Дата начала интервала /// - [DateValidation(GtDate ="2000-01-01")] public DateTime Begin { get; set; } = default; /// /// Дата окончания интервала /// - [DateValidation(GtDate ="2000-01-01")] public DateTime End { get; set; } = default; + + /// + public IEnumerable Validate(ValidationContext validationContext) + { + if (End < Begin) + yield return new("End mast be less then begin"); + + if (Begin < new DateTime(2000, 1, 1)) + yield return new("Begin mast be > 2000-1-1"); + } } \ No newline at end of file diff --git a/AsbCloudApp/Validation/DateValidationAttribute.cs b/AsbCloudApp/Validation/DateValidationAttribute.cs deleted file mode 100644 index 925739a4..00000000 --- a/AsbCloudApp/Validation/DateValidationAttribute.cs +++ /dev/null @@ -1,80 +0,0 @@ -using System; -using System.ComponentModel.DataAnnotations; - -namespace AsbCloudApp.Validation -{ - /// - /// Атрибут валидации даты-времени - /// - [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property)] - public class DateValidationAttribute : ValidationAttribute - { - private DateTime? gtDate; - - /// - /// null разрешен - /// - public bool AllowNull { get; set; } = true; - - /// - /// Разрешена только дат. - /// При наличии времени в DateTime инвалидирует. - /// При наличии UTC тоже инвалидирует. - /// - public bool IsDateOnly { get; set; } = false; - - /// - /// Допустима дата-время в UTC - /// - public bool AllowUtc { get; set; } = true; - - /// - /// Дата больше которой должно быть проверяемое значение. - /// Формат строки - любой поддерживаемый DateTime.Parse. - /// Желательно использовать ISO 8601 формат - /// - public string? GtDate { - get => gtDate.ToString(); - set - { - if(value is null) - gtDate = null; - else - gtDate = DateTime.Parse(value); - } - } - - /// - /// Проверка значения - /// - /// - /// - public override bool IsValid(object? value) - { - if (value is null) - return AllowNull; - - if (value is not DateTime dateTime) - return false; - - if (IsDateOnly) - { - if (dateTime.Hour > 0 || - dateTime.Minute > 0 || - dateTime.Second > 0 || - dateTime.Millisecond > 0 || - dateTime.Kind == DateTimeKind.Utc) - return false; - } - - if (!AllowUtc && dateTime.Kind == DateTimeKind.Utc) - return false; - - if (gtDate.HasValue && dateTime <= gtDate) - return false; - - return true; - } - - } -} diff --git a/AsbCloudWebApi.Tests/AsbCloudWebApi.Tests.csproj b/AsbCloudWebApi.Tests/AsbCloudWebApi.Tests.csproj index b538cf94..66a2f309 100644 --- a/AsbCloudWebApi.Tests/AsbCloudWebApi.Tests.csproj +++ b/AsbCloudWebApi.Tests/AsbCloudWebApi.Tests.csproj @@ -9,13 +9,13 @@ - - + + - - + + diff --git a/AsbCloudWebApi.Tests/Extensions/AspExtensions.cs b/AsbCloudWebApi.Tests/AspExtensions.cs similarity index 100% rename from AsbCloudWebApi.Tests/Extensions/AspExtensions.cs rename to AsbCloudWebApi.Tests/AspExtensions.cs diff --git a/AsbCloudWebApi.Tests/AttributeTest/DateValidationAttributeTest.cs b/AsbCloudWebApi.Tests/AttributeTest/DateValidationAttributeTest.cs deleted file mode 100644 index 35c446e0..00000000 --- a/AsbCloudWebApi.Tests/AttributeTest/DateValidationAttributeTest.cs +++ /dev/null @@ -1,108 +0,0 @@ -using AsbCloudApp.Validation; -using System; -using Xunit; - -namespace AsbCloudWebApi.Tests.AttributeTest -{ - public class DateValidationAttributeTest - { - [Fact] - public void AllowNull_true_on_null_valid() - { - var attribute = new DateValidationAttribute { AllowNull = true }; - var result = attribute.IsValid(null); - Assert.True(result); - } - - [Fact] - public void AllowNull_false_on_null_invalid() - { - var attribute = new DateValidationAttribute { AllowNull = false }; - var result = attribute.IsValid(null); - Assert.False(result); - } - - [Fact] - public void IsDateOnly_true_on_empty_timePart_valid() - { - var attribute = new DateValidationAttribute { IsDateOnly = true }; - var date = new DateTime(2023, 01, 01, 00, 00, 00); - var result = attribute.IsValid(date); - Assert.True(result); - } - - [Fact] - public void IsDateOnly_true_on_timePart_invalid() - { - var attribute = new DateValidationAttribute { IsDateOnly = true }; - var date = new DateTime(2023, 01, 01, 01, 01, 01); - var result = attribute.IsValid(date); - Assert.False(result); - } - - [Fact] - public void IsDateOnly_true_on_utc_invalid() - { - var attribute = new DateValidationAttribute { IsDateOnly = true }; - var date = new DateTime(2023, 01, 01, 00, 00, 00, DateTimeKind.Utc); - var result = attribute.IsValid(date); - Assert.False(result); - } - - [Fact] - public void AllowUtc_true_on_unspecified_valid() - { - var attribute = new DateValidationAttribute { AllowUtc = true }; - var date = new DateTime(2023, 01, 01, 00, 00, 00, DateTimeKind.Unspecified); - var result = attribute.IsValid(date); - Assert.True(result); - } - - [Fact] - public void AllowUtc_true_on_utc_valid() - { - var attribute = new DateValidationAttribute { AllowUtc = true }; - var date = new DateTime(2023, 01, 01, 00, 00, 00, DateTimeKind.Utc); - var result = attribute.IsValid(date); - Assert.True(result); - } - - [Fact] - public void AllowUtc_false_on_utc_invalid() - { - var attribute = new DateValidationAttribute { AllowUtc = false }; - var date = new DateTime(2023, 01, 01, 00, 00, 00, DateTimeKind.Utc); - var result = attribute.IsValid(date); - Assert.False(result); - } - - [Fact] - public void AllowUtc_false_on_unspecified_valid() - { - var attribute = new DateValidationAttribute { AllowUtc = false }; - var date = new DateTime(2023, 01, 01, 00, 00, 00, DateTimeKind.Unspecified); - var result = attribute.IsValid(date); - Assert.True(result); - } - - [Fact] - public void GtDate_on_same_date_invalid() - { - var gtDate = "2023-01-01T00:00:00"; - var date = DateTime.Parse(gtDate); - var attribute = new DateValidationAttribute { GtDate = gtDate }; - var result = attribute.IsValid(date); - Assert.False(result); - } - - [Fact] - public void GtDate_on_greater_date_valid() - { - var gtDate = "2023-01-01T00:00:00"; - var date = DateTime.Parse(gtDate).AddMilliseconds(1); - var attribute = new DateValidationAttribute { GtDate = gtDate }; - var result = attribute.IsValid(date); - Assert.True(result); - } - } -} diff --git a/AsbCloudWebApi.Tests/Background/BackgroundWorkerTest.cs b/AsbCloudWebApi.Tests/Background/BackgroundWorkerTest.cs new file mode 100644 index 00000000..912b4806 --- /dev/null +++ b/AsbCloudWebApi.Tests/Background/BackgroundWorkerTest.cs @@ -0,0 +1,119 @@ +using System; +using System.Reflection; +using System.Threading; +using System.Threading.Tasks; +using AsbCloudInfrastructure.Background; +using Microsoft.Extensions.DependencyInjection; +using NSubstitute; +using Xunit; + +namespace AsbCloudWebApi.Tests.Background; + +public class BackgroundWorkerTest +{ + private readonly IServiceProvider serviceProviderMock = Substitute.For(); + private readonly IServiceScope serviceScopeMock = Substitute.For(); + private readonly IServiceScopeFactory serviceScopeFactoryMock = Substitute.For(); + + private readonly BackgroundWorker backgroundWorker; + + public BackgroundWorkerTest() + { + serviceScopeFactoryMock.CreateScope().Returns(serviceScopeMock); + ((ISupportRequiredService)serviceProviderMock).GetRequiredService(typeof(IServiceScopeFactory)).Returns(serviceScopeFactoryMock); + + backgroundWorker = new BackgroundWorker(serviceProviderMock); + typeof(BackgroundWorker) + .GetField("minDelay", BindingFlags.NonPublic | BindingFlags.Instance) + ?.SetValue(backgroundWorker, TimeSpan.FromMilliseconds(1)); + } + + [Fact] + public async Task Enqueue_ShouldReturn_WorkCount() + { + //arrange + const int 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); + backgroundWorker.Enqueue(work); + } + + await backgroundWorker.ExecuteTask; + + //assert + Assert.Equal(workCount, result); + } + + [Fact] + public async Task Enqueue_Continues_AfterExceptions() + { + //arrange + const int expectadResult = 42; + var result = 0; + + Task workAction(string id, IServiceProvider services, Action callback, CancellationToken token) + { + result = expectadResult; + return Task.CompletedTask; + } + + var goodWork = Work.CreateByDelegate("", workAction); + + Task failAction(string id, IServiceProvider services, Action callback, CancellationToken token) + => throw new Exception(); + + var badWork = Work.CreateByDelegate("", failAction); + badWork.OnErrorAsync = (id, exception, token) => throw new Exception(); + + //act + backgroundWorker.Enqueue(badWork); + backgroundWorker.Enqueue(goodWork); + + await backgroundWorker.ExecuteTask; + + //assert + Assert.Equal(expectadResult, result); + Assert.Equal(1, backgroundWorker.Felled.Count); + Assert.Equal(1, backgroundWorker.Done.Count); + } + + [Fact] + public async Task TryRemoveFromQueue_ShouldReturn_True() + { + //arrange + const int workCount = 5; + var result = 0; + + Task workAction(string id, IServiceProvider services, Action callback, CancellationToken token) + { + result++; + return Task.Delay(10); + } + + //act + for (int i = 0; i < workCount; i++) + { + var work = Work.CreateByDelegate(i.ToString(), workAction); + backgroundWorker.Enqueue(work); + } + + var removed = backgroundWorker.TryRemoveFromQueue((workCount - 1).ToString()); + + await backgroundWorker.ExecuteTask; + + //assert + Assert.True(removed); + Assert.Equal(workCount - 1, result); + Assert.Equal(workCount - 1, backgroundWorker.Done.Count); + } +} \ No newline at end of file diff --git a/AsbCloudWebApi.Tests/UnitTests/Background/PeriodicBackgroundWorkerTest.cs b/AsbCloudWebApi.Tests/Background/PeriodicBackgroundWorkerTest.cs similarity index 93% rename from AsbCloudWebApi.Tests/UnitTests/Background/PeriodicBackgroundWorkerTest.cs rename to AsbCloudWebApi.Tests/Background/PeriodicBackgroundWorkerTest.cs index fced6864..938d8106 100644 --- a/AsbCloudWebApi.Tests/UnitTests/Background/PeriodicBackgroundWorkerTest.cs +++ b/AsbCloudWebApi.Tests/Background/PeriodicBackgroundWorkerTest.cs @@ -8,7 +8,7 @@ using Microsoft.Extensions.DependencyInjection; using NSubstitute; using Xunit; -namespace AsbCloudWebApi.Tests.UnitTests.Background; +namespace AsbCloudWebApi.Tests.Background; //TODO: нужно поправить тесты, иногда они не проходят public class PeriodicBackgroundWorkerTest @@ -55,7 +55,7 @@ public class PeriodicBackgroundWorkerTest var stopwatch = Stopwatch.StartNew(); service.Add(work, period); - var delay = (periodMs / 20) + (periodMs * workCount) - stopwatch.ElapsedMilliseconds; + var delay = periodMs / 20 + periodMs * workCount - stopwatch.ElapsedMilliseconds; await Task.Delay(TimeSpan.FromMilliseconds(delay)); //assert @@ -86,7 +86,7 @@ public class PeriodicBackgroundWorkerTest service.Add(badWork, TimeSpan.FromSeconds(2)); service.Add(goodWork, TimeSpan.FromSeconds(2)); - await Task.Delay(TimeSpan.FromMilliseconds(128)); + await Task.Delay(TimeSpan.FromMilliseconds(256)); //assert Assert.Equal(expectadResult, result); diff --git a/AsbCloudWebApi.Tests/Background/WorkTest.cs b/AsbCloudWebApi.Tests/Background/WorkTest.cs new file mode 100644 index 00000000..41fc486d --- /dev/null +++ b/AsbCloudWebApi.Tests/Background/WorkTest.cs @@ -0,0 +1,152 @@ +using System; +using System.Threading; +using System.Threading.Tasks; +using AsbCloudInfrastructure.Background; +using Microsoft.Extensions.DependencyInjection; +using NSubstitute; +using Xunit; + +namespace AsbCloudWebApi.Tests.Background; + +public class WorkTest +{ + private readonly IServiceProvider serviceProviderMock = Substitute.For(); + private readonly IServiceScope serviceScopeMock = Substitute.For(); + private readonly IServiceScopeFactory serviceScopeFactoryMock = Substitute.For(); + + public WorkTest() + { + serviceScopeFactoryMock.CreateScope().Returns(serviceScopeMock); + ((ISupportRequiredService)serviceProviderMock).GetRequiredService(typeof(IServiceScopeFactory)).Returns(serviceScopeFactoryMock); + } + + [Fact] + public async Task Start_ShouldReturn_Success() + { + //arrange + Task workAction(string id, IServiceProvider services, Action callback, CancellationToken token) + => Task.CompletedTask; + + var work = Work.CreateByDelegate("", workAction); + + //act + var begin = DateTime.Now; + await work.Start(serviceProviderMock, CancellationToken.None); + var done = DateTime.Now; + var executionTime = done - begin; + + //assert + Assert.Equal(1, work.CountComplete); + Assert.Equal(1, work.CountStart); + Assert.Equal(0, work.CountErrors); + Assert.Null(work.CurrentState); + Assert.Null(work.LastError); + + var lastState = work.LastComplete; + Assert.NotNull(lastState); + Assert.InRange(lastState.Start, begin, done - 0.5 * executionTime); + Assert.InRange(lastState.End, done - 0.5 * executionTime, done); + Assert.InRange(lastState.ExecutionTime, TimeSpan.Zero, executionTime); + } + + [Fact] + public async Task ExecutionWork_Invokes_Callback() + { + //arrange + const string expectedState = "42"; + const double expectedProgress = 42d; + + var timeout = TimeSpan.FromMilliseconds(80); + + Task workAction(string id, IServiceProvider services, Action callback, CancellationToken token) + { + callback.Invoke(expectedState, expectedProgress); + return Task.Delay(timeout); + } + + var work = Work.CreateByDelegate("", workAction); + + //act + var begin = DateTime.Now; + _ = work.Start(serviceProviderMock, CancellationToken.None); + await Task.Delay(timeout / 3); + + //assert + Assert.Equal(0, work.CountComplete); + Assert.Equal(1, work.CountStart); + Assert.Equal(0, work.CountErrors); + Assert.NotNull(work.CurrentState); + Assert.Null(work.LastComplete); + Assert.Null(work.LastError); + + var currentState = work.CurrentState; + Assert.NotNull(currentState); + Assert.InRange(currentState.Start, begin, begin + timeout); + Assert.InRange(currentState.StateUpdate, begin, begin + timeout); + Assert.Equal(expectedState, currentState.State); + Assert.Equal(expectedProgress, currentState.Progress); + } + + [Fact] + public async Task ExecutionWork_ShouldReturn_FailsWithInfo() + { + //arrange + const string expectedState = "41"; + const string expectedErrorText = "42"; + var minWorkTime = TimeSpan.FromMilliseconds(10); + + async Task workAction(string id, IServiceProvider services, Action callback, CancellationToken token) + { + await Task.Delay(minWorkTime); + callback(expectedState, 0); + throw new Exception(expectedErrorText); + } + + var work = Work.CreateByDelegate("", workAction); + + //act + var begin = DateTime.Now; + await work.Start(serviceProviderMock, CancellationToken.None); + + //assert + Assert.Equal(0, work.CountComplete); + Assert.Equal(1, work.CountStart); + Assert.Equal(1, work.CountErrors); + Assert.Null(work.CurrentState); + Assert.Null(work.LastComplete); + + var error = work.LastError; + Assert.NotNull(error); + Assert.InRange(error.Start, begin, DateTime.Now); + Assert.InRange(error.End, begin, DateTime.Now); + Assert.InRange(error.ExecutionTime, minWorkTime, DateTime.Now - begin); + Assert.Contains(expectedErrorText, error.ErrorText, StringComparison.InvariantCultureIgnoreCase); + Assert.Equal(expectedState, error.State); + } + + [Fact] + public async Task Stop_ShouldReturn_Success() + { + //arrange + var workTime = TimeSpan.FromMilliseconds(1_000); + + Task workAction(string id, IServiceProvider services, Action callback, CancellationToken token) + => Task.Delay(workTime, token); + + var work = Work.CreateByDelegate("", workAction); + + //act + var begin = DateTime.Now; + _ = work.Start(serviceProviderMock, CancellationToken.None); + await Task.Delay(10); + work.Stop(); + await Task.Delay(10); + + //assert + Assert.Equal(0, work.CountComplete); + Assert.Equal(1, work.CountStart); + Assert.Equal(1, work.CountErrors); + Assert.Null(work.LastComplete); + Assert.NotNull(work.LastError); + } +} \ No newline at end of file diff --git a/AsbCloudWebApi.Tests/Services/DailyReportServiceTest.cs b/AsbCloudWebApi.Tests/Services/DailyReportServiceTest.cs new file mode 100644 index 00000000..d9665e4d --- /dev/null +++ b/AsbCloudWebApi.Tests/Services/DailyReportServiceTest.cs @@ -0,0 +1,583 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using AsbCloudApp.Data; +using AsbCloudApp.Data.DailyReport; +using AsbCloudApp.Data.DailyReport.Blocks.Sign; +using AsbCloudApp.Data.DailyReport.Blocks.Subsystems; +using AsbCloudApp.Data.DailyReport.Blocks.TimeBalance; +using AsbCloudApp.Data.DetectedOperation; +using AsbCloudApp.Data.ProcessMaps.Report; +using AsbCloudApp.Data.Subsystems; +using AsbCloudApp.Data.Trajectory; +using AsbCloudApp.Exceptions; +using AsbCloudApp.Repositories; +using AsbCloudApp.Requests; +using AsbCloudApp.Services; +using AsbCloudApp.Services.ProcessMaps.WellDrilling; +using AsbCloudInfrastructure.Services.DailyReport; +using NSubstitute; +using Xunit; + +namespace AsbCloudWebApi.Tests.Services; + +public class DailyReportServiceTest +{ + private const int idDailyReport = 1; + private const int idUser = 3; + private const int idWell = 2; + + private readonly SubsystemBlockDto fakeSubsystemBlock = new() + { + IdUser = idUser, + Wellbore = 999, + MeasurementsPerDay = 999, + TotalRopPlan = 999, + Comment = "Увеличить обороты", + Subsystems = new[] + { + new SubsystemRecordDto + { + Name = "АвтоСПО", + UsagePerDay = new SubsystemParametersDto + { + UsedTimeHours = 24, + SumDepthInterval = 1500, + KUsage = 15 + }, + UsagePerWell = new SubsystemParametersDto + { + UsedTimeHours = 500, + SumDepthInterval = 3000, + KUsage = 100 + } + } + } + }; + + private readonly SignBlockDto fakeSignBlock = new() + { + IdUser = idUser, + DrillingMaster = new SignRecordDto + { + Name = "Иван", + Patronymic = "Иванович", + Surname = "Иванов" + }, + Supervisor = new SignRecordDto() + { + Name = "Илья", + Patronymic = "Ильич", + Surname = "Бурилов" + } + }; + + private readonly TimeBalanceBlockDto fakeTimeBalanceBlock = new() + { + IdUser = idUser, + IdSection = 1, + WellDepth = new PlanFactDto + { + Plan = 2000 + }, + WellOperations = new[] + { + new TimeBalanceRecordDto + { + IdWellOperation = 1, + DurationHours = new PlanFactDto + { + Fact = 100, + Plan = 150, + }, + DrillingDeviationPerSection = 90, + DrillingDeviationPerDay = 100, + ReasonDeviation = "Отклонение" + } + } + }; + + private readonly DetectedOperationListDto fakeWellOperationSlipsTime = new() + { + Stats = new[] + { + new DetectedOperationDrillersStatDto + { + Count = 40 + } + } + }; + + private readonly ProcessMapReportWellDrillingDto fakeProcessMapReportWellDrilling = new() + { + DrillingMode = "Ротор", + DateStart = new DateTime(2023, 10, 26), + DeltaDepth = 500, + Rop = new PlanFactDto + { + Plan = 300, + Fact = 500 + }, + MechDrillingHours = 100 + }; + + private readonly WellSectionTypeDto fakeSectionType = new() + { + Id = 1, + Caption = "Пилотный ствол", + }; + + private readonly TrajectoryGeoFactDto fakeLastFactTrajectory = new() + { + WellboreDepth = 100, + VerticalDepth = 150, + ZenithAngle = 3, + AzimuthGeo = 5 + }; + + private readonly CompanyDto fakeCustomer = new() + { + Caption = "Тестовый заказчик", + IdCompanyType = 1 + }; + + private readonly CompanyDto fakeContractor = new() + { + Caption = "Тестовый подрядчик", + IdCompanyType = 2 + }; + + private readonly WellOperationDto fakeFirstFactWellOperation = new() + { + IdWell = idWell, + IdParentCategory = 4001, + IdWellSectionType = 1, + CategoryName = "Механическое. бурение", + DateStart = new DateTime(2023, 10, 26), + DepthStart = 80, + DepthEnd = 150, + DurationHours = 8, + }; + + private readonly WellOperationDto fakeLastFactWellOperation = new() + { + IdWell = idWell, + CategoryName = "Механическое. бурение", + IdWellSectionType = 1, + IdParentCategory = 4001, + DateStart = new DateTime(2023, 10, 26), + DepthStart = 150, + DepthEnd = 200, + DurationHours = 8, + }; + + private readonly ScheduleDto fakeShedule = new() + { + IdWell = idWell, + ShiftStart = new TimeDto(1), + ShiftEnd = new TimeDto(5), + DrillStart = new DateTime(2023, 01, 26), + DrillEnd = new DateTime(2023, 12, 26), + Driller = new() + { + Name = "Иван", + Surname = "Иванов", + Patronymic = "Бурила" + } + }; + + private readonly SubsystemStatDto fakeSubsystemsStat = new() + { + SubsystemName = "АПД", + SumDepthInterval = 250, + UsedTimeHours = 200, + KUsage = 30 + }; + + private readonly SimpleTimezoneDto fakeWellTimezone = new() + { + Hours = 5, + }; + + private readonly IWellService wellServiceMock = Substitute.For(); + private readonly ITrajectoryNnbRepository trajectoryFactNnbRepositoryMock = Substitute.For(); + private readonly IDailyReportRepository dailyReportRepositoryMock = Substitute.For(); + private readonly IScheduleRepository scheduleRepositoryMock = Substitute.For(); + private readonly IWellOperationRepository wellOperationRepositoryMock = Substitute.For(); + private readonly ISubsystemService subsystemServiceMock = Substitute.For(); + private readonly IProcessMapReportWellDrillingService processMapReportWellDrillingServiceMock = Substitute.For(); + private readonly IDetectedOperationService detectedOperationServiceMock = Substitute.For(); + + private readonly DailyReportService dailyReportService; + + private readonly DailyReportDto fakeDailyReport; + private readonly WellDto fakeWell; + private readonly DatesRangeDto fakeDatesRange; + + public DailyReportServiceTest() + { + fakeDailyReport = new DailyReportDto + { + Id = idDailyReport, + IdWell = idWell, + Date = new(2023, 10, 26), + DateLastUpdate = null + }; + + fakeWell = new WellDto + { + Id = idWell, + Caption = "Тестовое название", + WellType = "Горизонтальная", + Cluster = "Тестовый куст", + Deposit = "Тестовое месторождение", + Companies = new[] { fakeCustomer, fakeContractor } + }; + + fakeDatesRange = new DatesRangeDto + { + From = fakeFirstFactWellOperation.DateStart.DateTime, + To = fakeLastFactWellOperation.DateStart.DateTime + }; + + dailyReportService = new DailyReportService(wellServiceMock, + trajectoryFactNnbRepositoryMock, + dailyReportRepositoryMock, + scheduleRepositoryMock, + wellOperationRepositoryMock, + subsystemServiceMock, + processMapReportWellDrillingServiceMock, + detectedOperationServiceMock); + + dailyReportRepositoryMock.InsertAsync(Arg.Any(), Arg.Any()) + .ReturnsForAnyArgs(idDailyReport); + + dailyReportRepositoryMock.GetOrDefaultAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .ReturnsForAnyArgs(fakeDailyReport); + + dailyReportRepositoryMock.UpdateAsync(Arg.Any(), Arg.Any()) + .ReturnsForAnyArgs(idDailyReport); + + wellServiceMock.GetOrDefaultAsync(Arg.Any(), Arg.Any()) + .ReturnsForAnyArgs(fakeWell); + + trajectoryFactNnbRepositoryMock.GetByRequestAsync(Arg.Any(), Arg.Any()) + .ReturnsForAnyArgs(new[] { fakeLastFactTrajectory }); + + wellOperationRepositoryMock.GetAsync(Arg.Any(), Arg.Any()) + .ReturnsForAnyArgs(new[] { fakeFirstFactWellOperation, fakeLastFactWellOperation }); + + wellOperationRepositoryMock.GetDatesRangeAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .ReturnsForAnyArgs(fakeDatesRange); + + wellOperationRepositoryMock.GetSectionTypes() + .ReturnsForAnyArgs(new[] { fakeSectionType }); + + detectedOperationServiceMock.GetAsync(Arg.Any(), Arg.Any()) + .ReturnsForAnyArgs(fakeWellOperationSlipsTime); + + subsystemServiceMock.GetStatAsync(Arg.Any(), Arg.Any()) + .ReturnsForAnyArgs(new[] { fakeSubsystemsStat }); + + scheduleRepositoryMock.GetAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .ReturnsForAnyArgs(new[] { fakeShedule }); + + processMapReportWellDrillingServiceMock.GetAsync(Arg.Any(), Arg.Any()) + .ReturnsForAnyArgs(new[] { fakeProcessMapReportWellDrilling }); + + wellServiceMock.GetTimezone(Arg.Any()) + .ReturnsForAnyArgs(fakeWellTimezone); + } + + [Fact] + public async Task UpdateOrInsertAsync_ShouldReturn_UpdatedSubsystemBlock() + { + //act + var result = await dailyReportService.UpdateOrInsertAsync(idWell, fakeDailyReport.Date, idUser, fakeSubsystemBlock, CancellationToken.None); + + //assert + Assert.NotNull(fakeSubsystemBlock.LastUpdateDate); + Assert.NotNull(fakeDailyReport.DateLastUpdate); + Assert.Equal(fakeSubsystemBlock.IdUser, idUser); + Assert.Equal(fakeDailyReport.SubsystemBlock, fakeSubsystemBlock); + Assert.Equal(idDailyReport, result); + } + + [Theory] + [MemberData(nameof(DateDailyReport))] + public async Task UpdateOrInsertAsync_ShouldReturn_UnableToUpdateDailyReport(DateOnly dateDailyReport) + { + //act + var result = await Assert.ThrowsAsync(() => dailyReportService.UpdateOrInsertAsync( + idWell, + dateDailyReport, + idUser, + fakeSignBlock, + CancellationToken.None)); + + //assert + Assert.Contains("Невозможно обновить суточный отчёт", result.Message); + } + + [Fact] + public async Task UpdateOrInsertAsync_ShouldReturn_UpdatedSignBlock() + { + //act + var result = await dailyReportService.UpdateOrInsertAsync(idWell, fakeDailyReport.Date, idUser, fakeSignBlock, CancellationToken.None); + + //assert + Assert.NotNull(fakeSignBlock.LastUpdateDate); + Assert.NotNull(fakeDailyReport.DateLastUpdate); + Assert.Equal(fakeSignBlock.IdUser, idUser); + Assert.Equal(fakeDailyReport.SignBlock, fakeSignBlock); + Assert.Equal(idDailyReport, result); + } + + [Fact] + public async Task UpdateOrInsertAsync_ShouldReturn_UpdatedTimeBalanceBlock() + { + //act + var result = await dailyReportService.UpdateOrInsertAsync(idWell, fakeDailyReport.Date, idUser, fakeTimeBalanceBlock, + CancellationToken.None); + + //assert + Assert.NotNull(fakeTimeBalanceBlock.LastUpdateDate); + Assert.NotNull(fakeDailyReport.DateLastUpdate); + Assert.Equal(fakeTimeBalanceBlock.IdUser, idUser); + Assert.Equal(fakeDailyReport.TimeBalanceBlock, fakeTimeBalanceBlock); + Assert.Equal(idDailyReport, result); + } + + [Theory] + [MemberData(nameof(DateDailyReport))] + public async Task GetAsync_ShouldReturn_UnableToGetDailyReport(DateOnly dateDailyReport) + { + //act + var result = await Assert.ThrowsAsync(() => dailyReportService.GetAsync(idWell, + dateDailyReport, + CancellationToken.None)); + + //assert + Assert.Contains("Невозможно получить суточный отчёт", result.Message); + } + + [Fact] + public async Task GetAsync_ShouldReturn_AddedWellInfo() + { + //act + var result = await dailyReportService.GetAsync(idWell, fakeDailyReport.Date, CancellationToken.None); + + //assert + Assert.Equal(result.IdWell, fakeWell.Id); + Assert.Equal(result.WellCaption, fakeWell.Caption); + Assert.Equal(result.WellType, fakeWell.WellType); + Assert.Equal(result.Cluster, fakeWell.Cluster); + Assert.Equal(result.Deposit, fakeWell.Deposit); + Assert.Equal(result.Customer, fakeCustomer.Caption); + Assert.Equal(result.Contractor, fakeContractor.Caption); + Assert.Equal(result.DepthStart, fakeFirstFactWellOperation.DepthStart); + Assert.Equal(result.DepthEnd, fakeLastFactWellOperation.DepthEnd); + } + + [Fact] + public async Task GetAsync_ShouldReturn_AddedTrajectoryBlock() + { + //act + var result = await dailyReportService.GetAsync(idWell, fakeDailyReport.Date, CancellationToken.None); + + //assert + Assert.Equal(fakeLastFactTrajectory.WellboreDepth, result.TrajectoryBlock.WellboreDepth); + Assert.Equal(fakeLastFactTrajectory.VerticalDepth, result.TrajectoryBlock.VerticalDepth); + Assert.Equal(fakeLastFactTrajectory.ZenithAngle, result.TrajectoryBlock.ZenithAngle); + Assert.Equal(fakeLastFactTrajectory.AzimuthGeo, result.TrajectoryBlock.AzimuthGeo); + } + + [Fact] + public async Task GetAsync_ShouldReturn_AddedFactWellOperationBlock() + { + //act + var result = await dailyReportService.GetAsync(idWell, fakeDailyReport.Date, CancellationToken.None); + + //assert + Assert.Equal(16, result.FactWellOperationBlock.SectionDrillingHours); + Assert.Single(result.FactWellOperationBlock.WellOperations); + + var wellOperation = result.FactWellOperationBlock.WellOperations.Single(); + + Assert.Equal("Механическое. бурение", wellOperation.CategoryName); + Assert.Equal(16, wellOperation.DurationHours); + } + + [Fact] + public async Task GetAsync_ShouldReturn_AddedScheduleBlock() + { + //act + var result = await dailyReportService.GetAsync(idWell, fakeDailyReport.Date, CancellationToken.None); + + //assert + Assert.Single(result.ScheduleBlock); + + var sheduleRecord = result.ScheduleBlock.Single(); + + Assert.Equal(fakeShedule.ShiftStart, sheduleRecord.ShiftStart); + Assert.Equal(fakeShedule.ShiftEnd, sheduleRecord.ShiftEnd); + Assert.Equal(fakeShedule.Driller?.Name, sheduleRecord.Name); + Assert.Equal(fakeShedule.Driller?.Surname, sheduleRecord.Surname); + Assert.Equal(fakeShedule.Driller?.Patronymic, sheduleRecord.Patronymic); + } + + [Fact] + public async Task GetAsync_ShouldReturn_UpdatedTimeBalanceBlock() + { + //arrange + fakeDailyReport.TimeBalanceBlock = fakeTimeBalanceBlock; + + //act + var result = await dailyReportService.GetAsync(idWell, fakeDailyReport.Date, CancellationToken.None); + + //assert + Assert.NotNull(result.TimeBalanceBlock); + Assert.Equal(fakeSectionType.Id, result.TimeBalanceBlock.IdSection); + Assert.Equal(fakeSectionType.Caption, result.TimeBalanceBlock.SectionName); + Assert.Equal(2000, result.TimeBalanceBlock?.WellDepth.Plan); + Assert.Equal(120, result.TimeBalanceBlock?.WellDepth.Fact); + Assert.Equal(40, result.TimeBalanceBlock?.WellOperationSlipsTimeCount); + } + + [Fact] + public async Task GetAsync_ShouldReturn_AddedProcessMapWellDrillingBlock() + { + //act + var result = await dailyReportService.GetAsync(idWell, fakeDailyReport.Date, CancellationToken.None); + + //assert + Assert.Single(result.ProcessMapWellDrillingBlock); + + var processMapWellDrillingRecord = result.ProcessMapWellDrillingBlock.Single(); + + Assert.Equal(fakeProcessMapReportWellDrilling.DrillingMode, processMapWellDrillingRecord.DrillingMode); + Assert.Equal(fakeProcessMapReportWellDrilling.Rop.Plan, processMapWellDrillingRecord.Rop.Plan); + Assert.Equal(fakeProcessMapReportWellDrilling.Rop.Fact, processMapWellDrillingRecord.Rop.Fact); + Assert.Equal(fakeProcessMapReportWellDrilling.DeltaDepth, processMapWellDrillingRecord.WellBoreDepth); + Assert.Equal(fakeProcessMapReportWellDrilling.MechDrillingHours, processMapWellDrillingRecord.MechDrillingHours); + } + + [Fact] + public async Task GetAsync_ShouldReturn_UpdatedSubsystemBlock() + { + //arrange + fakeDailyReport.SubsystemBlock = fakeSubsystemBlock; + + //act + var result = await dailyReportService.GetAsync(idDailyReport, fakeDailyReport.Date, CancellationToken.None); + + //assert + Assert.NotNull(result.SubsystemBlock); + Assert.Equal(2, result.SubsystemBlock?.Subsystems.Count()); + + var subsystemRecord0 = result.SubsystemBlock?.Subsystems.ElementAt(0); + + Assert.Equal("АвтоСПО", subsystemRecord0?.Name); + Assert.Equal(24, subsystemRecord0?.UsagePerDay?.UsedTimeHours); + Assert.Equal(1500, subsystemRecord0?.UsagePerDay?.SumDepthInterval); + Assert.Equal(15, subsystemRecord0?.UsagePerDay?.KUsage); + + Assert.Equal(500, subsystemRecord0?.UsagePerWell?.UsedTimeHours); + Assert.Equal(3000, subsystemRecord0?.UsagePerWell?.SumDepthInterval); + Assert.Equal(100, subsystemRecord0?.UsagePerWell?.KUsage); + + var subsystemRecord1 = result.SubsystemBlock?.Subsystems.ElementAt(1); + + Assert.Equal("АПД", subsystemRecord1?.Name); + Assert.Equal(200, subsystemRecord1?.UsagePerDay?.UsedTimeHours); + Assert.Equal(250, subsystemRecord1?.UsagePerDay?.SumDepthInterval); + Assert.Equal(30, subsystemRecord1?.UsagePerDay?.KUsage); + + Assert.Equal(200, subsystemRecord1?.UsagePerWell?.UsedTimeHours); + Assert.Equal(250, subsystemRecord1?.UsagePerWell?.SumDepthInterval); + Assert.Equal(30, subsystemRecord1?.UsagePerWell?.KUsage); + } + + [Fact] + public async Task GetAsync_ShouldReturn_FictiveDailyReport() + { + //arrange + var expectedCount = (fakeLastFactWellOperation.DateStart - fakeFirstFactWellOperation.DateStart).TotalDays + 1; + + //act + var result = await dailyReportService.GetAsync(idWell, new FileReportRequest(), CancellationToken.None); + + //assert + Assert.Equal(expectedCount, result.Count); + } + + [Theory] + [MemberData(nameof(FactWellOperationDatesRange))] + public async Task GetDatesRangeAsync_ShouldReturn_DateRangeByFactWellOperations(DatesRangeDto datesRange) + { + //arrange + wellOperationRepositoryMock.GetDatesRangeAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(datesRange); + + //act + var result = await dailyReportService.GetDatesRangeAsync(idWell, CancellationToken.None); + + //assert + Assert.NotNull(result); + Assert.True(result.From <= result.To); + Assert.True(result.To < DateTime.UtcNow.Date); + } + + public static IEnumerable DateDailyReport() + { + yield return new object[] + { + new DateOnly(2090, 01, 01), + }; + yield return new object[] + { + new DateOnly(2000, 01, 01) + }; + } + + public static IEnumerable FactWellOperationDatesRange() + { + yield return new object[] + { + new DatesRangeDto + { + From = new DateTime(2023, 11, 1), + To = new DateTime(2023, 11, 9) + } + }; + + yield return new object[] + { + new DatesRangeDto + { + From = new DateTime(2023, 11, 1), + To = new DateTime(2023, 11, 1) + } + }; + + yield return new object[] + { + new DatesRangeDto + { + From = DateTime.UtcNow, + To = DateTime.UtcNow + } + }; + + yield return new object[] + { + new DatesRangeDto + { + From = new DateTime(2023, 11, 1), + To = new DateTime(2023, 11, 11) + } + }; + } +} \ No newline at end of file diff --git a/AsbCloudWebApi.Tests/Services/FileServiceTest.cs b/AsbCloudWebApi.Tests/Services/FileServiceTest.cs new file mode 100644 index 00000000..311e483f --- /dev/null +++ b/AsbCloudWebApi.Tests/Services/FileServiceTest.cs @@ -0,0 +1,172 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +using AsbCloudApp.Data; +using AsbCloudApp.Data.User; +using AsbCloudApp.Repositories; +using AsbCloudApp.Requests; +using AsbCloudApp.Services; +using NSubstitute; +using Xunit; + +namespace AsbCloudWebApi.Tests.Services; + +public class FileServiceTest +{ + private const int idMark = 132; + private const int idWell = 190; + private const int idCategory = 10_000; + private const int idFile = 1742; + private const int idAuthor = 1; + private const string fileName = "test.txt"; + + private static readonly MemoryStream fileStream = new(Array.Empty()); + + private static UserDto author = new() + { + Id = 1, + IdCompany = 1 + }; + + private static FileInfoDto fileInfo = new() + { + Id = idFile, + IdAuthor = idAuthor, + Author = author, + IdWell = idWell, + IdCategory = idCategory, + Name = fileName, + Size = 0, + UploadDate = DateTime.Now + }; + + private static FileMarkDto fileMark = new() + { + Id = idMark, + IdFile = idFile, + User = author, + Comment = "qqq", + IdMarkType = 1, + DateCreated = DateTime.Now, + IsDeleted = false + }; + + private readonly IFileRepository fileRepositoryMock = Substitute.For(); + private readonly IFileStorageRepository storageRepositoryMock = Substitute.For(); + + private readonly FileService fileService; + + public FileServiceTest() + { + fileRepositoryMock.GetByMarkId(Arg.Any(), Arg.Any()) + .ReturnsForAnyArgs(fileInfo); + + fileRepositoryMock.GetInfoByIdsAsync(Arg.Any>(), Arg.Any()) + .ReturnsForAnyArgs(new[] { fileInfo }); + + fileRepositoryMock.DeleteAsync(Arg.Any>(), Arg.Any()) + .ReturnsForAnyArgs(new[] { fileInfo }); + + fileRepositoryMock.MarkFileMarkAsDeletedAsync(Arg.Any>(), Arg.Any()) + .ReturnsForAnyArgs(fileMark.Id); + + fileRepositoryMock.MarkAsDeletedAsync(Arg.Any(), Arg.Any()) + .ReturnsForAnyArgs(fileMark.Id); + + fileRepositoryMock.GetInfosAsync(Arg.Any(), Arg.Any()) + .ReturnsForAnyArgs(new[] { fileInfo }); + + fileRepositoryMock.CreateFileMarkAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .ReturnsForAnyArgs(fileMark.Id); + + fileRepositoryMock.GetOrDefaultAsync(Arg.Any(), Arg.Any()) + .ReturnsForAnyArgs(fileInfo); + + storageRepositoryMock.GetFilePath(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .ReturnsForAnyArgs(Path.Combine("files", idWell.ToString(), idCategory.ToString(), fileName)); + + fileService = new FileService(fileRepositoryMock, storageRepositoryMock); + } + + [Fact] + public async Task GetByMarkId_ShouldReturn_FileInfo() + { + //act + var data = await fileService.GetByMarkId(idMark, CancellationToken.None); + + //assert + Assert.NotNull(data); + } + + [Fact] + public async Task GetOrDefaultAsync_ShouldReturn_FileInfo() + { + //act + var data = await fileService.GetOrDefaultAsync(idFile, CancellationToken.None); + + //assert + Assert.NotNull(data); + } + + [Fact] + public async Task GetInfoByIdsAsync_ShouldReturn_FileInfo() + { + //act + var data = await fileService.GetInfoByIdsAsync(new[] { idFile }, CancellationToken.None); + + //assert + Assert.NotNull(data); + } + + [Fact] + public async Task SaveAsync_ShouldReturn_FileInfo() + { + //act + var data = await fileService.SaveAsync(idWell, idAuthor, idCategory, fileName, fileStream, CancellationToken.None); + + //assert + Assert.NotNull(data); + } + + [Fact] + public async Task DeleteAsync_ShouldReturn_DeletedRecordCount() + { + //act + var result = await fileService.DeleteAsync(new[] { idFile }, CancellationToken.None); + + //assert + Assert.True(result > 0); + } + + [Fact] + public async Task MarkFileMarkAsDeletedAsync_ShouldReturn_SavedRecordCount() + { + //act + var result = await fileService.MarkFileMarkAsDeletedAsync(new[] { idMark }, CancellationToken.None); + + //assert + Assert.True(result > 0); + } + + [Fact] + public async Task MarkAsDeletedAsync_ShouldReturn_DeletedRecordCount() + { + //act + var result = await fileService.MarkAsDeletedAsync(idFile, CancellationToken.None); + + //assert + Assert.True(result > 0); + } + + [Fact] + public async Task CreateFileMarkAsync_ShouldReturn_SavedRecordCount() + { + //act + var result = await fileService.CreateFileMarkAsync(fileMark, idAuthor, CancellationToken.None); + + //assert + Assert.True(result > 0); + } +} \ No newline at end of file diff --git a/AsbCloudWebApi.Tests/Services/HelpPageServiceTest.cs b/AsbCloudWebApi.Tests/Services/HelpPageServiceTest.cs new file mode 100644 index 00000000..e722fcb9 --- /dev/null +++ b/AsbCloudWebApi.Tests/Services/HelpPageServiceTest.cs @@ -0,0 +1,97 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +using AsbCloudApp.Data; +using AsbCloudApp.Repositories; +using AsbCloudInfrastructure.Services; +using Microsoft.Extensions.Configuration; +using NSubstitute; +using Xunit; + +namespace AsbCloudWebApi.Tests.Services; + +public class HelpPageServiceTest +{ + private const string urlPage = "test"; + private const string fileName = "Справка_для_страницы_test.pdf"; + private const int idCategory = 20000; + + private static Dictionary configSettings = new() + { + { "DirectoryNameHelpPageFiles", "helpPages" } + }; + + private static readonly MemoryStream fileStream = new(Array.Empty()); + + private static readonly HelpPageDto existingHelpPage = new() + { + Id = 178, + IdCategory = idCategory, + UrlPage = "test2", + Name = "Справка_для_страницы_test2.pdf" + }; + + private readonly IHelpPageRepository helpPageRepositoryMock = Substitute.For(); + private readonly IFileStorageRepository fileStorageRepositoryMock = Substitute.For(); + + private readonly HelpPageService helpPageService; + + public HelpPageServiceTest() + { + IConfiguration configuration = new ConfigurationBuilder() + .AddInMemoryCollection(configSettings) + .Build(); + + helpPageRepositoryMock.GetOrDefaultByUrlPageAndIdCategoryAsync(existingHelpPage.UrlPage, existingHelpPage.IdCategory, Arg.Any()) + .Returns(existingHelpPage); + + helpPageRepositoryMock.InsertAsync(Arg.Any(), Arg.Any()) + .ReturnsForAnyArgs(1); + + fileStorageRepositoryMock.SaveFileAsync(Arg.Any(), Arg.Any(), Arg.Any()); + + helpPageService = new HelpPageService(helpPageRepositoryMock, + fileStorageRepositoryMock, + configuration); + } + + [Fact] + public async Task AddOrUpdateAsync_ShouldReturn_AddedHelpPage() + { + //act + var result = await helpPageService.AddOrUpdateAsync(urlPage, + idCategory, + fileName, + fileStream, + CancellationToken.None); + + //assert + await helpPageRepositoryMock.Received().InsertAsync(Arg.Any(), Arg.Any()); + await fileStorageRepositoryMock.Received().SaveFileAsync(Arg.Any(), Arg.Any(), Arg.Any()); + + Assert.NotEqual(existingHelpPage.Id, result); + Assert.NotEqual(urlPage, existingHelpPage.UrlPage); + Assert.NotEqual(fileName, existingHelpPage.Name); + Assert.Equal(idCategory, existingHelpPage.IdCategory); + } + + + [Fact] + public async Task UpdateAsync_ShouldReturn_UpdatedHelpPage() + { + //act + var result = await helpPageService.AddOrUpdateAsync(existingHelpPage.UrlPage, + existingHelpPage.IdCategory, + existingHelpPage.Name, + fileStream, + CancellationToken.None); + + //assert + await helpPageRepositoryMock.Received().UpdateAsync(Arg.Any(), Arg.Any()); + await fileStorageRepositoryMock.Received().SaveFileAsync(Arg.Any(), Arg.Any(), Arg.Any()); + + Assert.Equal(existingHelpPage.Id, result); + } +} \ No newline at end of file diff --git a/AsbCloudWebApi.Tests/UnitTests/Services/Notification/EmailNotificationTransportServiceTests.cs b/AsbCloudWebApi.Tests/Services/Notification/EmailNotificationTransportServiceTests.cs similarity index 97% rename from AsbCloudWebApi.Tests/UnitTests/Services/Notification/EmailNotificationTransportServiceTests.cs rename to AsbCloudWebApi.Tests/Services/Notification/EmailNotificationTransportServiceTests.cs index c3dc936a..724f1e7b 100644 --- a/AsbCloudWebApi.Tests/UnitTests/Services/Notification/EmailNotificationTransportServiceTests.cs +++ b/AsbCloudWebApi.Tests/Services/Notification/EmailNotificationTransportServiceTests.cs @@ -12,7 +12,7 @@ using System.Threading; using System.Threading.Tasks; using Xunit; -namespace AsbCloudWebApi.Tests.UnitTests.Services.Notification +namespace AsbCloudWebApi.Tests.Services.Notification { public class EmailNotificationTransportServiceTests { diff --git a/AsbCloudWebApi.Tests/Services/ProcessMaps/ProcessMapPlanServiceTests.cs b/AsbCloudWebApi.Tests/Services/ProcessMaps/ProcessMapPlanServiceTests.cs new file mode 100644 index 00000000..df1b5a8b --- /dev/null +++ b/AsbCloudWebApi.Tests/Services/ProcessMaps/ProcessMapPlanServiceTests.cs @@ -0,0 +1,94 @@ +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using AsbCloudApp.Data; +using AsbCloudApp.Data.ProcessMaps; +using AsbCloudApp.Repositories; +using AsbCloudApp.Services; +using AsbCloudInfrastructure.Services.ProcessMaps; +using NSubstitute; +using Xunit; + +namespace AsbCloudWebApi.Tests.Services.ProcessMaps; + +public class ProcessMapPlanServiceTests +{ + private const int idWellSectionPlan = 1; + private const int idWell = 3; + private const int idWellSectionType = 54; + + private readonly IEnumerable fakeCollectionWellSectionPlan = new WellSectionPlanDto[] + { + new() + { + Id = idWellSectionPlan, + IdWell = idWell, + IdSectionType = idWellSectionType, + DepthStart = 80, + DepthEnd = 150 + } + }; + + private readonly IEnumerable fakeCollectionWellSectionTypes = new WellSectionTypeDto[] + { + new() + { + Id = idWellSectionType, + Caption = "Направление 1", + Order = 1 + } + }; + + private readonly ICrudRepository wellSectionTypeRepositoryMock = + Substitute.For>(); + + private readonly IProcessMapPlanRepository processMapPlanRepositoryMock = + Substitute.For>(); + + private readonly IRepositoryWellRelated wellSectionPlanRepositoryMock = + Substitute.For>(); + + private readonly ProcessMapPlanService processMapPlanService; + + public ProcessMapPlanServiceTests() + { + processMapPlanService = new ProcessMapPlanService(wellSectionTypeRepositoryMock, + processMapPlanRepositoryMock, wellSectionPlanRepositoryMock); + + wellSectionPlanRepositoryMock.GetByIdWellAsync(Arg.Any(), Arg.Any()) + .ReturnsForAnyArgs(fakeCollectionWellSectionPlan); + + wellSectionTypeRepositoryMock.GetAllAsync(Arg.Any()) + .ReturnsForAnyArgs(fakeCollectionWellSectionTypes); + } + + [Theory] + [InlineData(80, 150, true)] + [InlineData(90, 140, true)] + [InlineData(0, 110, false)] + [InlineData(110, 200, false)] + public async Task GetAsync_ReturnsValidatedCollectionProcessMapPlanWellDrilling(int depthStart, int depthEnd, bool isValidCollection) + { + //arrange + var fakeCollectionProcessMapPlanWellDrilling = new ProcessMapPlanWellDrillingDto[] + { + new() + { + IdWellSectionType = idWellSectionType, + DepthStart = depthStart, + DepthEnd = depthEnd + } + }; + + processMapPlanRepositoryMock.GetByIdWellAsync(Arg.Any(), Arg.Any()) + .ReturnsForAnyArgs(fakeCollectionProcessMapPlanWellDrilling); + + //act + var result = (await processMapPlanService.GetAsync(idWell, CancellationToken.None)).ToArray(); + + //assert + Assert.Equal(isValidCollection, result.All(r => r.IsValid)); + Assert.Single(result); + } +} \ No newline at end of file diff --git a/AsbCloudWebApi.Tests/Services/SAUB/TelemetryDataSaubCacheTests.cs b/AsbCloudWebApi.Tests/Services/SAUB/TelemetryDataSaubCacheTests.cs new file mode 100644 index 00000000..7e771fb2 --- /dev/null +++ b/AsbCloudWebApi.Tests/Services/SAUB/TelemetryDataSaubCacheTests.cs @@ -0,0 +1,65 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using AsbCloudApp.Data.SAUB; +using AsbCloudDb.Model; +using AsbCloudInfrastructure.Background; +using AsbCloudInfrastructure.Services.SAUB; +using Microsoft.Extensions.DependencyInjection; +using NSubstitute; +using Xunit; + +namespace AsbCloudWebApi.Tests.Services.SAUB; + +public class TelemetryDataSaubCacheTests +{ + private const int idTelemetry = 1; + + private readonly IEnumerable fakeTelemetries = new[] + { + new TelemetryDataSaubDto() + }; + + private readonly IServiceProvider serviceProviderMock = Substitute.For(); + + private readonly TelemetryDataCache telemetryDataCache; + private readonly Type telemetryDataCacheType; + + public TelemetryDataSaubCacheTests() + { + serviceProviderMock.GetService().Returns(new BackgroundWorker(serviceProviderMock)); + + telemetryDataCache = TelemetryDataCache.GetInstance(serviceProviderMock); + + telemetryDataCacheType = telemetryDataCache.GetType(); + } + + [Fact] + public void AddRange_ShouldReturn_AddedElementToCache() + { + //arrange + telemetryDataCacheType.GetField("isLoading", BindingFlags.NonPublic | BindingFlags.Instance)?.SetValue(telemetryDataCache, false); + + //act + telemetryDataCache.AddRange(idTelemetry, fakeTelemetries); + var lastTelemetry = telemetryDataCache.GetLastOrDefault(idTelemetry); + + //assert + Assert.Equal(lastTelemetry, fakeTelemetries.Last()); + } + + [Fact] + public void AddRange_ShouldReturn_NotAddedToCache() + { + //arrange + telemetryDataCacheType.GetField("isLoading", BindingFlags.NonPublic | BindingFlags.Instance)?.SetValue(telemetryDataCache, true); + + //act + telemetryDataCache.AddRange(idTelemetry, fakeTelemetries); + var lastTelemetry = telemetryDataCache.GetLastOrDefault(idTelemetry); + + //assert + Assert.Null(lastTelemetry ); + } +} \ No newline at end of file diff --git a/AsbCloudWebApi.Tests/UnitTests/Services/Trajectory/Templates/TrajectoryFactManualTemplate.xlsx b/AsbCloudWebApi.Tests/Services/Trajectory/Templates/TrajectoryFactManualTemplate.xlsx similarity index 100% rename from AsbCloudWebApi.Tests/UnitTests/Services/Trajectory/Templates/TrajectoryFactManualTemplate.xlsx rename to AsbCloudWebApi.Tests/Services/Trajectory/Templates/TrajectoryFactManualTemplate.xlsx diff --git a/AsbCloudWebApi.Tests/UnitTests/Services/Trajectory/Templates/TrajectoryPlanTemplate.xlsx b/AsbCloudWebApi.Tests/Services/Trajectory/Templates/TrajectoryPlanTemplate.xlsx similarity index 100% rename from AsbCloudWebApi.Tests/UnitTests/Services/Trajectory/Templates/TrajectoryPlanTemplate.xlsx rename to AsbCloudWebApi.Tests/Services/Trajectory/Templates/TrajectoryPlanTemplate.xlsx diff --git a/AsbCloudWebApi.Tests/UnitTests/Services/Trajectory/TrajectoryExportTest.cs b/AsbCloudWebApi.Tests/Services/Trajectory/TrajectoryExportTest.cs similarity index 98% rename from AsbCloudWebApi.Tests/UnitTests/Services/Trajectory/TrajectoryExportTest.cs rename to AsbCloudWebApi.Tests/Services/Trajectory/TrajectoryExportTest.cs index 0bc9c2d4..79b63ac6 100644 --- a/AsbCloudWebApi.Tests/UnitTests/Services/Trajectory/TrajectoryExportTest.cs +++ b/AsbCloudWebApi.Tests/Services/Trajectory/TrajectoryExportTest.cs @@ -8,7 +8,7 @@ using System.Threading; using System.Threading.Tasks; using Xunit; -namespace AsbCloudWebApi.Tests.UnitTests.Services.Trajectory +namespace AsbCloudWebApi.Tests.Services.Trajectory { public class TrajectoryExportTest { diff --git a/AsbCloudWebApi.Tests/UnitTests/Services/Trajectory/TrajectoryImportTest.cs b/AsbCloudWebApi.Tests/Services/Trajectory/TrajectoryImportTest.cs similarity index 94% rename from AsbCloudWebApi.Tests/UnitTests/Services/Trajectory/TrajectoryImportTest.cs rename to AsbCloudWebApi.Tests/Services/Trajectory/TrajectoryImportTest.cs index cb151ce5..e6763582 100644 --- a/AsbCloudWebApi.Tests/UnitTests/Services/Trajectory/TrajectoryImportTest.cs +++ b/AsbCloudWebApi.Tests/Services/Trajectory/TrajectoryImportTest.cs @@ -2,14 +2,14 @@ using System.Linq; using Xunit; -namespace AsbCloudWebApi.Tests.UnitTests.Services.Trajectory +namespace AsbCloudWebApi.Tests.Services.Trajectory { public class TrajectoryImportTest { private readonly TrajectoryPlanParserService trajectoryPlanImportService; private readonly TrajectoryFactManualParserService trajectoryFactManualImportService; - private string usingTemplateFile = "AsbCloudWebApi.Tests.UnitTests.Services.Trajectory.Templates"; + private string usingTemplateFile = "AsbCloudWebApi.Tests.Services.Trajectory.Templates"; public TrajectoryImportTest() { diff --git a/AsbCloudWebApi.Tests/Services/TrajectoryVisualizationServiceTest.cs b/AsbCloudWebApi.Tests/Services/TrajectoryVisualizationServiceTest.cs new file mode 100644 index 00000000..d6776eb9 --- /dev/null +++ b/AsbCloudWebApi.Tests/Services/TrajectoryVisualizationServiceTest.cs @@ -0,0 +1,196 @@ +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using AsbCloudApp.Data; +using AsbCloudApp.Data.Trajectory; +using AsbCloudApp.Repositories; +using AsbCloudApp.Requests; +using AsbCloudInfrastructure.Services.Trajectory; +using NSubstitute; +using Xunit; + +namespace AsbCloudWebApi.Tests.Services; + +public class TrajectoryVisualizationServiceTest +{ + private readonly ITrajectoryEditableRepository trajectoryPlanRepositoryMock = Substitute.For>(); + private readonly ITrajectoryEditableRepository trajectoryFactRepositoryMock = Substitute.For>(); + private readonly ITrajectoryNnbRepository trajectoryNnbRepositoryMock = Substitute.For(); + + private readonly TrajectoryService trajectoryService; + + public TrajectoryVisualizationServiceTest() + { + trajectoryService = new TrajectoryService(trajectoryPlanRepositoryMock, trajectoryFactRepositoryMock, trajectoryNnbRepositoryMock); + } + + [Fact] + public async Task GetTrajectoryAsync_ShouldReturn_SameCounts() + { + //arrange + var plannedTrajectory = new TrajectoryGeoPlanDto[] + { + new() { WellboreDepth = 0d, ZenithAngle = 0d, AzimuthGeo = 0d }, + new() { WellboreDepth = 0d, ZenithAngle = 0d, AzimuthGeo = 10d }, + new() { WellboreDepth = 0d, ZenithAngle = 30d, AzimuthGeo = 20d }, + new() { WellboreDepth = 30d, ZenithAngle = 0d, AzimuthGeo = 30d }, + new() { WellboreDepth = 30d, ZenithAngle = 90d, AzimuthGeo = 40d }, + new() { WellboreDepth = 0d, ZenithAngle = 0d, AzimuthGeo = 50d }, + }; + + var actualTrajectory = new TrajectoryGeoFactDto[] + { + new() { WellboreDepth = 0, ZenithAngle = 0, AzimuthGeo = 0 }, + new() { WellboreDepth = 30, ZenithAngle = 30, AzimuthGeo = 10 }, + new() { WellboreDepth = 0, ZenithAngle = 0, AzimuthGeo = 20 }, + }; + + var nnbTrajectory = new TrajectoryGeoFactDto[] + { + new() { WellboreDepth = 0, ZenithAngle = 0, AzimuthGeo = 0 }, + new() { WellboreDepth = 30, ZenithAngle = 30, AzimuthGeo = 10 }, + new() { WellboreDepth = 0, ZenithAngle = 0, AzimuthGeo = 20 }, + new() { WellboreDepth = 0, ZenithAngle = 10, AzimuthGeo = 20 }, + }; + + trajectoryPlanRepositoryMock.GetAsync(Arg.Any(), Arg.Any()) + .ReturnsForAnyArgs(plannedTrajectory); + + trajectoryFactRepositoryMock.GetAsync(Arg.Any(), Arg.Any()) + .ReturnsForAnyArgs(actualTrajectory); + + trajectoryNnbRepositoryMock.GetAsync(Arg.Any(), Arg.Any()) + .ReturnsForAnyArgs(nnbTrajectory); + + //act + var result = await trajectoryService.GetTrajectoryCartesianAsync(1, CancellationToken.None); + + //assert + Assert.Equal(plannedTrajectory.Count(), result.Plan?.Count()); + Assert.Equal(actualTrajectory.Count(), result.FactManual?.Count()); + Assert.Equal(nnbTrajectory.Count(), result.FactNnb?.Count()); + } + + [Fact] + public async Task GetTrajectoryAsync_ShouldReturn_StraightBore() + { + //arrange + var plannedTrajectory = new TrajectoryGeoPlanDto[] + { + new() { WellboreDepth = 0, ZenithAngle = 0, AzimuthGeo = 0 }, + new() { WellboreDepth = 0, ZenithAngle = 0, AzimuthGeo = 0 }, + new() { WellboreDepth = 20, ZenithAngle = 0, AzimuthGeo = 0 }, + new() { WellboreDepth = 20, ZenithAngle = 0, AzimuthGeo = 0 }, + new() { WellboreDepth = 30, ZenithAngle = 0, AzimuthGeo = 0 }, + new() { WellboreDepth = 50, ZenithAngle = 0, AzimuthGeo = 0 }, + }; + + var actualTrajectory = new TrajectoryGeoFactDto[] + { + new() { WellboreDepth = 0, ZenithAngle = 0, AzimuthGeo = 0 }, + new() { WellboreDepth = 0, ZenithAngle = 0, AzimuthGeo = 0 }, + new() { WellboreDepth = 20, ZenithAngle = 0, AzimuthGeo = 0 }, + new() { WellboreDepth = 20, ZenithAngle = 0, AzimuthGeo = 0 }, + new() { WellboreDepth = 30, ZenithAngle = 0, AzimuthGeo = 0 }, + new() { WellboreDepth = 50, ZenithAngle = 0, AzimuthGeo = 0 }, + }; + + var nnbTrajectory = new TrajectoryGeoFactDto[] + { + new() { WellboreDepth = 0, ZenithAngle = 0, AzimuthGeo = 0 }, + new() { WellboreDepth = 0, ZenithAngle = 0, AzimuthGeo = 0 }, + new() { WellboreDepth = 20, ZenithAngle = 0, AzimuthGeo = 0 }, + new() { WellboreDepth = 20, ZenithAngle = 0, AzimuthGeo = 0 }, + new() { WellboreDepth = 30, ZenithAngle = 0, AzimuthGeo = 0 }, + new() { WellboreDepth = 50, ZenithAngle = 0, AzimuthGeo = 0 }, + }; + + trajectoryPlanRepositoryMock.GetAsync(Arg.Any(), Arg.Any()) + .ReturnsForAnyArgs(plannedTrajectory); + + trajectoryFactRepositoryMock.GetAsync(Arg.Any(), Arg.Any()) + .ReturnsForAnyArgs(actualTrajectory); + + trajectoryNnbRepositoryMock.GetAsync(Arg.Any(), Arg.Any()) + .ReturnsForAnyArgs(nnbTrajectory); + + //act + var result = await trajectoryService.GetTrajectoryCartesianAsync(1, CancellationToken.None); + + //assert + var lastPointPlan = result.Plan!.Last(); + var lastPointFact = result.FactManual!.Last(); + var lastPointNnb = result.FactNnb!.Last(); + + Assert.Equal(0d, lastPointPlan.X, 0.1d); + Assert.Equal(-50d, lastPointPlan.Y, 0.1d); + Assert.Equal(0d, lastPointPlan.Z, 0.1d); + + Assert.Equal(0d, lastPointFact.X, 0.1d); + Assert.Equal(-50d, lastPointFact.Y, 0.1d); + Assert.Equal(0d, lastPointFact.Z, 0.1d); + + Assert.Equal(0d, lastPointNnb.X, 0.1d); + Assert.Equal(-50d, lastPointNnb.Y, 0.1d); + Assert.Equal(0d, lastPointNnb.Z, 0.1d); + } + + [Fact] + public async Task GetTrajectoryAsync_ShouldReturn_Match() + { + //arrange + const double tolerancePlan = 0.001d; + const double toleranceFact = 0.001d; + + var plannedTrajectory = new TrajectoryGeoPlanDto[] + { + new() { WellboreDepth = 0, ZenithAngle = 0, AzimuthGeo = 0 }, + new() { WellboreDepth = 10, ZenithAngle = 30, AzimuthGeo = 30 }, + new() { WellboreDepth = 20, ZenithAngle = 0, AzimuthGeo = 0 }, + }; + + var actualTrajectory = new TrajectoryGeoFactDto[] + { + new() { WellboreDepth = 0, ZenithAngle = 0, AzimuthGeo = 0 }, + new() { WellboreDepth = 10, ZenithAngle = 30, AzimuthGeo = 30 }, + new() { WellboreDepth = 20, ZenithAngle = 0, AzimuthGeo = 0 }, + }; + + var nnbTrajectory = new TrajectoryGeoFactDto[] + { + new() { WellboreDepth = 0, ZenithAngle = 0, AzimuthGeo = 0 }, + new() { WellboreDepth = 10, ZenithAngle = 30, AzimuthGeo = 30 }, + new() { WellboreDepth = 20, ZenithAngle = 0, AzimuthGeo = 0 }, + }; + + + trajectoryPlanRepositoryMock.GetAsync(Arg.Any(), Arg.Any()) + .ReturnsForAnyArgs(plannedTrajectory); + + trajectoryFactRepositoryMock.GetAsync(Arg.Any(), Arg.Any()) + .ReturnsForAnyArgs(actualTrajectory); + + trajectoryNnbRepositoryMock.GetAsync(Arg.Any(), Arg.Any()) + .ReturnsForAnyArgs(nnbTrajectory); + + //act + var result = await trajectoryService.GetTrajectoryCartesianAsync(1, CancellationToken.None); + + //assert + var lastPointPlan = result.Plan!.Last(); + var lastPointFact = result.FactManual!.Last(); + var lastPointNnb = result.FactManual!.Last(); + + Assert.InRange(lastPointPlan.Z, -10 - tolerancePlan, 0 - tolerancePlan); + Assert.InRange(lastPointPlan.Y, -20 - tolerancePlan, -10 + tolerancePlan); + Assert.InRange(lastPointPlan.X, 0 + tolerancePlan, 10 - tolerancePlan); + + Assert.InRange(lastPointFact.Z, -10 - toleranceFact, 0 - toleranceFact); + Assert.InRange(lastPointFact.Y, -20 - toleranceFact, -10 + toleranceFact); + Assert.InRange(lastPointFact.X, 0 + toleranceFact, 10 - toleranceFact); + + Assert.InRange(lastPointNnb.Z, -10 - toleranceFact, 0 - toleranceFact); + Assert.InRange(lastPointNnb.Y, -20 - toleranceFact, -10 + toleranceFact); + Assert.InRange(lastPointNnb.X, 0 + toleranceFact, 10 - toleranceFact); + } +} \ No newline at end of file diff --git a/AsbCloudWebApi.Tests/Services/WellFinalDocumentsServiceTest.cs b/AsbCloudWebApi.Tests/Services/WellFinalDocumentsServiceTest.cs new file mode 100644 index 00000000..a85ca068 --- /dev/null +++ b/AsbCloudWebApi.Tests/Services/WellFinalDocumentsServiceTest.cs @@ -0,0 +1,168 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +using AsbCloudApp.Data; +using AsbCloudApp.Data.User; +using AsbCloudApp.Repositories; +using AsbCloudApp.Services; +using AsbCloudApp.Services.Notifications; +using AsbCloudInfrastructure.Services; +using Microsoft.Extensions.Configuration; +using NSubstitute; +using Xunit; + +namespace AsbCloudWebApi.Tests.Services; + +public class WellFinalDocumentsServiceTest +{ + private const int idWell = 1; + private const int validInsertedFileId = 555; + private const int idWellFinalDocCategory = 10_000; + private const string editPublisherPermission = "WellFinalDocuments.editPublisher"; + private const string fileName = "test.txt"; + + private static readonly MemoryStream fileStream = new(Array.Empty()); + + private static readonly WellFinalDocumentDto wellFinalDocument = new() + { + IdCategory = idWellFinalDocCategory, + PermissionToUpload = true, + Publishers = new List + { + new() + { + Id = 1 + } + } + }; + + private static readonly UserExtendedDto user = new() + { + Id = 1, + IdCompany = 1, + Surname = "Tester 1", + Name = "Peppa", + Email = "test@test.com" + }; + + private static readonly WellCaseDto wellCase = new() + { + IdWell = 1, + PermissionToSetPubliher = true, + WellFinalDocuments = new[] { wellFinalDocument } + }; + + private static readonly WellFinalDocumentDBDto wellFinalDocumentDB = new() + { + IdCategory = idWellFinalDocCategory, + IdUser = 1, + IdWell = 1 + }; + + private static readonly NotificationCategoryDto notificationCategory = new() + { + Id = 20000, + Name = "Системные уведомления" + }; + + private static readonly WellDto well = new() + { + Id = 1, + Caption = "well 1", + Cluster = "cluster 1", + Deposit = "deposit 1" + }; + + private static readonly FileCategoryDto fileCategory = new() + { + Id = idWellFinalDocCategory, + Name = "Проект на бурение транспортного и горизонтального участков скважины" + }; + + private readonly IConfiguration configuration = new ConfigurationBuilder().Build(); + private readonly IUserRepository userRepositoryMock = Substitute.For(); + private readonly IFileCategoryService fileCategoryServiceMock = Substitute.For(); + private readonly ICrudRepository notificationCategoryRepositoryMock = Substitute.For>(); + private readonly IFileRepository fileRepositoryMock = Substitute.For(); + private readonly IWellFinalDocumentsRepository wellFinalDocumentsRepositoryMock = Substitute.For(); + private readonly IWellService wellServiceMock = Substitute.For(); + private readonly INotificationRepository notificationRepositoryMock = Substitute.For(); + private readonly INotificationTransportService notificationTransportServiceMock = Substitute.For(); + private readonly IFileStorageRepository fileStorageRepositoryMock = Substitute.For(); + + private readonly WellFinalDocumentsService wellFinalDocumentsService; + private readonly FileService fileService; + private readonly NotificationService notificationService; + + + public WellFinalDocumentsServiceTest() + { + wellFinalDocumentsRepositoryMock.GetByWellIdAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .ReturnsForAnyArgs(wellCase); + + wellFinalDocumentsRepositoryMock.GetCategoryAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .ReturnsForAnyArgs(wellFinalDocumentDB); + + fileRepositoryMock.InsertAsync(Arg.Any(), Arg.Any()) + .ReturnsForAnyArgs(validInsertedFileId); + + fileRepositoryMock.GetOrDefaultAsync(validInsertedFileId, Arg.Any()) + .ReturnsForAnyArgs(new FileInfoDto { Id = validInsertedFileId }); + + userRepositoryMock.GetAllAsync(Arg.Any()) + .ReturnsForAnyArgs(new[] { user }); + + userRepositoryMock.GetOrDefault(Arg.Any()) + .ReturnsForAnyArgs(user); + + userRepositoryMock.GetOrDefaultAsync(Arg.Any(), Arg.Any()) + .ReturnsForAnyArgs(user); + + userRepositoryMock.HasPermission(user.Id, editPublisherPermission) + .ReturnsForAnyArgs(true); + + wellServiceMock.GetOrDefaultAsync(Arg.Any(), Arg.Any()) + .ReturnsForAnyArgs(well); + + notificationCategoryRepositoryMock.GetOrDefaultAsync(Arg.Any(), + Arg.Any()) + .ReturnsForAnyArgs(notificationCategory); + + fileCategoryServiceMock.GetOrDefaultAsync(idWellFinalDocCategory, Arg.Any()) + .ReturnsForAnyArgs(fileCategory); + + notificationService = new NotificationService(notificationCategoryRepositoryMock, + notificationRepositoryMock, + new[] { notificationTransportServiceMock }); + + fileService = new FileService(fileRepositoryMock, fileStorageRepositoryMock); + + wellFinalDocumentsService = new WellFinalDocumentsService(fileService, userRepositoryMock, wellServiceMock, configuration, + fileCategoryServiceMock, + wellFinalDocumentsRepositoryMock, + notificationService); + } + + [Fact] + public async Task GetHistoryFileByIdCategory_ShouldReturn_EmptyHistory() + { + //act + var data = await wellFinalDocumentsService.GetFilesHistoryByIdCategoryAsync(idWell, idWellFinalDocCategory, CancellationToken.None); + + //assert + Assert.NotNull(data); + Assert.Empty(data.Files); + } + + [Fact] + public async Task SaveCategoryFile_ShouldReturn_FileId() + { + //act + var idFile = await wellFinalDocumentsService.SaveCategoryFileAsync(idWell, idWellFinalDocCategory, user.Id, fileStream, fileName, CancellationToken.None); + + //assert + Assert.Equal(validInsertedFileId, idFile); + } +} \ No newline at end of file diff --git a/AsbCloudWebApi.Tests/UnitTests/Services/WellOperationExport/WellOperationExportServiceTest.cs b/AsbCloudWebApi.Tests/Services/WellOperationExport/WellOperationExportServiceTest.cs similarity index 98% rename from AsbCloudWebApi.Tests/UnitTests/Services/WellOperationExport/WellOperationExportServiceTest.cs rename to AsbCloudWebApi.Tests/Services/WellOperationExport/WellOperationExportServiceTest.cs index 2994f541..2590df26 100644 --- a/AsbCloudWebApi.Tests/UnitTests/Services/WellOperationExport/WellOperationExportServiceTest.cs +++ b/AsbCloudWebApi.Tests/Services/WellOperationExport/WellOperationExportServiceTest.cs @@ -19,7 +19,7 @@ using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; -namespace AsbCloudWebApi.Tests.UnitTests.Services.WellOperationExport +namespace AsbCloudWebApi.Tests.Services.WellOperationExport { public class WellOperationExportServiceTest { @@ -188,11 +188,11 @@ namespace AsbCloudWebApi.Tests.UnitTests.Services.WellOperationExport private static IEnumerable GetPropsWithDefaultValue(T dto, params string[] excludeProps) { IEnumerable props = typeof(T).GetProperties( - BindingFlags.Public + BindingFlags.Public | BindingFlags.Instance); props = props - .Where(prop=>prop.CanWrite) + .Where(prop => prop.CanWrite) .Where(prop => !excludeProps.Contains(prop.Name)); foreach (var prop in props) diff --git a/AsbCloudWebApi.Tests/Services/WellboreServiceTest.cs b/AsbCloudWebApi.Tests/Services/WellboreServiceTest.cs new file mode 100644 index 00000000..7f647158 --- /dev/null +++ b/AsbCloudWebApi.Tests/Services/WellboreServiceTest.cs @@ -0,0 +1,280 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using AsbCloudApp.Data; +using AsbCloudApp.Data.SAUB; +using AsbCloudApp.Repositories; +using AsbCloudApp.Requests; +using AsbCloudApp.Services; +using AsbCloudInfrastructure.Services; +using NSubstitute; +using Xunit; + +namespace AsbCloudWebApi.Tests.Services; + +public class WellboreServiceTest +{ + private static readonly WellDto well1 = new() + { + Id = 1, + IdState = 1, + IdTelemetry = 1, + LastTelemetryDate = DateTime.Now, + Caption = "well 1" + }; + + private static readonly WellDto well2 = new() + { + Id = 2, + IdState = 1, + IdTelemetry = 100, + LastTelemetryDate = DateTime.Now, + Caption = "well 2" + }; + + private readonly IWellService wellServiceMock = Substitute.For(); + private readonly IWellOperationRepository wellOperationRepositoryMock = Substitute.For(); + private readonly ITelemetryDataCache telemetryDataCacheMock = Substitute.For>(); + + private readonly WellboreService wellboreService; + + public WellboreServiceTest() + { + wellboreService = new WellboreService(wellServiceMock, wellOperationRepositoryMock, telemetryDataCacheMock); + } + + [Fact] + public async Task GetWellboresAsync_ShouldReturn_EmptyCollection() + { + var result = await wellboreService.GetWellboresAsync(new[] { 1 }, CancellationToken.None); + + Assert.NotNull(result); + Assert.False(result.Any()); + } + + [Fact] + public async Task GetWellboresAsync_ShouldReturn_OneWellboreByWellOnly() + { + wellServiceMock.GetAsync(Arg.Any(), Arg.Any()) + .Returns(new[] { well1 }); + + var result = await wellboreService.GetWellboresAsync(new[] { 1 }, CancellationToken.None); + + Assert.Single(result); + var wellbore0 = result.ElementAt(0); + Assert.Equal(well1.Caption, wellbore0.Well.Caption); + Assert.Equal(well1.Id, wellbore0.Well.Id); + + Assert.Equal("Ствол 1", wellbore0.Name); + Assert.Equal(1, wellbore0.Id); + + Assert.Equal(default, wellbore0.DateStart); + Assert.Equal(default, wellbore0.DateEnd); + Assert.Equal(default, wellbore0.DepthStart); + Assert.Equal(default, wellbore0.DepthEnd); + } + + [Fact] + public async Task GetWellboresAsync_ShouldReturn_TwoWellboreByTwoWellsOnly() + { + wellServiceMock.GetAsync(Arg.Any(), Arg.Any()) + .Returns(new[] { well1, well2 }); + + var result = await wellboreService.GetWellboresAsync(new[] { 1 }, CancellationToken.None); + + Assert.Equal(2, result.Count()); + } + + [Fact] + public async Task GetWellboresAsync_ShouldReturn_TwoWellboreByWellWithSections() + { + wellServiceMock.GetAsync(Arg.Any(), Arg.Any()) + .Returns(new[] { well1 }); + + var section0 = new SectionByOperationsDto + { + IdWell = well1.Id, + IdWellSectionType = 0, + IdType = 1, + DateStart = new DateTime(2023, 01, 01), + DateEnd = new DateTime(2023, 01, 02), + DepthStart = 000, + DepthEnd = 100 + }; + var section1 = new SectionByOperationsDto + { + IdWell = well1.Id, + IdWellSectionType = 0, + IdType = 1, + DateStart = new DateTime(2023, 01, 02), + DateEnd = new DateTime(2023, 01, 03), + DepthStart = 100, + DepthEnd = 300 + }; + var section2 = new SectionByOperationsDto + { + IdWell = well1.Id, + IdWellSectionType = 0, + IdType = 1, + DateStart = new DateTime(2023, 01, 03), + DateEnd = new DateTime(2023, 01, 04), + DepthStart = 200, + DepthEnd = 210 + }; + var section3 = new SectionByOperationsDto + { + IdWell = int.MaxValue, + IdWellSectionType = 0, + IdType = 1, + DateStart = new DateTime(2023, 01, 03), + DateEnd = new DateTime(2023, 01, 04), + DepthStart = 200, + DepthEnd = 220 + }; + var section4 = new SectionByOperationsDto + { + IdWell = well1.Id, + IdWellSectionType = 0, + IdType = 0, + DateStart = new DateTime(2023, 01, 05), + DateEnd = new DateTime(2023, 01, 06), + DepthStart = 150, + DepthEnd = 220 + }; + + wellOperationRepositoryMock.GetSectionsAsync(Arg.Any>(), Arg.Any()) + .Returns(new[] { section0, section1, section2, section3, section4, }); + + var result = await wellboreService.GetWellboresAsync(new[] { 1 }, CancellationToken.None); + + Assert.Equal(2, result.Count()); + var wellbore0 = result.ElementAt(0); + Assert.Equal(well1.Caption, wellbore0.Well.Caption); + Assert.Equal(well1.Id, wellbore0.Well.Id); + + Assert.Equal("Ствол 1", wellbore0.Name); + Assert.Equal(1, wellbore0.Id); + + Assert.Equal(section0.DateStart, wellbore0.DateStart); + Assert.Equal(section0.DepthStart, wellbore0.DepthStart); + Assert.Equal(section1.DateEnd, wellbore0.DateEnd); + Assert.Equal(section1.DepthEnd, wellbore0.DepthEnd); + + var wellbore1 = result.ElementAt(1); + Assert.Equal(well1.Caption, wellbore1.Well.Caption); + Assert.Equal(well1.Id, wellbore1.Well.Id); + + Assert.Equal("Ствол 2", wellbore1.Name); + Assert.Equal(2, wellbore1.Id); + + Assert.Equal(section2.DateStart, wellbore1.DateStart); + Assert.Equal(section2.DepthStart, wellbore1.DepthStart); + Assert.Equal(section2.DateEnd, wellbore1.DateEnd); + Assert.Equal(section2.DepthEnd, wellbore1.DepthEnd); + } + + + [Fact] + public async Task GetWellboresAsync_ShouldReturn_OneWellboreByWellWithTelemetry() + { + wellServiceMock.GetAsync(Arg.Any(), Arg.Any()) + .Returns(new[] { well1 }); + + var firstCacheItem = new TelemetryDataSaubDto { DateTime = new DateTime(2000, 01, 01), WellDepth = 0, }; + var lastCacheItem = new TelemetryDataSaubDto { DateTime = new DateTime(2023, 01, 05), WellDepth = 321, }; + + telemetryDataCacheMock.GetOrDefaultFirstLast(Arg.Any()) + .Returns((firstCacheItem, lastCacheItem)); + + var result = await wellboreService.GetWellboresAsync(new[] { 1 }, CancellationToken.None); + + Assert.Single(result); + var wellbore0 = result.ElementAt(0); + Assert.Equal(well1.Caption, wellbore0.Well.Caption); + Assert.Equal(well1.Id, wellbore0.Well.Id); + + Assert.Equal("Ствол 1", wellbore0.Name); + Assert.Equal(1, wellbore0.Id); + + Assert.Equal(firstCacheItem.DateTime, wellbore0.DateStart); + Assert.Equal(firstCacheItem.WellDepth, wellbore0.DepthStart); + Assert.Equal(lastCacheItem.DateTime, wellbore0.DateEnd); + Assert.Equal(lastCacheItem.WellDepth, wellbore0.DepthEnd); + } + + [Fact] + public async Task GetWellboresAsync_ShouldReturn_TwoWellboreByWellWithAll() + { + wellServiceMock.GetAsync(Arg.Any(), Arg.Any()) + .Returns(new[] { well1 }); + + var section0 = new SectionByOperationsDto + { + IdWell = well1.Id, + IdWellSectionType = 0, + IdType = 1, + DateStart = new DateTime(2023, 01, 01), + DateEnd = new DateTime(2023, 01, 02), + DepthStart = 000, + DepthEnd = 100 + }; + var section1 = new SectionByOperationsDto + { + IdWell = well1.Id, + IdWellSectionType = 0, + IdType = 1, + DateStart = new DateTime(2023, 01, 02), + DateEnd = new DateTime(2023, 01, 03), + DepthStart = 100, + DepthEnd = 300 + }; + var section2 = new SectionByOperationsDto + { + IdWell = well1.Id, + IdWellSectionType = 0, + IdType = 1, + DateStart = new DateTime(2023, 01, 03), + DateEnd = new DateTime(2023, 01, 04), + DepthStart = 200, + DepthEnd = 210 + }; + + wellOperationRepositoryMock.GetSectionsAsync(Arg.Any>(), Arg.Any()) + .Returns(new[] { section0, section1, section2 }); + + var firstCacheItem = new TelemetryDataSaubDto { DateTime = new DateTime(2000, 01, 01), WellDepth = 0, }; + var lastCacheItem = new TelemetryDataSaubDto { DateTime = new DateTime(2023, 01, 05), WellDepth = 321, }; + + telemetryDataCacheMock.GetOrDefaultFirstLast(Arg.Any()) + .Returns((firstCacheItem, lastCacheItem)); + + var result = await wellboreService.GetWellboresAsync(new[] { 1 }, CancellationToken.None); + + Assert.Equal(2, result.Count()); + var wellbore0 = result.ElementAt(0); + Assert.Equal(well1.Caption, wellbore0.Well.Caption); + Assert.Equal(well1.Id, wellbore0.Well.Id); + + Assert.Equal("Ствол 1", wellbore0.Name); + Assert.Equal(1, wellbore0.Id); + + Assert.Equal(section0.DateStart, wellbore0.DateStart); + Assert.Equal(section0.DepthStart, wellbore0.DepthStart); + Assert.Equal(section1.DateEnd, wellbore0.DateEnd); + Assert.Equal(section1.DepthEnd, wellbore0.DepthEnd); + + var wellbore1 = result.ElementAt(1); + Assert.Equal(well1.Caption, wellbore1.Well.Caption); + Assert.Equal(well1.Id, wellbore1.Well.Id); + + Assert.Equal("Ствол 2", wellbore1.Name); + Assert.Equal(2, wellbore1.Id); + + Assert.Equal(section2.DateStart, wellbore1.DateStart); + Assert.Equal(section2.DepthStart, wellbore1.DepthStart); + Assert.Equal(lastCacheItem.DateTime, wellbore1.DateEnd); + Assert.Equal(lastCacheItem.WellDepth, wellbore1.DepthEnd); + } +} \ No newline at end of file diff --git a/AsbCloudWebApi.Tests/UnitTests/Background/BackgroundWorkerTest.cs b/AsbCloudWebApi.Tests/UnitTests/Background/BackgroundWorkerTest.cs deleted file mode 100644 index aaafe317..00000000 --- a/AsbCloudWebApi.Tests/UnitTests/Background/BackgroundWorkerTest.cs +++ /dev/null @@ -1,119 +0,0 @@ -using System; -using System.Reflection; -using System.Threading; -using System.Threading.Tasks; -using AsbCloudInfrastructure.Background; -using Microsoft.Extensions.DependencyInjection; -using NSubstitute; -using Xunit; - -namespace AsbCloudWebApi.Tests.UnitTests.Background; - -public class BackgroundWorkerTest -{ - private readonly IServiceProvider serviceProviderMock = Substitute.For(); - private readonly IServiceScope serviceScopeMock = Substitute.For(); - private readonly IServiceScopeFactory serviceScopeFactoryMock = Substitute.For(); - - private readonly BackgroundWorker backgroundWorker; - - public BackgroundWorkerTest() - { - serviceScopeFactoryMock.CreateScope().Returns(serviceScopeMock); - ((ISupportRequiredService)serviceProviderMock).GetRequiredService(typeof(IServiceScopeFactory)).Returns(serviceScopeFactoryMock); - - backgroundWorker = new BackgroundWorker(serviceProviderMock); - typeof(BackgroundWorker) - .GetField("minDelay", BindingFlags.NonPublic | BindingFlags.Instance) - ?.SetValue(backgroundWorker, TimeSpan.FromMilliseconds(1)); - } - - [Fact] - public async Task Enqueue_ShouldReturn_WorkCount() - { - //arrange - const int 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); - backgroundWorker.Enqueue(work); - } - - await backgroundWorker.ExecuteTask; - - //assert - Assert.Equal(workCount, result); - } - - [Fact] - public async Task Enqueue_Continues_AfterExceptions() - { - //arrange - const int expectadResult = 42; - var result = 0; - - Task workAction(string id, IServiceProvider services, Action callback, CancellationToken token) - { - result = expectadResult; - return Task.CompletedTask; - } - - var goodWork = Work.CreateByDelegate("", workAction); - - Task failAction(string id, IServiceProvider services, Action callback, CancellationToken token) - => throw new Exception(); - - var badWork = Work.CreateByDelegate("", failAction); - badWork.OnErrorAsync = (id, exception, token) => throw new Exception(); - - //act - backgroundWorker.Enqueue(badWork); - backgroundWorker.Enqueue(goodWork); - - await backgroundWorker.ExecuteTask; - - //assert - Assert.Equal(expectadResult, result); - Assert.Equal(1, backgroundWorker.Felled.Count); - Assert.Equal(1, backgroundWorker.Done.Count); - } - - [Fact] - public async Task TryRemoveFromQueue_ShouldReturn_True() - { - //arrange - const int workCount = 5; - var result = 0; - - Task workAction(string id, IServiceProvider services, Action callback, CancellationToken token) - { - result++; - return Task.Delay(10); - } - - //act - for (int i = 0; i < workCount; i++) - { - var work = Work.CreateByDelegate(i.ToString(), workAction); - backgroundWorker.Enqueue(work); - } - - var removed = backgroundWorker.TryRemoveFromQueue((workCount - 1).ToString()); - - await backgroundWorker.ExecuteTask; - - //assert - Assert.True(removed); - Assert.Equal(workCount - 1, result); - Assert.Equal(workCount - 1, backgroundWorker.Done.Count); - } -} \ No newline at end of file diff --git a/AsbCloudWebApi.Tests/UnitTests/Background/WorkTest.cs b/AsbCloudWebApi.Tests/UnitTests/Background/WorkTest.cs deleted file mode 100644 index 10560fed..00000000 --- a/AsbCloudWebApi.Tests/UnitTests/Background/WorkTest.cs +++ /dev/null @@ -1,152 +0,0 @@ -using System; -using System.Threading; -using System.Threading.Tasks; -using AsbCloudInfrastructure.Background; -using Microsoft.Extensions.DependencyInjection; -using NSubstitute; -using Xunit; - -namespace AsbCloudWebApi.Tests.UnitTests.Background; - -public class WorkTest -{ - private readonly IServiceProvider serviceProviderMock = Substitute.For(); - private readonly IServiceScope serviceScopeMock = Substitute.For(); - private readonly IServiceScopeFactory serviceScopeFactoryMock = Substitute.For(); - - public WorkTest() - { - serviceScopeFactoryMock.CreateScope().Returns(serviceScopeMock); - ((ISupportRequiredService)serviceProviderMock).GetRequiredService(typeof(IServiceScopeFactory)).Returns(serviceScopeFactoryMock); - } - - [Fact] - public async Task Start_ShouldReturn_Success() - { - //arrange - Task workAction(string id, IServiceProvider services, Action callback, CancellationToken token) - => Task.CompletedTask; - - var work = Work.CreateByDelegate("", workAction); - - //act - var begin = DateTime.Now; - await work.Start(serviceProviderMock, CancellationToken.None); - var done = DateTime.Now; - var executionTime = done - begin; - - //assert - Assert.Equal(1, work.CountComplete); - Assert.Equal(1, work.CountStart); - Assert.Equal(0, work.CountErrors); - Assert.Null(work.CurrentState); - Assert.Null(work.LastError); - - var lastState = work.LastComplete; - Assert.NotNull(lastState); - Assert.InRange(lastState.Start, begin, done - 0.5 * executionTime); - Assert.InRange(lastState.End, done - 0.5 * executionTime, done); - Assert.InRange(lastState.ExecutionTime, TimeSpan.Zero, executionTime); - } - - [Fact] - public async Task ExecutionWork_Invokes_Callback() - { - //arrange - const string expectedState = "42"; - const double expectedProgress = 42d; - - var timeout = TimeSpan.FromMilliseconds(40); - - Task workAction(string id, IServiceProvider services, Action callback, CancellationToken token) - { - callback.Invoke(expectedState, expectedProgress); - return Task.Delay(timeout); - } - - var work = Work.CreateByDelegate("", workAction); - - //act - var begin = DateTime.Now; - _ = work.Start(serviceProviderMock, CancellationToken.None); - await Task.Delay(timeout / 3); - - //assert - Assert.Equal(0, work.CountComplete); - Assert.Equal(1, work.CountStart); - Assert.Equal(0, work.CountErrors); - Assert.NotNull(work.CurrentState); - Assert.Null(work.LastComplete); - Assert.Null(work.LastError); - - var currentState = work.CurrentState; - Assert.NotNull(currentState); - Assert.InRange(currentState.Start, begin, begin + timeout); - Assert.InRange(currentState.StateUpdate, begin, begin + timeout); - Assert.Equal(expectedState, currentState.State); - Assert.Equal(expectedProgress, currentState.Progress); - } - - [Fact] - public async Task ExecutionWork_ShouldReturn_FailsWithInfo() - { - //arrange - const string expectedState = "41"; - const string expectedErrorText = "42"; - var minWorkTime = TimeSpan.FromMilliseconds(10); - - async Task workAction(string id, IServiceProvider services, Action callback, CancellationToken token) - { - await Task.Delay(minWorkTime); - callback(expectedState, 0); - throw new Exception(expectedErrorText); - } - - var work = Work.CreateByDelegate("", workAction); - - //act - var begin = DateTime.Now; - await work.Start(serviceProviderMock, CancellationToken.None); - - //assert - Assert.Equal(0, work.CountComplete); - Assert.Equal(1, work.CountStart); - Assert.Equal(1, work.CountErrors); - Assert.Null(work.CurrentState); - Assert.Null(work.LastComplete); - - var error = work.LastError; - Assert.NotNull(error); - Assert.InRange(error.Start, begin, DateTime.Now); - Assert.InRange(error.End, begin, DateTime.Now); - Assert.InRange(error.ExecutionTime, minWorkTime, DateTime.Now - begin); - Assert.Contains(expectedErrorText, error.ErrorText, StringComparison.InvariantCultureIgnoreCase); - Assert.Equal(expectedState, error.State); - } - - [Fact] - public async Task Stop_ShouldReturn_Success() - { - //arrange - var workTime = TimeSpan.FromMilliseconds(1_000); - - Task workAction(string id, IServiceProvider services, Action callback, CancellationToken token) - => Task.Delay(workTime, token); - - var work = Work.CreateByDelegate("", workAction); - - //act - var begin = DateTime.Now; - _ = work.Start(serviceProviderMock, CancellationToken.None); - await Task.Delay(10); - work.Stop(); - await Task.Delay(10); - - //assert - Assert.Equal(0, work.CountComplete); - Assert.Equal(1, work.CountStart); - Assert.Equal(1, work.CountErrors); - Assert.Null(work.LastComplete); - Assert.NotNull(work.LastError); - } -} \ No newline at end of file diff --git a/AsbCloudWebApi.Tests/UnitTests/Services/DailyReportServiceTest.cs b/AsbCloudWebApi.Tests/UnitTests/Services/DailyReportServiceTest.cs deleted file mode 100644 index 54bd3d2f..00000000 --- a/AsbCloudWebApi.Tests/UnitTests/Services/DailyReportServiceTest.cs +++ /dev/null @@ -1,583 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using AsbCloudApp.Data; -using AsbCloudApp.Data.DailyReport; -using AsbCloudApp.Data.DailyReport.Blocks.Sign; -using AsbCloudApp.Data.DailyReport.Blocks.Subsystems; -using AsbCloudApp.Data.DailyReport.Blocks.TimeBalance; -using AsbCloudApp.Data.DetectedOperation; -using AsbCloudApp.Data.ProcessMaps.Report; -using AsbCloudApp.Data.Subsystems; -using AsbCloudApp.Data.Trajectory; -using AsbCloudApp.Exceptions; -using AsbCloudApp.Repositories; -using AsbCloudApp.Requests; -using AsbCloudApp.Services; -using AsbCloudApp.Services.ProcessMaps.WellDrilling; -using AsbCloudInfrastructure.Services.DailyReport; -using NSubstitute; -using Xunit; - -namespace AsbCloudWebApi.Tests.UnitTests.Services; - -public class DailyReportServiceTest -{ - private const int idDailyReport = 1; - private const int idUser = 3; - private const int idWell = 2; - - private readonly SubsystemBlockDto fakeSubsystemBlock = new() - { - IdUser = idUser, - Wellbore = 999, - MeasurementsPerDay = 999, - TotalRopPlan = 999, - Comment = "Увеличить обороты", - Subsystems = new[] - { - new SubsystemRecordDto - { - Name = "АвтоСПО", - UsagePerDay = new SubsystemParametersDto - { - UsedTimeHours = 24, - SumDepthInterval = 1500, - KUsage = 15 - }, - UsagePerWell = new SubsystemParametersDto - { - UsedTimeHours = 500, - SumDepthInterval = 3000, - KUsage = 100 - } - } - } - }; - - private readonly SignBlockDto fakeSignBlock = new() - { - IdUser = idUser, - DrillingMaster = new SignRecordDto - { - Name = "Иван", - Patronymic = "Иванович", - Surname = "Иванов" - }, - Supervisor = new SignRecordDto() - { - Name = "Илья", - Patronymic = "Ильич", - Surname = "Бурилов" - } - }; - - private readonly TimeBalanceBlockDto fakeTimeBalanceBlock = new() - { - IdUser = idUser, - IdSection = 1, - WellDepth = new PlanFactDto - { - Plan = 2000 - }, - WellOperations = new[] - { - new TimeBalanceRecordDto - { - IdWellOperation = 1, - DurationHours = new PlanFactDto - { - Fact = 100, - Plan = 150, - }, - DrillingDeviationPerSection = 90, - DrillingDeviationPerDay = 100, - ReasonDeviation = "Отклонение" - } - } - }; - - private readonly DetectedOperationListDto fakeWellOperationSlipsTime = new() - { - Stats = new[] - { - new DetectedOperationDrillersStatDto - { - Count = 40 - } - } - }; - - private readonly ProcessMapReportWellDrillingDto fakeProcessMapReportWellDrilling = new() - { - DrillingMode = "Ротор", - DateStart = new DateTime(2023, 10, 26), - DeltaDepth = 500, - Rop = new PlanFactDto - { - Plan = 300, - Fact = 500 - }, - MechDrillingHours = 100 - }; - - private readonly WellSectionTypeDto fakeSectionType = new() - { - Id = 1, - Caption = "Пилотный ствол", - }; - - private readonly TrajectoryGeoFactDto fakeLastFactTrajectory = new() - { - WellboreDepth = 100, - VerticalDepth = 150, - ZenithAngle = 3, - AzimuthGeo = 5 - }; - - private readonly CompanyDto fakeCustomer = new() - { - Caption = "Тестовый заказчик", - IdCompanyType = 1 - }; - - private readonly CompanyDto fakeContractor = new() - { - Caption = "Тестовый подрядчик", - IdCompanyType = 2 - }; - - private readonly WellOperationDto fakeFirstFactWellOperation = new() - { - IdWell = idWell, - IdParentCategory = 4001, - IdWellSectionType = 1, - CategoryName = "Механическое. бурение", - DateStart = new DateTime(2023, 10, 26), - DepthStart = 80, - DepthEnd = 150, - DurationHours = 8, - }; - - private readonly WellOperationDto fakeLastFactWellOperation = new() - { - IdWell = idWell, - CategoryName = "Механическое. бурение", - IdWellSectionType = 1, - IdParentCategory = 4001, - DateStart = new DateTime(2023, 10, 26), - DepthStart = 150, - DepthEnd = 200, - DurationHours = 8, - }; - - private readonly ScheduleDto fakeShedule = new() - { - IdWell = idWell, - ShiftStart = new TimeDto(1), - ShiftEnd = new TimeDto(5), - DrillStart = new DateTime(2023, 01, 26), - DrillEnd = new DateTime(2023, 12, 26), - Driller = new() - { - Name = "Иван", - Surname = "Иванов", - Patronymic = "Бурила" - } - }; - - private readonly SubsystemStatDto fakeSubsystemsStat = new() - { - SubsystemName = "АПД", - SumDepthInterval = 250, - UsedTimeHours = 200, - KUsage = 30 - }; - - private readonly SimpleTimezoneDto fakeWellTimezone = new() - { - Hours = 5, - }; - - private readonly IWellService wellServiceMock = Substitute.For(); - private readonly ITrajectoryNnbRepository trajectoryFactNnbRepositoryMock = Substitute.For(); - private readonly IDailyReportRepository dailyReportRepositoryMock = Substitute.For(); - private readonly IScheduleRepository scheduleRepositoryMock = Substitute.For(); - private readonly IWellOperationRepository wellOperationRepositoryMock = Substitute.For(); - private readonly ISubsystemService subsystemServiceMock = Substitute.For(); - private readonly IProcessMapReportWellDrillingService processMapReportWellDrillingServiceMock = Substitute.For(); - private readonly IDetectedOperationService detectedOperationServiceMock = Substitute.For(); - - private readonly DailyReportService dailyReportService; - - private readonly DailyReportDto fakeDailyReport; - private readonly WellDto fakeWell; - private readonly DatesRangeDto fakeDatesRange; - - public DailyReportServiceTest() - { - fakeDailyReport = new DailyReportDto - { - Id = idDailyReport, - IdWell = idWell, - Date = new(2023, 10, 26), - DateLastUpdate = null - }; - - fakeWell = new WellDto - { - Id = idWell, - Caption = "Тестовое название", - WellType = "Горизонтальная", - Cluster = "Тестовый куст", - Deposit = "Тестовое месторождение", - Companies = new[] { fakeCustomer, fakeContractor } - }; - - fakeDatesRange = new DatesRangeDto - { - From = fakeFirstFactWellOperation.DateStart.DateTime, - To = fakeLastFactWellOperation.DateStart.DateTime - }; - - dailyReportService = new DailyReportService(wellServiceMock, - trajectoryFactNnbRepositoryMock, - dailyReportRepositoryMock, - scheduleRepositoryMock, - wellOperationRepositoryMock, - subsystemServiceMock, - processMapReportWellDrillingServiceMock, - detectedOperationServiceMock); - - dailyReportRepositoryMock.InsertAsync(Arg.Any(), Arg.Any()) - .ReturnsForAnyArgs(idDailyReport); - - dailyReportRepositoryMock.GetOrDefaultAsync(Arg.Any(), Arg.Any(), Arg.Any()) - .ReturnsForAnyArgs(fakeDailyReport); - - dailyReportRepositoryMock.UpdateAsync(Arg.Any(), Arg.Any()) - .ReturnsForAnyArgs(idDailyReport); - - wellServiceMock.GetOrDefaultAsync(Arg.Any(), Arg.Any()) - .ReturnsForAnyArgs(fakeWell); - - trajectoryFactNnbRepositoryMock.GetByRequestAsync(Arg.Any(), Arg.Any()) - .ReturnsForAnyArgs(new[] { fakeLastFactTrajectory }); - - wellOperationRepositoryMock.GetAsync(Arg.Any(), Arg.Any()) - .ReturnsForAnyArgs(new[] { fakeFirstFactWellOperation, fakeLastFactWellOperation }); - - wellOperationRepositoryMock.GetDatesRangeAsync(Arg.Any(), Arg.Any(), Arg.Any()) - .ReturnsForAnyArgs(fakeDatesRange); - - wellOperationRepositoryMock.GetSectionTypes() - .ReturnsForAnyArgs(new[] { fakeSectionType }); - - detectedOperationServiceMock.GetAsync(Arg.Any(), Arg.Any()) - .ReturnsForAnyArgs(fakeWellOperationSlipsTime); - - subsystemServiceMock.GetStatAsync(Arg.Any(), Arg.Any()) - .ReturnsForAnyArgs(new[] { fakeSubsystemsStat }); - - scheduleRepositoryMock.GetAsync(Arg.Any(), Arg.Any(), Arg.Any()) - .ReturnsForAnyArgs(new[] { fakeShedule }); - - processMapReportWellDrillingServiceMock.GetAsync(Arg.Any(), Arg.Any()) - .ReturnsForAnyArgs(new[] { fakeProcessMapReportWellDrilling }); - - wellServiceMock.GetTimezone(Arg.Any()) - .ReturnsForAnyArgs(fakeWellTimezone); - } - - [Fact] - public async Task UpdateOrInsertAsync_ShouldReturn_UpdatedSubsystemBlock() - { - //act - var result = await dailyReportService.UpdateOrInsertAsync(idWell, fakeDailyReport.Date, idUser, fakeSubsystemBlock, CancellationToken.None); - - //assert - Assert.NotNull(fakeSubsystemBlock.LastUpdateDate); - Assert.NotNull(fakeDailyReport.DateLastUpdate); - Assert.Equal(fakeSubsystemBlock.IdUser, idUser); - Assert.Equal(fakeDailyReport.SubsystemBlock, fakeSubsystemBlock); - Assert.Equal(idDailyReport, result); - } - - [Theory] - [MemberData(nameof(DateDailyReport))] - public async Task UpdateOrInsertAsync_ShouldReturn_UnableToUpdateDailyReport(DateOnly dateDailyReport) - { - //act - var result = await Assert.ThrowsAsync(() => dailyReportService.UpdateOrInsertAsync( - idWell, - dateDailyReport, - idUser, - fakeSignBlock, - CancellationToken.None)); - - //assert - Assert.Contains("Невозможно обновить суточный отчёт", result.Message); - } - - [Fact] - public async Task UpdateOrInsertAsync_ShouldReturn_UpdatedSignBlock() - { - //act - var result = await dailyReportService.UpdateOrInsertAsync(idWell, fakeDailyReport.Date, idUser, fakeSignBlock, CancellationToken.None); - - //assert - Assert.NotNull(fakeSignBlock.LastUpdateDate); - Assert.NotNull(fakeDailyReport.DateLastUpdate); - Assert.Equal(fakeSignBlock.IdUser, idUser); - Assert.Equal(fakeDailyReport.SignBlock, fakeSignBlock); - Assert.Equal(idDailyReport, result); - } - - [Fact] - public async Task UpdateOrInsertAsync_ShouldReturn_UpdatedTimeBalanceBlock() - { - //act - var result = await dailyReportService.UpdateOrInsertAsync(idWell, fakeDailyReport.Date, idUser, fakeTimeBalanceBlock, - CancellationToken.None); - - //assert - Assert.NotNull(fakeTimeBalanceBlock.LastUpdateDate); - Assert.NotNull(fakeDailyReport.DateLastUpdate); - Assert.Equal(fakeTimeBalanceBlock.IdUser, idUser); - Assert.Equal(fakeDailyReport.TimeBalanceBlock, fakeTimeBalanceBlock); - Assert.Equal(idDailyReport, result); - } - - [Theory] - [MemberData(nameof(DateDailyReport))] - public async Task GetAsync_ShouldReturn_UnableToGetDailyReport(DateOnly dateDailyReport) - { - //act - var result = await Assert.ThrowsAsync(() => dailyReportService.GetAsync(idWell, - dateDailyReport, - CancellationToken.None)); - - //assert - Assert.Contains("Невозможно получить суточный отчёт", result.Message); - } - - [Fact] - public async Task GetAsync_ShouldReturn_AddedWellInfo() - { - //act - var result = await dailyReportService.GetAsync(idWell, fakeDailyReport.Date, CancellationToken.None); - - //assert - Assert.Equal(result.IdWell, fakeWell.Id); - Assert.Equal(result.WellCaption, fakeWell.Caption); - Assert.Equal(result.WellType, fakeWell.WellType); - Assert.Equal(result.Cluster, fakeWell.Cluster); - Assert.Equal(result.Deposit, fakeWell.Deposit); - Assert.Equal(result.Customer, fakeCustomer.Caption); - Assert.Equal(result.Contractor, fakeContractor.Caption); - Assert.Equal(result.DepthStart, fakeFirstFactWellOperation.DepthStart); - Assert.Equal(result.DepthEnd, fakeLastFactWellOperation.DepthEnd); - } - - [Fact] - public async Task GetAsync_ShouldReturn_AddedTrajectoryBlock() - { - //act - var result = await dailyReportService.GetAsync(idWell, fakeDailyReport.Date, CancellationToken.None); - - //assert - Assert.Equal(fakeLastFactTrajectory.WellboreDepth, result.TrajectoryBlock.WellboreDepth); - Assert.Equal(fakeLastFactTrajectory.VerticalDepth, result.TrajectoryBlock.VerticalDepth); - Assert.Equal(fakeLastFactTrajectory.ZenithAngle, result.TrajectoryBlock.ZenithAngle); - Assert.Equal(fakeLastFactTrajectory.AzimuthGeo, result.TrajectoryBlock.AzimuthGeo); - } - - [Fact] - public async Task GetAsync_ShouldReturn_AddedFactWellOperationBlock() - { - //act - var result = await dailyReportService.GetAsync(idWell, fakeDailyReport.Date, CancellationToken.None); - - //assert - Assert.Equal(16, result.FactWellOperationBlock.SectionDrillingHours); - Assert.Single(result.FactWellOperationBlock.WellOperations); - - var wellOperation = result.FactWellOperationBlock.WellOperations.Single(); - - Assert.Equal("Механическое. бурение", wellOperation.CategoryName); - Assert.Equal(16, wellOperation.DurationHours); - } - - [Fact] - public async Task GetAsync_ShouldReturn_AddedScheduleBlock() - { - //act - var result = await dailyReportService.GetAsync(idWell, fakeDailyReport.Date, CancellationToken.None); - - //assert - Assert.Single(result.ScheduleBlock); - - var sheduleRecord = result.ScheduleBlock.Single(); - - Assert.Equal(fakeShedule.ShiftStart, sheduleRecord.ShiftStart); - Assert.Equal(fakeShedule.ShiftEnd, sheduleRecord.ShiftEnd); - Assert.Equal(fakeShedule.Driller?.Name, sheduleRecord.Name); - Assert.Equal(fakeShedule.Driller?.Surname, sheduleRecord.Surname); - Assert.Equal(fakeShedule.Driller?.Patronymic, sheduleRecord.Patronymic); - } - - [Fact] - public async Task GetAsync_ShouldReturn_UpdatedTimeBalanceBlock() - { - //arrange - fakeDailyReport.TimeBalanceBlock = fakeTimeBalanceBlock; - - //act - var result = await dailyReportService.GetAsync(idWell, fakeDailyReport.Date, CancellationToken.None); - - //assert - Assert.NotNull(result.TimeBalanceBlock); - Assert.Equal(fakeSectionType.Id, result.TimeBalanceBlock.IdSection); - Assert.Equal(fakeSectionType.Caption, result.TimeBalanceBlock.SectionName); - Assert.Equal(2000, result.TimeBalanceBlock?.WellDepth.Plan); - Assert.Equal(120, result.TimeBalanceBlock?.WellDepth.Fact); - Assert.Equal(40, result.TimeBalanceBlock?.WellOperationSlipsTimeCount); - } - - [Fact] - public async Task GetAsync_ShouldReturn_AddedProcessMapWellDrillingBlock() - { - //act - var result = await dailyReportService.GetAsync(idWell, fakeDailyReport.Date, CancellationToken.None); - - //assert - Assert.Single(result.ProcessMapWellDrillingBlock); - - var processMapWellDrillingRecord = result.ProcessMapWellDrillingBlock.Single(); - - Assert.Equal(fakeProcessMapReportWellDrilling.DrillingMode, processMapWellDrillingRecord.DrillingMode); - Assert.Equal(fakeProcessMapReportWellDrilling.Rop.Plan, processMapWellDrillingRecord.Rop.Plan); - Assert.Equal(fakeProcessMapReportWellDrilling.Rop.Fact, processMapWellDrillingRecord.Rop.Fact); - Assert.Equal(fakeProcessMapReportWellDrilling.DeltaDepth, processMapWellDrillingRecord.WellBoreDepth); - Assert.Equal(fakeProcessMapReportWellDrilling.MechDrillingHours, processMapWellDrillingRecord.MechDrillingHours); - } - - [Fact] - public async Task GetAsync_ShouldReturn_UpdatedSubsystemBlock() - { - //arrange - fakeDailyReport.SubsystemBlock = fakeSubsystemBlock; - - //act - var result = await dailyReportService.GetAsync(idDailyReport, fakeDailyReport.Date, CancellationToken.None); - - //assert - Assert.NotNull(result.SubsystemBlock); - Assert.Equal(2, result.SubsystemBlock?.Subsystems.Count()); - - var subsystemRecord0 = result.SubsystemBlock?.Subsystems.ElementAt(0); - - Assert.Equal("АвтоСПО", subsystemRecord0?.Name); - Assert.Equal(24, subsystemRecord0?.UsagePerDay?.UsedTimeHours); - Assert.Equal(1500, subsystemRecord0?.UsagePerDay?.SumDepthInterval); - Assert.Equal(15, subsystemRecord0?.UsagePerDay?.KUsage); - - Assert.Equal(500, subsystemRecord0?.UsagePerWell?.UsedTimeHours); - Assert.Equal(3000, subsystemRecord0?.UsagePerWell?.SumDepthInterval); - Assert.Equal(100, subsystemRecord0?.UsagePerWell?.KUsage); - - var subsystemRecord1 = result.SubsystemBlock?.Subsystems.ElementAt(1); - - Assert.Equal("АПД", subsystemRecord1?.Name); - Assert.Equal(200, subsystemRecord1?.UsagePerDay?.UsedTimeHours); - Assert.Equal(250, subsystemRecord1?.UsagePerDay?.SumDepthInterval); - Assert.Equal(30, subsystemRecord1?.UsagePerDay?.KUsage); - - Assert.Equal(200, subsystemRecord1?.UsagePerWell?.UsedTimeHours); - Assert.Equal(250, subsystemRecord1?.UsagePerWell?.SumDepthInterval); - Assert.Equal(30, subsystemRecord1?.UsagePerWell?.KUsage); - } - - [Fact] - public async Task GetAsync_ShouldReturn_FictiveDailyReport() - { - //arrange - var expectedCount = (fakeLastFactWellOperation.DateStart - fakeFirstFactWellOperation.DateStart).TotalDays + 1; - - //act - var result = await dailyReportService.GetAsync(idWell, new FileReportRequest(), CancellationToken.None); - - //assert - Assert.Equal(expectedCount, result.Count); - } - - [Theory] - [MemberData(nameof(FactWellOperationDatesRange))] - public async Task GetDatesRangeAsync_ShouldReturn_DateRangeByFactWellOperations(DatesRangeDto datesRange) - { - //arrange - wellOperationRepositoryMock.GetDatesRangeAsync(Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(datesRange); - - //act - var result = await dailyReportService.GetDatesRangeAsync(idWell, CancellationToken.None); - - //assert - Assert.NotNull(result); - Assert.True(result.From <= result.To); - Assert.True(result.To < DateTime.UtcNow.Date); - } - - public static IEnumerable DateDailyReport() - { - yield return new object[] - { - new DateOnly(2090, 01, 01), - }; - yield return new object[] - { - new DateOnly(2000, 01, 01) - }; - } - - public static IEnumerable FactWellOperationDatesRange() - { - yield return new object[] - { - new DatesRangeDto - { - From = new DateTime(2023, 11, 1), - To = new DateTime(2023, 11, 9) - } - }; - - yield return new object[] - { - new DatesRangeDto - { - From = new DateTime(2023, 11, 1), - To = new DateTime(2023, 11, 1) - } - }; - - yield return new object[] - { - new DatesRangeDto - { - From = DateTime.UtcNow, - To = DateTime.UtcNow - } - }; - - yield return new object[] - { - new DatesRangeDto - { - From = new DateTime(2023, 11, 1), - To = new DateTime(2023, 11, 11) - } - }; - } -} \ No newline at end of file diff --git a/AsbCloudWebApi.Tests/UnitTests/Services/FileServiceTest.cs b/AsbCloudWebApi.Tests/UnitTests/Services/FileServiceTest.cs deleted file mode 100644 index f5c99ffd..00000000 --- a/AsbCloudWebApi.Tests/UnitTests/Services/FileServiceTest.cs +++ /dev/null @@ -1,172 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Threading; -using System.Threading.Tasks; -using AsbCloudApp.Data; -using AsbCloudApp.Data.User; -using AsbCloudApp.Repositories; -using AsbCloudApp.Requests; -using AsbCloudApp.Services; -using NSubstitute; -using Xunit; - -namespace AsbCloudWebApi.Tests.UnitTests.Services; - -public class FileServiceTest -{ - private const int idMark = 132; - private const int idWell = 190; - private const int idCategory = 10_000; - private const int idFile = 1742; - private const int idAuthor = 1; - private const string fileName = "test.txt"; - - private static readonly MemoryStream fileStream = new(Array.Empty()); - - private static UserDto author = new() - { - Id = 1, - IdCompany = 1 - }; - - private static FileInfoDto fileInfo = new() - { - Id = idFile, - IdAuthor = idAuthor, - Author = author, - IdWell = idWell, - IdCategory = idCategory, - Name = fileName, - Size = 0, - UploadDate = DateTime.Now - }; - - private static FileMarkDto fileMark = new() - { - Id = idMark, - IdFile = idFile, - User = author, - Comment = "qqq", - IdMarkType = 1, - DateCreated = DateTime.Now, - IsDeleted = false - }; - - private readonly IFileRepository fileRepositoryMock = Substitute.For(); - private readonly IFileStorageRepository storageRepositoryMock = Substitute.For(); - - private readonly FileService fileService; - - public FileServiceTest() - { - fileRepositoryMock.GetByMarkId(Arg.Any(), Arg.Any()) - .ReturnsForAnyArgs(fileInfo); - - fileRepositoryMock.GetInfoByIdsAsync(Arg.Any>(), Arg.Any()) - .ReturnsForAnyArgs(new[] { fileInfo }); - - fileRepositoryMock.DeleteAsync(Arg.Any>(), Arg.Any()) - .ReturnsForAnyArgs(new[] { fileInfo }); - - fileRepositoryMock.MarkFileMarkAsDeletedAsync(Arg.Any>(), Arg.Any()) - .ReturnsForAnyArgs(fileMark.Id); - - fileRepositoryMock.MarkAsDeletedAsync(Arg.Any(), Arg.Any()) - .ReturnsForAnyArgs(fileMark.Id); - - fileRepositoryMock.GetInfosAsync(Arg.Any(), Arg.Any()) - .ReturnsForAnyArgs(new[] { fileInfo }); - - fileRepositoryMock.CreateFileMarkAsync(Arg.Any(), Arg.Any(), Arg.Any()) - .ReturnsForAnyArgs(fileMark.Id); - - fileRepositoryMock.GetOrDefaultAsync(Arg.Any(), Arg.Any()) - .ReturnsForAnyArgs(fileInfo); - - storageRepositoryMock.GetFilePath(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) - .ReturnsForAnyArgs(Path.Combine("files", idWell.ToString(), idCategory.ToString(), fileName)); - - fileService = new FileService(fileRepositoryMock, storageRepositoryMock); - } - - [Fact] - public async Task GetByMarkId_ShouldReturn_FileInfo() - { - //act - var data = await fileService.GetByMarkId(idMark, CancellationToken.None); - - //assert - Assert.NotNull(data); - } - - [Fact] - public async Task GetOrDefaultAsync_ShouldReturn_FileInfo() - { - //act - var data = await fileService.GetOrDefaultAsync(idFile, CancellationToken.None); - - //assert - Assert.NotNull(data); - } - - [Fact] - public async Task GetInfoByIdsAsync_ShouldReturn_FileInfo() - { - //act - var data = await fileService.GetInfoByIdsAsync(new[] { idFile }, CancellationToken.None); - - //assert - Assert.NotNull(data); - } - - [Fact] - public async Task SaveAsync_ShouldReturn_FileInfo() - { - //act - var data = await fileService.SaveAsync(idWell, idAuthor, idCategory, fileName, fileStream, CancellationToken.None); - - //assert - Assert.NotNull(data); - } - - [Fact] - public async Task DeleteAsync_ShouldReturn_DeletedRecordCount() - { - //act - var result = await fileService.DeleteAsync(new[] { idFile }, CancellationToken.None); - - //assert - Assert.True(result > 0); - } - - [Fact] - public async Task MarkFileMarkAsDeletedAsync_ShouldReturn_SavedRecordCount() - { - //act - var result = await fileService.MarkFileMarkAsDeletedAsync(new[] { idMark }, CancellationToken.None); - - //assert - Assert.True(result > 0); - } - - [Fact] - public async Task MarkAsDeletedAsync_ShouldReturn_DeletedRecordCount() - { - //act - var result = await fileService.MarkAsDeletedAsync(idFile, CancellationToken.None); - - //assert - Assert.True(result > 0); - } - - [Fact] - public async Task CreateFileMarkAsync_ShouldReturn_SavedRecordCount() - { - //act - var result = await fileService.CreateFileMarkAsync(fileMark, idAuthor, CancellationToken.None); - - //assert - Assert.True(result > 0); - } -} \ No newline at end of file diff --git a/AsbCloudWebApi.Tests/UnitTests/Services/HelpPageServiceTest.cs b/AsbCloudWebApi.Tests/UnitTests/Services/HelpPageServiceTest.cs deleted file mode 100644 index 1277a83e..00000000 --- a/AsbCloudWebApi.Tests/UnitTests/Services/HelpPageServiceTest.cs +++ /dev/null @@ -1,97 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Threading; -using System.Threading.Tasks; -using AsbCloudApp.Data; -using AsbCloudApp.Repositories; -using AsbCloudInfrastructure.Services; -using Microsoft.Extensions.Configuration; -using NSubstitute; -using Xunit; - -namespace AsbCloudWebApi.Tests.UnitTests.Services; - -public class HelpPageServiceTest -{ - private const string urlPage = "test"; - private const string fileName = "Справка_для_страницы_test.pdf"; - private const int idCategory = 20000; - - private static Dictionary configSettings = new() - { - { "DirectoryNameHelpPageFiles", "helpPages" } - }; - - private static readonly MemoryStream fileStream = new(Array.Empty()); - - private static readonly HelpPageDto existingHelpPage = new() - { - Id = 178, - IdCategory = idCategory, - UrlPage = "test2", - Name = "Справка_для_страницы_test2.pdf" - }; - - private readonly IHelpPageRepository helpPageRepositoryMock = Substitute.For(); - private readonly IFileStorageRepository fileStorageRepositoryMock = Substitute.For(); - - private readonly HelpPageService helpPageService; - - public HelpPageServiceTest() - { - IConfiguration configuration = new ConfigurationBuilder() - .AddInMemoryCollection(configSettings) - .Build(); - - helpPageRepositoryMock.GetOrDefaultByUrlPageAndIdCategoryAsync(existingHelpPage.UrlPage, existingHelpPage.IdCategory, Arg.Any()) - .Returns(existingHelpPage); - - helpPageRepositoryMock.InsertAsync(Arg.Any(), Arg.Any()) - .ReturnsForAnyArgs(1); - - fileStorageRepositoryMock.SaveFileAsync(Arg.Any(), Arg.Any(), Arg.Any()); - - helpPageService = new HelpPageService(helpPageRepositoryMock, - fileStorageRepositoryMock, - configuration); - } - - [Fact] - public async Task AddOrUpdateAsync_ShouldReturn_AddedHelpPage() - { - //act - var result = await helpPageService.AddOrUpdateAsync(urlPage, - idCategory, - fileName, - fileStream, - CancellationToken.None); - - //assert - await helpPageRepositoryMock.Received().InsertAsync(Arg.Any(), Arg.Any()); - await fileStorageRepositoryMock.Received().SaveFileAsync(Arg.Any(), Arg.Any(), Arg.Any()); - - Assert.NotEqual(existingHelpPage.Id, result); - Assert.NotEqual(urlPage, existingHelpPage.UrlPage); - Assert.NotEqual(fileName, existingHelpPage.Name); - Assert.Equal(idCategory, existingHelpPage.IdCategory); - } - - - [Fact] - public async Task UpdateAsync_ShouldReturn_UpdatedHelpPage() - { - //act - var result = await helpPageService.AddOrUpdateAsync(existingHelpPage.UrlPage, - existingHelpPage.IdCategory, - existingHelpPage.Name, - fileStream, - CancellationToken.None); - - //assert - await helpPageRepositoryMock.Received().UpdateAsync(Arg.Any(), Arg.Any()); - await fileStorageRepositoryMock.Received().SaveFileAsync(Arg.Any(), Arg.Any(), Arg.Any()); - - Assert.Equal(existingHelpPage.Id, result); - } -} \ No newline at end of file diff --git a/AsbCloudWebApi.Tests/UnitTests/Services/ProcessMaps/ProcessMapPlanServiceTests.cs b/AsbCloudWebApi.Tests/UnitTests/Services/ProcessMaps/ProcessMapPlanServiceTests.cs deleted file mode 100644 index 17d96d81..00000000 --- a/AsbCloudWebApi.Tests/UnitTests/Services/ProcessMaps/ProcessMapPlanServiceTests.cs +++ /dev/null @@ -1,94 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using AsbCloudApp.Data; -using AsbCloudApp.Data.ProcessMaps; -using AsbCloudApp.Repositories; -using AsbCloudApp.Services; -using AsbCloudInfrastructure.Services.ProcessMaps; -using NSubstitute; -using Xunit; - -namespace AsbCloudWebApi.Tests.UnitTests.Services.ProcessMaps; - -public class ProcessMapPlanServiceTests -{ - private const int idWellSectionPlan = 1; - private const int idWell = 3; - private const int idWellSectionType = 54; - - private readonly IEnumerable fakeCollectionWellSectionPlan = new WellSectionPlanDto[] - { - new() - { - Id = idWellSectionPlan, - IdWell = idWell, - IdSectionType = idWellSectionType, - DepthStart = 80, - DepthEnd = 150 - } - }; - - private readonly IEnumerable fakeCollectionWellSectionTypes = new WellSectionTypeDto[] - { - new() - { - Id = idWellSectionType, - Caption = "Направление 1", - Order = 1 - } - }; - - private readonly ICrudRepository wellSectionTypeRepositoryMock = - Substitute.For>(); - - private readonly IProcessMapPlanRepository processMapPlanRepositoryMock = - Substitute.For>(); - - private readonly IRepositoryWellRelated wellSectionPlanRepositoryMock = - Substitute.For>(); - - private readonly ProcessMapPlanService processMapPlanService; - - public ProcessMapPlanServiceTests() - { - processMapPlanService = new ProcessMapPlanService(wellSectionTypeRepositoryMock, - processMapPlanRepositoryMock, wellSectionPlanRepositoryMock); - - wellSectionPlanRepositoryMock.GetByIdWellAsync(Arg.Any(), Arg.Any()) - .ReturnsForAnyArgs(fakeCollectionWellSectionPlan); - - wellSectionTypeRepositoryMock.GetAllAsync(Arg.Any()) - .ReturnsForAnyArgs(fakeCollectionWellSectionTypes); - } - - [Theory] - [InlineData(80, 150, true)] - [InlineData(90, 140, true)] - [InlineData(0, 110, false)] - [InlineData(110, 200, false)] - public async Task GetAsync_ReturnsValidatedCollectionProcessMapPlanWellDrilling(int depthStart, int depthEnd, bool isValidCollection) - { - //arrange - var fakeCollectionProcessMapPlanWellDrilling = new ProcessMapPlanWellDrillingDto[] - { - new() - { - IdWellSectionType = idWellSectionType, - DepthStart = depthStart, - DepthEnd = depthEnd - } - }; - - processMapPlanRepositoryMock.GetByIdWellAsync(Arg.Any(), Arg.Any()) - .ReturnsForAnyArgs(fakeCollectionProcessMapPlanWellDrilling); - - //act - var result = (await processMapPlanService.GetAsync(idWell, CancellationToken.None)).ToArray(); - - //assert - Assert.Equal(isValidCollection, result.All(r => r.IsValid)); - Assert.Single(result); - } -} \ No newline at end of file diff --git a/AsbCloudWebApi.Tests/UnitTests/Services/SAUB/TelemetryDataSaubCacheTests.cs b/AsbCloudWebApi.Tests/UnitTests/Services/SAUB/TelemetryDataSaubCacheTests.cs deleted file mode 100644 index fd80fd34..00000000 --- a/AsbCloudWebApi.Tests/UnitTests/Services/SAUB/TelemetryDataSaubCacheTests.cs +++ /dev/null @@ -1,65 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using AsbCloudApp.Data.SAUB; -using AsbCloudDb.Model; -using AsbCloudInfrastructure.Background; -using AsbCloudInfrastructure.Services.SAUB; -using Microsoft.Extensions.DependencyInjection; -using NSubstitute; -using Xunit; - -namespace AsbCloudWebApi.Tests.UnitTests.Services.SAUB; - -public class TelemetryDataSaubCacheTests -{ - private const int idTelemetry = 1; - - private readonly IEnumerable fakeTelemetries = new[] - { - new TelemetryDataSaubDto() - }; - - private readonly IServiceProvider serviceProviderMock = Substitute.For(); - - private readonly TelemetryDataCache telemetryDataCache; - private readonly Type telemetryDataCacheType; - - public TelemetryDataSaubCacheTests() - { - serviceProviderMock.GetService().Returns(new BackgroundWorker(serviceProviderMock)); - - telemetryDataCache = TelemetryDataCache.GetInstance(serviceProviderMock); - - telemetryDataCacheType = telemetryDataCache.GetType(); - } - - [Fact] - public void AddRange_ShouldReturn_AddedElementToCache() - { - //arrange - telemetryDataCacheType.GetField("isLoading", BindingFlags.NonPublic | BindingFlags.Instance)?.SetValue(telemetryDataCache, false); - - //act - telemetryDataCache.AddRange(idTelemetry, fakeTelemetries); - var lastTelemetry = telemetryDataCache.GetLastOrDefault(idTelemetry); - - //assert - Assert.Equal(lastTelemetry, fakeTelemetries.Last()); - } - - [Fact] - public void AddRange_ShouldReturn_NotAddedToCache() - { - //arrange - telemetryDataCacheType.GetField("isLoading", BindingFlags.NonPublic | BindingFlags.Instance)?.SetValue(telemetryDataCache, true); - - //act - telemetryDataCache.AddRange(idTelemetry, fakeTelemetries); - var lastTelemetry = telemetryDataCache.GetLastOrDefault(idTelemetry); - - //assert - Assert.Equal(lastTelemetry, fakeTelemetries.Last()); - } -} \ No newline at end of file diff --git a/AsbCloudWebApi.Tests/UnitTests/Services/TrajectoryVisualizationServiceTest.cs b/AsbCloudWebApi.Tests/UnitTests/Services/TrajectoryVisualizationServiceTest.cs deleted file mode 100644 index b029f983..00000000 --- a/AsbCloudWebApi.Tests/UnitTests/Services/TrajectoryVisualizationServiceTest.cs +++ /dev/null @@ -1,196 +0,0 @@ -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using AsbCloudApp.Data; -using AsbCloudApp.Data.Trajectory; -using AsbCloudApp.Repositories; -using AsbCloudApp.Requests; -using AsbCloudInfrastructure.Services.Trajectory; -using NSubstitute; -using Xunit; - -namespace AsbCloudWebApi.Tests.UnitTests.Services; - -public class TrajectoryVisualizationServiceTest -{ - private readonly ITrajectoryEditableRepository trajectoryPlanRepositoryMock = Substitute.For>(); - private readonly ITrajectoryEditableRepository trajectoryFactRepositoryMock = Substitute.For>(); - private readonly ITrajectoryNnbRepository trajectoryNnbRepositoryMock = Substitute.For(); - - private readonly TrajectoryService trajectoryService; - - public TrajectoryVisualizationServiceTest() - { - trajectoryService = new TrajectoryService(trajectoryPlanRepositoryMock, trajectoryFactRepositoryMock, trajectoryNnbRepositoryMock); - } - - [Fact] - public async Task GetTrajectoryAsync_ShouldReturn_SameCounts() - { - //arrange - var plannedTrajectory = new TrajectoryGeoPlanDto[] - { - new() { WellboreDepth = 0d, ZenithAngle = 0d, AzimuthGeo = 0d }, - new() { WellboreDepth = 0d, ZenithAngle = 0d, AzimuthGeo = 10d }, - new() { WellboreDepth = 0d, ZenithAngle = 30d, AzimuthGeo = 20d }, - new() { WellboreDepth = 30d, ZenithAngle = 0d, AzimuthGeo = 30d }, - new() { WellboreDepth = 30d, ZenithAngle = 90d, AzimuthGeo = 40d }, - new() { WellboreDepth = 0d, ZenithAngle = 0d, AzimuthGeo = 50d }, - }; - - var actualTrajectory = new TrajectoryGeoFactDto[] - { - new() { WellboreDepth = 0, ZenithAngle = 0, AzimuthGeo = 0 }, - new() { WellboreDepth = 30, ZenithAngle = 30, AzimuthGeo = 10 }, - new() { WellboreDepth = 0, ZenithAngle = 0, AzimuthGeo = 20 }, - }; - - var nnbTrajectory = new TrajectoryGeoFactDto[] - { - new() { WellboreDepth = 0, ZenithAngle = 0, AzimuthGeo = 0 }, - new() { WellboreDepth = 30, ZenithAngle = 30, AzimuthGeo = 10 }, - new() { WellboreDepth = 0, ZenithAngle = 0, AzimuthGeo = 20 }, - new() { WellboreDepth = 0, ZenithAngle = 10, AzimuthGeo = 20 }, - }; - - trajectoryPlanRepositoryMock.GetAsync(Arg.Any(), Arg.Any()) - .ReturnsForAnyArgs(plannedTrajectory); - - trajectoryFactRepositoryMock.GetAsync(Arg.Any(), Arg.Any()) - .ReturnsForAnyArgs(actualTrajectory); - - trajectoryNnbRepositoryMock.GetAsync(Arg.Any(), Arg.Any()) - .ReturnsForAnyArgs(nnbTrajectory); - - //act - var result = await trajectoryService.GetTrajectoryCartesianAsync(1, CancellationToken.None); - - //assert - Assert.Equal(plannedTrajectory.Count(), result.Plan?.Count()); - Assert.Equal(actualTrajectory.Count(), result.FactManual?.Count()); - Assert.Equal(nnbTrajectory.Count(), result.FactNnb?.Count()); - } - - [Fact] - public async Task GetTrajectoryAsync_ShouldReturn_StraightBore() - { - //arrange - var plannedTrajectory = new TrajectoryGeoPlanDto[] - { - new() { WellboreDepth = 0, ZenithAngle = 0, AzimuthGeo = 0 }, - new() { WellboreDepth = 0, ZenithAngle = 0, AzimuthGeo = 0 }, - new() { WellboreDepth = 20, ZenithAngle = 0, AzimuthGeo = 0 }, - new() { WellboreDepth = 20, ZenithAngle = 0, AzimuthGeo = 0 }, - new() { WellboreDepth = 30, ZenithAngle = 0, AzimuthGeo = 0 }, - new() { WellboreDepth = 50, ZenithAngle = 0, AzimuthGeo = 0 }, - }; - - var actualTrajectory = new TrajectoryGeoFactDto[] - { - new() { WellboreDepth = 0, ZenithAngle = 0, AzimuthGeo = 0 }, - new() { WellboreDepth = 0, ZenithAngle = 0, AzimuthGeo = 0 }, - new() { WellboreDepth = 20, ZenithAngle = 0, AzimuthGeo = 0 }, - new() { WellboreDepth = 20, ZenithAngle = 0, AzimuthGeo = 0 }, - new() { WellboreDepth = 30, ZenithAngle = 0, AzimuthGeo = 0 }, - new() { WellboreDepth = 50, ZenithAngle = 0, AzimuthGeo = 0 }, - }; - - var nnbTrajectory = new TrajectoryGeoFactDto[] - { - new() { WellboreDepth = 0, ZenithAngle = 0, AzimuthGeo = 0 }, - new() { WellboreDepth = 0, ZenithAngle = 0, AzimuthGeo = 0 }, - new() { WellboreDepth = 20, ZenithAngle = 0, AzimuthGeo = 0 }, - new() { WellboreDepth = 20, ZenithAngle = 0, AzimuthGeo = 0 }, - new() { WellboreDepth = 30, ZenithAngle = 0, AzimuthGeo = 0 }, - new() { WellboreDepth = 50, ZenithAngle = 0, AzimuthGeo = 0 }, - }; - - trajectoryPlanRepositoryMock.GetAsync(Arg.Any(), Arg.Any()) - .ReturnsForAnyArgs(plannedTrajectory); - - trajectoryFactRepositoryMock.GetAsync(Arg.Any(), Arg.Any()) - .ReturnsForAnyArgs(actualTrajectory); - - trajectoryNnbRepositoryMock.GetAsync(Arg.Any(), Arg.Any()) - .ReturnsForAnyArgs(nnbTrajectory); - - //act - var result = await trajectoryService.GetTrajectoryCartesianAsync(1, CancellationToken.None); - - //assert - var lastPointPlan = result.Plan!.Last(); - var lastPointFact = result.FactManual!.Last(); - var lastPointNnb = result.FactNnb!.Last(); - - Assert.Equal(0d, lastPointPlan.X, 0.1d); - Assert.Equal(-50d, lastPointPlan.Y, 0.1d); - Assert.Equal(0d, lastPointPlan.Z, 0.1d); - - Assert.Equal(0d, lastPointFact.X, 0.1d); - Assert.Equal(-50d, lastPointFact.Y, 0.1d); - Assert.Equal(0d, lastPointFact.Z, 0.1d); - - Assert.Equal(0d, lastPointNnb.X, 0.1d); - Assert.Equal(-50d, lastPointNnb.Y, 0.1d); - Assert.Equal(0d, lastPointNnb.Z, 0.1d); - } - - [Fact] - public async Task GetTrajectoryAsync_ShouldReturn_Match() - { - //arrange - const double tolerancePlan = 0.001d; - const double toleranceFact = 0.001d; - - var plannedTrajectory = new TrajectoryGeoPlanDto[] - { - new() { WellboreDepth = 0, ZenithAngle = 0, AzimuthGeo = 0 }, - new() { WellboreDepth = 10, ZenithAngle = 30, AzimuthGeo = 30 }, - new() { WellboreDepth = 20, ZenithAngle = 0, AzimuthGeo = 0 }, - }; - - var actualTrajectory = new TrajectoryGeoFactDto[] - { - new() { WellboreDepth = 0, ZenithAngle = 0, AzimuthGeo = 0 }, - new() { WellboreDepth = 10, ZenithAngle = 30, AzimuthGeo = 30 }, - new() { WellboreDepth = 20, ZenithAngle = 0, AzimuthGeo = 0 }, - }; - - var nnbTrajectory = new TrajectoryGeoFactDto[] - { - new() { WellboreDepth = 0, ZenithAngle = 0, AzimuthGeo = 0 }, - new() { WellboreDepth = 10, ZenithAngle = 30, AzimuthGeo = 30 }, - new() { WellboreDepth = 20, ZenithAngle = 0, AzimuthGeo = 0 }, - }; - - - trajectoryPlanRepositoryMock.GetAsync(Arg.Any(), Arg.Any()) - .ReturnsForAnyArgs(plannedTrajectory); - - trajectoryFactRepositoryMock.GetAsync(Arg.Any(), Arg.Any()) - .ReturnsForAnyArgs(actualTrajectory); - - trajectoryNnbRepositoryMock.GetAsync(Arg.Any(), Arg.Any()) - .ReturnsForAnyArgs(nnbTrajectory); - - //act - var result = await trajectoryService.GetTrajectoryCartesianAsync(1, CancellationToken.None); - - //assert - var lastPointPlan = result.Plan!.Last(); - var lastPointFact = result.FactManual!.Last(); - var lastPointNnb = result.FactManual!.Last(); - - Assert.InRange(lastPointPlan.Z, -10 - tolerancePlan, 0 - tolerancePlan); - Assert.InRange(lastPointPlan.Y, -20 - tolerancePlan, -10 + tolerancePlan); - Assert.InRange(lastPointPlan.X, 0 + tolerancePlan, 10 - tolerancePlan); - - Assert.InRange(lastPointFact.Z, -10 - toleranceFact, 0 - toleranceFact); - Assert.InRange(lastPointFact.Y, -20 - toleranceFact, -10 + toleranceFact); - Assert.InRange(lastPointFact.X, 0 + toleranceFact, 10 - toleranceFact); - - Assert.InRange(lastPointNnb.Z, -10 - toleranceFact, 0 - toleranceFact); - Assert.InRange(lastPointNnb.Y, -20 - toleranceFact, -10 + toleranceFact); - Assert.InRange(lastPointNnb.X, 0 + toleranceFact, 10 - toleranceFact); - } -} \ No newline at end of file diff --git a/AsbCloudWebApi.Tests/UnitTests/Services/WellFinalDocumentsServiceTest.cs b/AsbCloudWebApi.Tests/UnitTests/Services/WellFinalDocumentsServiceTest.cs deleted file mode 100644 index acaa0dcc..00000000 --- a/AsbCloudWebApi.Tests/UnitTests/Services/WellFinalDocumentsServiceTest.cs +++ /dev/null @@ -1,168 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Threading; -using System.Threading.Tasks; -using AsbCloudApp.Data; -using AsbCloudApp.Data.User; -using AsbCloudApp.Repositories; -using AsbCloudApp.Services; -using AsbCloudApp.Services.Notifications; -using AsbCloudInfrastructure.Services; -using Microsoft.Extensions.Configuration; -using NSubstitute; -using Xunit; - -namespace AsbCloudWebApi.Tests.UnitTests.Services; - -public class WellFinalDocumentsServiceTest -{ - private const int idWell = 1; - private const int validInsertedFileId = 555; - private const int idWellFinalDocCategory = 10_000; - private const string editPublisherPermission = "WellFinalDocuments.editPublisher"; - private const string fileName = "test.txt"; - - private static readonly MemoryStream fileStream = new(Array.Empty()); - - private static readonly WellFinalDocumentDto wellFinalDocument = new() - { - IdCategory = idWellFinalDocCategory, - PermissionToUpload = true, - Publishers = new List - { - new() - { - Id = 1 - } - } - }; - - private static readonly UserExtendedDto user = new() - { - Id = 1, - IdCompany = 1, - Surname = "Tester 1", - Name = "Peppa", - Email = "test@test.com" - }; - - private static readonly WellCaseDto wellCase = new() - { - IdWell = 1, - PermissionToSetPubliher = true, - WellFinalDocuments = new[] { wellFinalDocument } - }; - - private static readonly WellFinalDocumentDBDto wellFinalDocumentDB = new() - { - IdCategory = idWellFinalDocCategory, - IdUser = 1, - IdWell = 1 - }; - - private static readonly NotificationCategoryDto notificationCategory = new() - { - Id = 20000, - Name = "Системные уведомления" - }; - - private static readonly WellDto well = new() - { - Id = 1, - Caption = "well 1", - Cluster = "cluster 1", - Deposit = "deposit 1" - }; - - private static readonly FileCategoryDto fileCategory = new() - { - Id = idWellFinalDocCategory, - Name = "Проект на бурение транспортного и горизонтального участков скважины" - }; - - private readonly IConfiguration configuration = new ConfigurationBuilder().Build(); - private readonly IUserRepository userRepositoryMock = Substitute.For(); - private readonly IFileCategoryService fileCategoryServiceMock = Substitute.For(); - private readonly ICrudRepository notificationCategoryRepositoryMock = Substitute.For>(); - private readonly IFileRepository fileRepositoryMock = Substitute.For(); - private readonly IWellFinalDocumentsRepository wellFinalDocumentsRepositoryMock = Substitute.For(); - private readonly IWellService wellServiceMock = Substitute.For(); - private readonly INotificationRepository notificationRepositoryMock = Substitute.For(); - private readonly INotificationTransportService notificationTransportServiceMock = Substitute.For(); - private readonly IFileStorageRepository fileStorageRepositoryMock = Substitute.For(); - - private readonly WellFinalDocumentsService wellFinalDocumentsService; - private readonly FileService fileService; - private readonly NotificationService notificationService; - - - public WellFinalDocumentsServiceTest() - { - wellFinalDocumentsRepositoryMock.GetByWellIdAsync(Arg.Any(), Arg.Any(), Arg.Any()) - .ReturnsForAnyArgs(wellCase); - - wellFinalDocumentsRepositoryMock.GetCategoryAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) - .ReturnsForAnyArgs(wellFinalDocumentDB); - - fileRepositoryMock.InsertAsync(Arg.Any(), Arg.Any()) - .ReturnsForAnyArgs(validInsertedFileId); - - fileRepositoryMock.GetOrDefaultAsync(validInsertedFileId, Arg.Any()) - .ReturnsForAnyArgs(new FileInfoDto { Id = validInsertedFileId }); - - userRepositoryMock.GetAllAsync(Arg.Any()) - .ReturnsForAnyArgs(new[] { user }); - - userRepositoryMock.GetOrDefault(Arg.Any()) - .ReturnsForAnyArgs(user); - - userRepositoryMock.GetOrDefaultAsync(Arg.Any(), Arg.Any()) - .ReturnsForAnyArgs(user); - - userRepositoryMock.HasPermission(user.Id, editPublisherPermission) - .ReturnsForAnyArgs(true); - - wellServiceMock.GetOrDefaultAsync(Arg.Any(), Arg.Any()) - .ReturnsForAnyArgs(well); - - notificationCategoryRepositoryMock.GetOrDefaultAsync(Arg.Any(), - Arg.Any()) - .ReturnsForAnyArgs(notificationCategory); - - fileCategoryServiceMock.GetOrDefaultAsync(idWellFinalDocCategory, Arg.Any()) - .ReturnsForAnyArgs(fileCategory); - - notificationService = new NotificationService(notificationCategoryRepositoryMock, - notificationRepositoryMock, - new[] { notificationTransportServiceMock }); - - fileService = new FileService(fileRepositoryMock, fileStorageRepositoryMock); - - wellFinalDocumentsService = new WellFinalDocumentsService(fileService, userRepositoryMock, wellServiceMock, configuration, - fileCategoryServiceMock, - wellFinalDocumentsRepositoryMock, - notificationService); - } - - [Fact] - public async Task GetHistoryFileByIdCategory_ShouldReturn_EmptyHistory() - { - //act - var data = await wellFinalDocumentsService.GetFilesHistoryByIdCategoryAsync(idWell, idWellFinalDocCategory, CancellationToken.None); - - //assert - Assert.NotNull(data); - Assert.Empty(data.Files); - } - - [Fact] - public async Task SaveCategoryFile_ShouldReturn_FileId() - { - //act - var idFile = await wellFinalDocumentsService.SaveCategoryFileAsync(idWell, idWellFinalDocCategory, user.Id, fileStream, fileName, CancellationToken.None); - - //assert - Assert.Equal(validInsertedFileId, idFile); - } -} \ No newline at end of file diff --git a/AsbCloudWebApi.Tests/UnitTests/Services/WellboreServiceTest.cs b/AsbCloudWebApi.Tests/UnitTests/Services/WellboreServiceTest.cs deleted file mode 100644 index ab6fa939..00000000 --- a/AsbCloudWebApi.Tests/UnitTests/Services/WellboreServiceTest.cs +++ /dev/null @@ -1,240 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using AsbCloudApp.Data; -using AsbCloudApp.Data.SAUB; -using AsbCloudApp.Repositories; -using AsbCloudApp.Requests; -using AsbCloudApp.Services; -using AsbCloudInfrastructure.Services; -using NSubstitute; -using Xunit; - -namespace AsbCloudWebApi.Tests.UnitTests.Services; - -public class WellboreServiceTest -{ - private static WellDto well1 = new() - { - Id = 1, - IdState = 1, - IdTelemetry = 1, - LastTelemetryDate = DateTime.Now, - Caption = "well 1" - }; - - private static WellDto well2 = new() - { - Id = 2, - IdState = 1, - IdTelemetry = 100, - LastTelemetryDate = DateTime.Now, - Caption = "well 2" - }; - - private readonly IWellService wellServiceMock = Substitute.For(); - private readonly IWellOperationRepository wellOperationRepositoryMock = Substitute.For(); - private readonly ITelemetryDataCache telemetryDataCacheMock = Substitute.For>(); - - private readonly WellboreService wellboreService; - - public WellboreServiceTest() - { - wellboreService = new WellboreService(wellServiceMock, wellOperationRepositoryMock, telemetryDataCacheMock); - } - - [Fact] - public async Task GetWellboresAsync_ShouldReturn_EmptyCollection() - { - var result = await wellboreService.GetWellboresAsync(new[] { 1 }, CancellationToken.None); - - Assert.NotNull(result); - Assert.False(result.Any()); - } - - [Fact] - public async Task GetWellboresAsync_ShouldReturn_OneWellboreByWellOnly() - { - wellServiceMock.GetAsync(Arg.Any(), Arg.Any()) - .Returns(new [] { well1 }); - - var result = await wellboreService.GetWellboresAsync(new[] { 1 }, CancellationToken.None); - - Assert.Single(result); - var wellbore0 = result.ElementAt(0); - Assert.Equal(well1.Caption, wellbore0.Well.Caption); - Assert.Equal(well1.Id, wellbore0.Well.Id); - - Assert.Equal("Ствол 1", wellbore0.Name); - Assert.Equal(1, wellbore0.Id); - - Assert.Equal(default, wellbore0.DateStart); - Assert.Equal(default, wellbore0.DateEnd); - Assert.Equal(default, wellbore0.DepthStart); - Assert.Equal(default, wellbore0.DepthEnd); - } - - [Fact] - public async Task GetWellboresAsync_ShouldReturn_TwoWellboreByTwoWellsOnly() - { - wellServiceMock.GetAsync(Arg.Any(), Arg.Any()) - .Returns(new [] { well1, well2 }); - - var result = await wellboreService.GetWellboresAsync(new[] { 1 }, CancellationToken.None); - - Assert.Equal(2, result.Count()); - } - - [Fact] - public async Task GetWellboresAsync_ShouldReturn_TwoWellboreByWellWithSections() - { - wellServiceMock.GetAsync(Arg.Any(), Arg.Any()) - .Returns(new [] { well1 }); - - var section0 = new SectionByOperationsDto - { - IdWell = well1.Id, IdWellSectionType = 0, IdType = 1, DateStart = new DateTime(2023, 01, 01), - DateEnd = new DateTime(2023, 01, 02), DepthStart = 000, DepthEnd = 100 - }; - var section1 = new SectionByOperationsDto - { - IdWell = well1.Id, IdWellSectionType = 0, IdType = 1, DateStart = new DateTime(2023, 01, 02), - DateEnd = new DateTime(2023, 01, 03), DepthStart = 100, DepthEnd = 300 - }; - var section2 = new SectionByOperationsDto - { - IdWell = well1.Id, IdWellSectionType = 0, IdType = 1, DateStart = new DateTime(2023, 01, 03), - DateEnd = new DateTime(2023, 01, 04), DepthStart = 200, DepthEnd = 210 - }; - var section3 = new SectionByOperationsDto - { - IdWell = int.MaxValue, IdWellSectionType = 0, IdType = 1, DateStart = new DateTime(2023, 01, 03), - DateEnd = new DateTime(2023, 01, 04), DepthStart = 200, DepthEnd = 220 - }; - var section4 = new SectionByOperationsDto - { - IdWell = well1.Id, IdWellSectionType = 0, IdType = 0, DateStart = new DateTime(2023, 01, 05), - DateEnd = new DateTime(2023, 01, 06), DepthStart = 150, DepthEnd = 220 - }; - - wellOperationRepositoryMock.GetSectionsAsync(Arg.Any>(), Arg.Any()) - .Returns(new [] { section0, section1, section2, section3, section4, }); - - var result = await wellboreService.GetWellboresAsync(new[] { 1 }, CancellationToken.None); - - Assert.Equal(2, result.Count()); - var wellbore0 = result.ElementAt(0); - Assert.Equal(well1.Caption, wellbore0.Well.Caption); - Assert.Equal(well1.Id, wellbore0.Well.Id); - - Assert.Equal("Ствол 1", wellbore0.Name); - Assert.Equal(1, wellbore0.Id); - - Assert.Equal(section0.DateStart, wellbore0.DateStart); - Assert.Equal(section0.DepthStart, wellbore0.DepthStart); - Assert.Equal(section1.DateEnd, wellbore0.DateEnd); - Assert.Equal(section1.DepthEnd, wellbore0.DepthEnd); - - var wellbore1 = result.ElementAt(1); - Assert.Equal(well1.Caption, wellbore1.Well.Caption); - Assert.Equal(well1.Id, wellbore1.Well.Id); - - Assert.Equal("Ствол 2", wellbore1.Name); - Assert.Equal(2, wellbore1.Id); - - Assert.Equal(section2.DateStart, wellbore1.DateStart); - Assert.Equal(section2.DepthStart, wellbore1.DepthStart); - Assert.Equal(section2.DateEnd, wellbore1.DateEnd); - Assert.Equal(section2.DepthEnd, wellbore1.DepthEnd); - } - - - [Fact] - public async Task GetWellboresAsync_ShouldReturn_OneWellboreByWellWithTelemetry() - { - wellServiceMock.GetAsync(Arg.Any(), Arg.Any()) - .Returns(new [] { well1 }); - - var firstCacheItem = new TelemetryDataSaubDto { DateTime = new DateTime(2000, 01, 01), WellDepth = 0, }; - var lastCacheItem = new TelemetryDataSaubDto { DateTime = new DateTime(2023, 01, 05), WellDepth = 321, }; - - telemetryDataCacheMock.GetOrDefaultFirstLast(Arg.Any()) - .Returns((firstCacheItem, lastCacheItem)); - - var result = await wellboreService.GetWellboresAsync(new[] { 1 }, CancellationToken.None); - - Assert.Single(result); - var wellbore0 = result.ElementAt(0); - Assert.Equal(well1.Caption, wellbore0.Well.Caption); - Assert.Equal(well1.Id, wellbore0.Well.Id); - - Assert.Equal("Ствол 1", wellbore0.Name); - Assert.Equal(1, wellbore0.Id); - - Assert.Equal(firstCacheItem.DateTime, wellbore0.DateStart); - Assert.Equal(firstCacheItem.WellDepth!.Value, wellbore0.DepthStart); - Assert.Equal(lastCacheItem.DateTime, wellbore0.DateEnd); - Assert.Equal(lastCacheItem.WellDepth!.Value, wellbore0.DepthEnd); - } - - [Fact] - public async Task GetWellboresAsync_ShouldReturn_TwoWellboreByWellWithAll() - { - wellServiceMock.GetAsync(Arg.Any(), Arg.Any()) - .Returns(new [] { well1 }); - - var section0 = new SectionByOperationsDto - { - IdWell = well1.Id, IdWellSectionType = 0, IdType = 1, DateStart = new DateTime(2023, 01, 01), - DateEnd = new DateTime(2023, 01, 02), DepthStart = 000, DepthEnd = 100 - }; - var section1 = new SectionByOperationsDto - { - IdWell = well1.Id, IdWellSectionType = 0, IdType = 1, DateStart = new DateTime(2023, 01, 02), - DateEnd = new DateTime(2023, 01, 03), DepthStart = 100, DepthEnd = 300 - }; - var section2 = new SectionByOperationsDto - { - IdWell = well1.Id, IdWellSectionType = 0, IdType = 1, DateStart = new DateTime(2023, 01, 03), - DateEnd = new DateTime(2023, 01, 04), DepthStart = 200, DepthEnd = 210 - }; - - wellOperationRepositoryMock.GetSectionsAsync(Arg.Any>(), Arg.Any()) - .Returns(new [] { section0, section1, section2 }); - - var firstCacheItem = new TelemetryDataSaubDto { DateTime = new DateTime(2000, 01, 01), WellDepth = 0, }; - var lastCacheItem = new TelemetryDataSaubDto { DateTime = new DateTime(2023, 01, 05), WellDepth = 321, }; - - telemetryDataCacheMock.GetOrDefaultFirstLast(Arg.Any()) - .Returns((firstCacheItem, lastCacheItem)); - - var result = await wellboreService.GetWellboresAsync(new[] { 1 }, CancellationToken.None); - - Assert.Equal(2, result.Count()); - var wellbore0 = result.ElementAt(0); - Assert.Equal(well1.Caption, wellbore0.Well.Caption); - Assert.Equal(well1.Id, wellbore0.Well.Id); - - Assert.Equal("Ствол 1", wellbore0.Name); - Assert.Equal(1, wellbore0.Id); - - Assert.Equal(section0.DateStart, wellbore0.DateStart); - Assert.Equal(section0.DepthStart, wellbore0.DepthStart); - Assert.Equal(section1.DateEnd, wellbore0.DateEnd); - Assert.Equal(section1.DepthEnd, wellbore0.DepthEnd); - - var wellbore1 = result.ElementAt(1); - Assert.Equal(well1.Caption, wellbore1.Well.Caption); - Assert.Equal(well1.Id, wellbore1.Well.Id); - - Assert.Equal("Ствол 2", wellbore1.Name); - Assert.Equal(2, wellbore1.Id); - - Assert.Equal(section2.DateStart, wellbore1.DateStart); - Assert.Equal(section2.DepthStart, wellbore1.DepthStart); - Assert.Equal(lastCacheItem.DateTime, wellbore1.DateEnd); - Assert.Equal(lastCacheItem.WellDepth!.Value, wellbore1.DepthEnd); - } -} \ No newline at end of file