remove DateValidationAttribute,

reorganize and fix unitTests
This commit is contained in:
Frolov-Nikita 2024-01-21 13:43:15 +05:00
parent f69bec9687
commit cfe936abf0
No known key found for this signature in database
GPG Key ID: 719E3386D12B0760
33 changed files with 1959 additions and 2101 deletions

View File

@ -114,11 +114,6 @@ namespace AsbCloudApp.Data
/// <returns></returns>
public IEnumerable<ValidationResult> 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(

View File

@ -1,32 +1,43 @@
using AsbCloudApp.Validation;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace AsbCloudApp.Requests;
/// <summary>
/// Параметры для создания отчёта и получения прогнозируемого количества страниц будущего отчета
/// </summary>
public class ReportParametersRequest
public class ReportParametersRequest: IValidatableObject
{
/// <summary>
/// Шаг интервала
/// </summary>
public int StepSeconds { get; set; }
/// <summary>
/// Шаг интервала
/// </summary>
[Range(1, 86400)]
public int StepSeconds { get; set; }
/// <summary>
/// формат отчета (0-PDF, 1-LAS)
/// </summary>
[Range(0, 1)]
public int Format { get; set; }
/// <summary>
/// Дата начала интервала
/// </summary>
[DateValidation(GtDate ="2000-01-01")]
public DateTime Begin { get; set; } = default;
/// <summary>
/// Дата окончания интервала
/// </summary>
[DateValidation(GtDate ="2000-01-01")]
public DateTime End { get; set; } = default;
/// <inheritdoc/>
public IEnumerable<ValidationResult> 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");
}
}

View File

@ -1,80 +0,0 @@
using System;
using System.ComponentModel.DataAnnotations;
namespace AsbCloudApp.Validation
{
/// <summary>
/// Атрибут валидации даты-времени
/// </summary>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property)]
public class DateValidationAttribute : ValidationAttribute
{
private DateTime? gtDate;
/// <summary>
/// null разрешен
/// </summary>
public bool AllowNull { get; set; } = true;
/// <summary>
/// Разрешена только дат.
/// При наличии времени в DateTime инвалидирует.
/// При наличии UTC тоже инвалидирует.
/// </summary>
public bool IsDateOnly { get; set; } = false;
/// <summary>
/// Допустима дата-время в UTC
/// </summary>
public bool AllowUtc { get; set; } = true;
/// <summary>
/// Дата больше которой должно быть проверяемое значение.
/// Формат строки - любой поддерживаемый DateTime.Parse.
/// Желательно использовать ISO 8601 формат
/// </summary>
public string? GtDate {
get => gtDate.ToString();
set
{
if(value is null)
gtDate = null;
else
gtDate = DateTime.Parse(value);
}
}
/// <summary>
/// Проверка значения
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
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;
}
}
}

View File

@ -9,13 +9,13 @@
</PropertyGroup>
<ItemGroup>
<None Remove="UnitTests\Services\Trajectory\PlannedTrajectoryTemplate.xlsx" />
<None Remove="UnitTests\Services\Trajectory\Templates\TrajectoryFactManualTemplate.xlsx" />
<None Remove="Services\Trajectory\PlannedTrajectoryTemplate.xlsx" />
<None Remove="Services\Trajectory\Templates\TrajectoryFactManualTemplate.xlsx" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="UnitTests\Services\Trajectory\Templates\TrajectoryFactManualTemplate.xlsx" />
<EmbeddedResource Include="UnitTests\Services\Trajectory\Templates\TrajectoryPlanTemplate.xlsx" />
<EmbeddedResource Include="Services\Trajectory\Templates\TrajectoryFactManualTemplate.xlsx" />
<EmbeddedResource Include="Services\Trajectory\Templates\TrajectoryPlanTemplate.xlsx" />
</ItemGroup>
<ItemGroup>

View File

@ -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);
}
}
}

View File

@ -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<IServiceProvider, ISupportRequiredService>();
private readonly IServiceScope serviceScopeMock = Substitute.For<IServiceScope>();
private readonly IServiceScopeFactory serviceScopeFactoryMock = Substitute.For<IServiceScopeFactory>();
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<string, double?> 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<string, double?> callback, CancellationToken token)
{
result = expectadResult;
return Task.CompletedTask;
}
var goodWork = Work.CreateByDelegate("", workAction);
Task failAction(string id, IServiceProvider services, Action<string, double?> 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<string, double?> 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);
}
}

View File

@ -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);

View File

@ -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<IServiceProvider, ISupportRequiredService>();
private readonly IServiceScope serviceScopeMock = Substitute.For<IServiceScope>();
private readonly IServiceScopeFactory serviceScopeFactoryMock = Substitute.For<IServiceScopeFactory>();
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<string, double?> 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<string, double?> 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<string, double?> 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<string, double?> 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);
}
}

View File

@ -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<double?>
{
Plan = 2000
},
WellOperations = new[]
{
new TimeBalanceRecordDto
{
IdWellOperation = 1,
DurationHours = new PlanFactDto<double?>
{
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<double?>
{
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<IWellService>();
private readonly ITrajectoryNnbRepository trajectoryFactNnbRepositoryMock = Substitute.For<ITrajectoryNnbRepository>();
private readonly IDailyReportRepository dailyReportRepositoryMock = Substitute.For<IDailyReportRepository>();
private readonly IScheduleRepository scheduleRepositoryMock = Substitute.For<IScheduleRepository>();
private readonly IWellOperationRepository wellOperationRepositoryMock = Substitute.For<IWellOperationRepository>();
private readonly ISubsystemService subsystemServiceMock = Substitute.For<ISubsystemService>();
private readonly IProcessMapReportWellDrillingService processMapReportWellDrillingServiceMock = Substitute.For<IProcessMapReportWellDrillingService>();
private readonly IDetectedOperationService detectedOperationServiceMock = Substitute.For<IDetectedOperationService>();
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<DailyReportDto>(), Arg.Any<CancellationToken>())
.ReturnsForAnyArgs(idDailyReport);
dailyReportRepositoryMock.GetOrDefaultAsync(Arg.Any<int>(), Arg.Any<DateOnly>(), Arg.Any<CancellationToken>())
.ReturnsForAnyArgs(fakeDailyReport);
dailyReportRepositoryMock.UpdateAsync(Arg.Any<DailyReportDto>(), Arg.Any<CancellationToken>())
.ReturnsForAnyArgs(idDailyReport);
wellServiceMock.GetOrDefaultAsync(Arg.Any<int>(), Arg.Any<CancellationToken>())
.ReturnsForAnyArgs(fakeWell);
trajectoryFactNnbRepositoryMock.GetByRequestAsync(Arg.Any<TrajectoryRequest>(), Arg.Any<CancellationToken>())
.ReturnsForAnyArgs(new[] { fakeLastFactTrajectory });
wellOperationRepositoryMock.GetAsync(Arg.Any<WellOperationRequest>(), Arg.Any<CancellationToken>())
.ReturnsForAnyArgs(new[] { fakeFirstFactWellOperation, fakeLastFactWellOperation });
wellOperationRepositoryMock.GetDatesRangeAsync(Arg.Any<int>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
.ReturnsForAnyArgs(fakeDatesRange);
wellOperationRepositoryMock.GetSectionTypes()
.ReturnsForAnyArgs(new[] { fakeSectionType });
detectedOperationServiceMock.GetAsync(Arg.Any<DetectedOperationRequest>(), Arg.Any<CancellationToken>())
.ReturnsForAnyArgs(fakeWellOperationSlipsTime);
subsystemServiceMock.GetStatAsync(Arg.Any<SubsystemRequest>(), Arg.Any<CancellationToken>())
.ReturnsForAnyArgs(new[] { fakeSubsystemsStat });
scheduleRepositoryMock.GetAsync(Arg.Any<int>(), Arg.Any<DateTime>(), Arg.Any<CancellationToken>())
.ReturnsForAnyArgs(new[] { fakeShedule });
processMapReportWellDrillingServiceMock.GetAsync(Arg.Any<int>(), Arg.Any<CancellationToken>())
.ReturnsForAnyArgs(new[] { fakeProcessMapReportWellDrilling });
wellServiceMock.GetTimezone(Arg.Any<int>())
.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<ArgumentInvalidException>(() => 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<ArgumentInvalidException>(() => 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<int>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
.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<object[]> DateDailyReport()
{
yield return new object[]
{
new DateOnly(2090, 01, 01),
};
yield return new object[]
{
new DateOnly(2000, 01, 01)
};
}
public static IEnumerable<object[]> 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)
}
};
}
}

View File

@ -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<byte>());
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<IFileRepository>();
private readonly IFileStorageRepository storageRepositoryMock = Substitute.For<IFileStorageRepository>();
private readonly FileService fileService;
public FileServiceTest()
{
fileRepositoryMock.GetByMarkId(Arg.Any<int>(), Arg.Any<CancellationToken>())
.ReturnsForAnyArgs(fileInfo);
fileRepositoryMock.GetInfoByIdsAsync(Arg.Any<IEnumerable<int>>(), Arg.Any<CancellationToken>())
.ReturnsForAnyArgs(new[] { fileInfo });
fileRepositoryMock.DeleteAsync(Arg.Any<IEnumerable<int>>(), Arg.Any<CancellationToken>())
.ReturnsForAnyArgs(new[] { fileInfo });
fileRepositoryMock.MarkFileMarkAsDeletedAsync(Arg.Any<IEnumerable<int>>(), Arg.Any<CancellationToken>())
.ReturnsForAnyArgs(fileMark.Id);
fileRepositoryMock.MarkAsDeletedAsync(Arg.Any<int>(), Arg.Any<CancellationToken>())
.ReturnsForAnyArgs(fileMark.Id);
fileRepositoryMock.GetInfosAsync(Arg.Any<FileRequest>(), Arg.Any<CancellationToken>())
.ReturnsForAnyArgs(new[] { fileInfo });
fileRepositoryMock.CreateFileMarkAsync(Arg.Any<FileMarkDto>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
.ReturnsForAnyArgs(fileMark.Id);
fileRepositoryMock.GetOrDefaultAsync(Arg.Any<int>(), Arg.Any<CancellationToken>())
.ReturnsForAnyArgs(fileInfo);
storageRepositoryMock.GetFilePath(Arg.Any<int>(), Arg.Any<int>(), Arg.Any<int>(), Arg.Any<string>())
.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);
}
}

View File

@ -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<string, string> configSettings = new()
{
{ "DirectoryNameHelpPageFiles", "helpPages" }
};
private static readonly MemoryStream fileStream = new(Array.Empty<byte>());
private static readonly HelpPageDto existingHelpPage = new()
{
Id = 178,
IdCategory = idCategory,
UrlPage = "test2",
Name = "Справка_для_страницы_test2.pdf"
};
private readonly IHelpPageRepository helpPageRepositoryMock = Substitute.For<IHelpPageRepository>();
private readonly IFileStorageRepository fileStorageRepositoryMock = Substitute.For<IFileStorageRepository>();
private readonly HelpPageService helpPageService;
public HelpPageServiceTest()
{
IConfiguration configuration = new ConfigurationBuilder()
.AddInMemoryCollection(configSettings)
.Build();
helpPageRepositoryMock.GetOrDefaultByUrlPageAndIdCategoryAsync(existingHelpPage.UrlPage, existingHelpPage.IdCategory, Arg.Any<CancellationToken>())
.Returns(existingHelpPage);
helpPageRepositoryMock.InsertAsync(Arg.Any<HelpPageDto>(), Arg.Any<CancellationToken>())
.ReturnsForAnyArgs(1);
fileStorageRepositoryMock.SaveFileAsync(Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<CancellationToken>());
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<HelpPageDto>(), Arg.Any<CancellationToken>());
await fileStorageRepositoryMock.Received().SaveFileAsync(Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<CancellationToken>());
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<HelpPageDto>(), Arg.Any<CancellationToken>());
await fileStorageRepositoryMock.Received().SaveFileAsync(Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<CancellationToken>());
Assert.Equal(existingHelpPage.Id, result);
}
}

View File

@ -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
{

View File

@ -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<WellSectionPlanDto> fakeCollectionWellSectionPlan = new WellSectionPlanDto[]
{
new()
{
Id = idWellSectionPlan,
IdWell = idWell,
IdSectionType = idWellSectionType,
DepthStart = 80,
DepthEnd = 150
}
};
private readonly IEnumerable<WellSectionTypeDto> fakeCollectionWellSectionTypes = new WellSectionTypeDto[]
{
new()
{
Id = idWellSectionType,
Caption = "Направление 1",
Order = 1
}
};
private readonly ICrudRepository<WellSectionTypeDto> wellSectionTypeRepositoryMock =
Substitute.For<ICrudRepository<WellSectionTypeDto>>();
private readonly IProcessMapPlanRepository<ProcessMapPlanWellDrillingDto> processMapPlanRepositoryMock =
Substitute.For<IProcessMapPlanRepository<ProcessMapPlanWellDrillingDto>>();
private readonly IRepositoryWellRelated<WellSectionPlanDto> wellSectionPlanRepositoryMock =
Substitute.For<IRepositoryWellRelated<WellSectionPlanDto>>();
private readonly ProcessMapPlanService<ProcessMapPlanWellDrillingDto> processMapPlanService;
public ProcessMapPlanServiceTests()
{
processMapPlanService = new ProcessMapPlanService<ProcessMapPlanWellDrillingDto>(wellSectionTypeRepositoryMock,
processMapPlanRepositoryMock, wellSectionPlanRepositoryMock);
wellSectionPlanRepositoryMock.GetByIdWellAsync(Arg.Any<int>(), Arg.Any<CancellationToken>())
.ReturnsForAnyArgs(fakeCollectionWellSectionPlan);
wellSectionTypeRepositoryMock.GetAllAsync(Arg.Any<CancellationToken>())
.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<int>(), Arg.Any<CancellationToken>())
.ReturnsForAnyArgs(fakeCollectionProcessMapPlanWellDrilling);
//act
var result = (await processMapPlanService.GetAsync(idWell, CancellationToken.None)).ToArray();
//assert
Assert.Equal(isValidCollection, result.All(r => r.IsValid));
Assert.Single(result);
}
}

View File

@ -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<TelemetryDataSaubDto> fakeTelemetries = new[]
{
new TelemetryDataSaubDto()
};
private readonly IServiceProvider serviceProviderMock = Substitute.For<IServiceProvider>();
private readonly TelemetryDataCache<TelemetryDataSaubDto> telemetryDataCache;
private readonly Type telemetryDataCacheType;
public TelemetryDataSaubCacheTests()
{
serviceProviderMock.GetService<BackgroundWorker>().Returns(new BackgroundWorker(serviceProviderMock));
telemetryDataCache = TelemetryDataCache<TelemetryDataSaubDto>.GetInstance<TelemetryDataSaub>(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 );
}
}

View File

@ -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
{

View File

@ -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()
{

View File

@ -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<TrajectoryGeoPlanDto> trajectoryPlanRepositoryMock = Substitute.For<ITrajectoryEditableRepository<TrajectoryGeoPlanDto>>();
private readonly ITrajectoryEditableRepository<TrajectoryGeoFactDto> trajectoryFactRepositoryMock = Substitute.For<ITrajectoryEditableRepository<TrajectoryGeoFactDto>>();
private readonly ITrajectoryNnbRepository trajectoryNnbRepositoryMock = Substitute.For<ITrajectoryNnbRepository>();
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<int>(), Arg.Any<CancellationToken>())
.ReturnsForAnyArgs(plannedTrajectory);
trajectoryFactRepositoryMock.GetAsync(Arg.Any<int>(), Arg.Any<CancellationToken>())
.ReturnsForAnyArgs(actualTrajectory);
trajectoryNnbRepositoryMock.GetAsync(Arg.Any<int>(), Arg.Any<CancellationToken>())
.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<int>(), Arg.Any<CancellationToken>())
.ReturnsForAnyArgs(plannedTrajectory);
trajectoryFactRepositoryMock.GetAsync(Arg.Any<int>(), Arg.Any<CancellationToken>())
.ReturnsForAnyArgs(actualTrajectory);
trajectoryNnbRepositoryMock.GetAsync(Arg.Any<int>(), Arg.Any<CancellationToken>())
.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<int>(), Arg.Any<CancellationToken>())
.ReturnsForAnyArgs(plannedTrajectory);
trajectoryFactRepositoryMock.GetAsync(Arg.Any<int>(), Arg.Any<CancellationToken>())
.ReturnsForAnyArgs(actualTrajectory);
trajectoryNnbRepositoryMock.GetAsync(Arg.Any<int>(), Arg.Any<CancellationToken>())
.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);
}
}

View File

@ -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<byte>());
private static readonly WellFinalDocumentDto wellFinalDocument = new()
{
IdCategory = idWellFinalDocCategory,
PermissionToUpload = true,
Publishers = new List<UserDto>
{
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<IUserRepository>();
private readonly IFileCategoryService fileCategoryServiceMock = Substitute.For<IFileCategoryService>();
private readonly ICrudRepository<NotificationCategoryDto> notificationCategoryRepositoryMock = Substitute.For<ICrudRepository<NotificationCategoryDto>>();
private readonly IFileRepository fileRepositoryMock = Substitute.For<IFileRepository>();
private readonly IWellFinalDocumentsRepository wellFinalDocumentsRepositoryMock = Substitute.For<IWellFinalDocumentsRepository>();
private readonly IWellService wellServiceMock = Substitute.For<IWellService>();
private readonly INotificationRepository notificationRepositoryMock = Substitute.For<INotificationRepository>();
private readonly INotificationTransportService notificationTransportServiceMock = Substitute.For<INotificationTransportService>();
private readonly IFileStorageRepository fileStorageRepositoryMock = Substitute.For<IFileStorageRepository>();
private readonly WellFinalDocumentsService wellFinalDocumentsService;
private readonly FileService fileService;
private readonly NotificationService notificationService;
public WellFinalDocumentsServiceTest()
{
wellFinalDocumentsRepositoryMock.GetByWellIdAsync(Arg.Any<int>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
.ReturnsForAnyArgs(wellCase);
wellFinalDocumentsRepositoryMock.GetCategoryAsync(Arg.Any<int>(), Arg.Any<int>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
.ReturnsForAnyArgs(wellFinalDocumentDB);
fileRepositoryMock.InsertAsync(Arg.Any<FileInfoDto>(), Arg.Any<CancellationToken>())
.ReturnsForAnyArgs(validInsertedFileId);
fileRepositoryMock.GetOrDefaultAsync(validInsertedFileId, Arg.Any<CancellationToken>())
.ReturnsForAnyArgs(new FileInfoDto { Id = validInsertedFileId });
userRepositoryMock.GetAllAsync(Arg.Any<CancellationToken>())
.ReturnsForAnyArgs(new[] { user });
userRepositoryMock.GetOrDefault(Arg.Any<int>())
.ReturnsForAnyArgs(user);
userRepositoryMock.GetOrDefaultAsync(Arg.Any<int>(), Arg.Any<CancellationToken>())
.ReturnsForAnyArgs(user);
userRepositoryMock.HasPermission(user.Id, editPublisherPermission)
.ReturnsForAnyArgs(true);
wellServiceMock.GetOrDefaultAsync(Arg.Any<int>(), Arg.Any<CancellationToken>())
.ReturnsForAnyArgs(well);
notificationCategoryRepositoryMock.GetOrDefaultAsync(Arg.Any<int>(),
Arg.Any<CancellationToken>())
.ReturnsForAnyArgs(notificationCategory);
fileCategoryServiceMock.GetOrDefaultAsync(idWellFinalDocCategory, Arg.Any<CancellationToken>())
.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);
}
}

View File

@ -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<string> GetPropsWithDefaultValue<T>(T dto, params string[] excludeProps)
{
IEnumerable<PropertyInfo> 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)

View File

@ -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<IWellService>();
private readonly IWellOperationRepository wellOperationRepositoryMock = Substitute.For<IWellOperationRepository>();
private readonly ITelemetryDataCache<TelemetryDataSaubDto> telemetryDataCacheMock = Substitute.For<ITelemetryDataCache<TelemetryDataSaubDto>>();
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<WellRequest>(), Arg.Any<CancellationToken>())
.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<WellRequest>(), Arg.Any<CancellationToken>())
.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<WellRequest>(), Arg.Any<CancellationToken>())
.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<IEnumerable<int>>(), Arg.Any<CancellationToken>())
.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<WellRequest>(), Arg.Any<CancellationToken>())
.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<int>())
.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<WellRequest>(), Arg.Any<CancellationToken>())
.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<IEnumerable<int>>(), Arg.Any<CancellationToken>())
.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<int>())
.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);
}
}

View File

@ -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<IServiceProvider, ISupportRequiredService>();
private readonly IServiceScope serviceScopeMock = Substitute.For<IServiceScope>();
private readonly IServiceScopeFactory serviceScopeFactoryMock = Substitute.For<IServiceScopeFactory>();
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<string, double?> 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<string, double?> callback, CancellationToken token)
{
result = expectadResult;
return Task.CompletedTask;
}
var goodWork = Work.CreateByDelegate("", workAction);
Task failAction(string id, IServiceProvider services, Action<string, double?> 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<string, double?> 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);
}
}

View File

@ -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<IServiceProvider, ISupportRequiredService>();
private readonly IServiceScope serviceScopeMock = Substitute.For<IServiceScope>();
private readonly IServiceScopeFactory serviceScopeFactoryMock = Substitute.For<IServiceScopeFactory>();
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<string, double?> 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<string, double?> 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<string, double?> 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<string, double?> 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);
}
}

View File

@ -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<double?>
{
Plan = 2000
},
WellOperations = new[]
{
new TimeBalanceRecordDto
{
IdWellOperation = 1,
DurationHours = new PlanFactDto<double?>
{
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<double?>
{
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<IWellService>();
private readonly ITrajectoryNnbRepository trajectoryFactNnbRepositoryMock = Substitute.For<ITrajectoryNnbRepository>();
private readonly IDailyReportRepository dailyReportRepositoryMock = Substitute.For<IDailyReportRepository>();
private readonly IScheduleRepository scheduleRepositoryMock = Substitute.For<IScheduleRepository>();
private readonly IWellOperationRepository wellOperationRepositoryMock = Substitute.For<IWellOperationRepository>();
private readonly ISubsystemService subsystemServiceMock = Substitute.For<ISubsystemService>();
private readonly IProcessMapReportWellDrillingService processMapReportWellDrillingServiceMock = Substitute.For<IProcessMapReportWellDrillingService>();
private readonly IDetectedOperationService detectedOperationServiceMock = Substitute.For<IDetectedOperationService>();
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<DailyReportDto>(), Arg.Any<CancellationToken>())
.ReturnsForAnyArgs(idDailyReport);
dailyReportRepositoryMock.GetOrDefaultAsync(Arg.Any<int>(), Arg.Any<DateOnly>(), Arg.Any<CancellationToken>())
.ReturnsForAnyArgs(fakeDailyReport);
dailyReportRepositoryMock.UpdateAsync(Arg.Any<DailyReportDto>(), Arg.Any<CancellationToken>())
.ReturnsForAnyArgs(idDailyReport);
wellServiceMock.GetOrDefaultAsync(Arg.Any<int>(), Arg.Any<CancellationToken>())
.ReturnsForAnyArgs(fakeWell);
trajectoryFactNnbRepositoryMock.GetByRequestAsync(Arg.Any<TrajectoryRequest>(), Arg.Any<CancellationToken>())
.ReturnsForAnyArgs(new[] { fakeLastFactTrajectory });
wellOperationRepositoryMock.GetAsync(Arg.Any<WellOperationRequest>(), Arg.Any<CancellationToken>())
.ReturnsForAnyArgs(new[] { fakeFirstFactWellOperation, fakeLastFactWellOperation });
wellOperationRepositoryMock.GetDatesRangeAsync(Arg.Any<int>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
.ReturnsForAnyArgs(fakeDatesRange);
wellOperationRepositoryMock.GetSectionTypes()
.ReturnsForAnyArgs(new[] { fakeSectionType });
detectedOperationServiceMock.GetAsync(Arg.Any<DetectedOperationRequest>(), Arg.Any<CancellationToken>())
.ReturnsForAnyArgs(fakeWellOperationSlipsTime);
subsystemServiceMock.GetStatAsync(Arg.Any<SubsystemRequest>(), Arg.Any<CancellationToken>())
.ReturnsForAnyArgs(new[] { fakeSubsystemsStat });
scheduleRepositoryMock.GetAsync(Arg.Any<int>(), Arg.Any<DateTime>(), Arg.Any<CancellationToken>())
.ReturnsForAnyArgs(new[] { fakeShedule });
processMapReportWellDrillingServiceMock.GetAsync(Arg.Any<int>(), Arg.Any<CancellationToken>())
.ReturnsForAnyArgs(new[] { fakeProcessMapReportWellDrilling });
wellServiceMock.GetTimezone(Arg.Any<int>())
.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<ArgumentInvalidException>(() => 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<ArgumentInvalidException>(() => 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<int>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
.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<object[]> DateDailyReport()
{
yield return new object[]
{
new DateOnly(2090, 01, 01),
};
yield return new object[]
{
new DateOnly(2000, 01, 01)
};
}
public static IEnumerable<object[]> 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)
}
};
}
}

View File

@ -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<byte>());
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<IFileRepository>();
private readonly IFileStorageRepository storageRepositoryMock = Substitute.For<IFileStorageRepository>();
private readonly FileService fileService;
public FileServiceTest()
{
fileRepositoryMock.GetByMarkId(Arg.Any<int>(), Arg.Any<CancellationToken>())
.ReturnsForAnyArgs(fileInfo);
fileRepositoryMock.GetInfoByIdsAsync(Arg.Any<IEnumerable<int>>(), Arg.Any<CancellationToken>())
.ReturnsForAnyArgs(new[] { fileInfo });
fileRepositoryMock.DeleteAsync(Arg.Any<IEnumerable<int>>(), Arg.Any<CancellationToken>())
.ReturnsForAnyArgs(new[] { fileInfo });
fileRepositoryMock.MarkFileMarkAsDeletedAsync(Arg.Any<IEnumerable<int>>(), Arg.Any<CancellationToken>())
.ReturnsForAnyArgs(fileMark.Id);
fileRepositoryMock.MarkAsDeletedAsync(Arg.Any<int>(), Arg.Any<CancellationToken>())
.ReturnsForAnyArgs(fileMark.Id);
fileRepositoryMock.GetInfosAsync(Arg.Any<FileRequest>(), Arg.Any<CancellationToken>())
.ReturnsForAnyArgs(new[] { fileInfo });
fileRepositoryMock.CreateFileMarkAsync(Arg.Any<FileMarkDto>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
.ReturnsForAnyArgs(fileMark.Id);
fileRepositoryMock.GetOrDefaultAsync(Arg.Any<int>(), Arg.Any<CancellationToken>())
.ReturnsForAnyArgs(fileInfo);
storageRepositoryMock.GetFilePath(Arg.Any<int>(), Arg.Any<int>(), Arg.Any<int>(), Arg.Any<string>())
.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);
}
}

View File

@ -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<string, string> configSettings = new()
{
{ "DirectoryNameHelpPageFiles", "helpPages" }
};
private static readonly MemoryStream fileStream = new(Array.Empty<byte>());
private static readonly HelpPageDto existingHelpPage = new()
{
Id = 178,
IdCategory = idCategory,
UrlPage = "test2",
Name = "Справка_для_страницы_test2.pdf"
};
private readonly IHelpPageRepository helpPageRepositoryMock = Substitute.For<IHelpPageRepository>();
private readonly IFileStorageRepository fileStorageRepositoryMock = Substitute.For<IFileStorageRepository>();
private readonly HelpPageService helpPageService;
public HelpPageServiceTest()
{
IConfiguration configuration = new ConfigurationBuilder()
.AddInMemoryCollection(configSettings)
.Build();
helpPageRepositoryMock.GetOrDefaultByUrlPageAndIdCategoryAsync(existingHelpPage.UrlPage, existingHelpPage.IdCategory, Arg.Any<CancellationToken>())
.Returns(existingHelpPage);
helpPageRepositoryMock.InsertAsync(Arg.Any<HelpPageDto>(), Arg.Any<CancellationToken>())
.ReturnsForAnyArgs(1);
fileStorageRepositoryMock.SaveFileAsync(Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<CancellationToken>());
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<HelpPageDto>(), Arg.Any<CancellationToken>());
await fileStorageRepositoryMock.Received().SaveFileAsync(Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<CancellationToken>());
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<HelpPageDto>(), Arg.Any<CancellationToken>());
await fileStorageRepositoryMock.Received().SaveFileAsync(Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<CancellationToken>());
Assert.Equal(existingHelpPage.Id, result);
}
}

View File

@ -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<WellSectionPlanDto> fakeCollectionWellSectionPlan = new WellSectionPlanDto[]
{
new()
{
Id = idWellSectionPlan,
IdWell = idWell,
IdSectionType = idWellSectionType,
DepthStart = 80,
DepthEnd = 150
}
};
private readonly IEnumerable<WellSectionTypeDto> fakeCollectionWellSectionTypes = new WellSectionTypeDto[]
{
new()
{
Id = idWellSectionType,
Caption = "Направление 1",
Order = 1
}
};
private readonly ICrudRepository<WellSectionTypeDto> wellSectionTypeRepositoryMock =
Substitute.For<ICrudRepository<WellSectionTypeDto>>();
private readonly IProcessMapPlanRepository<ProcessMapPlanWellDrillingDto> processMapPlanRepositoryMock =
Substitute.For<IProcessMapPlanRepository<ProcessMapPlanWellDrillingDto>>();
private readonly IRepositoryWellRelated<WellSectionPlanDto> wellSectionPlanRepositoryMock =
Substitute.For<IRepositoryWellRelated<WellSectionPlanDto>>();
private readonly ProcessMapPlanService<ProcessMapPlanWellDrillingDto> processMapPlanService;
public ProcessMapPlanServiceTests()
{
processMapPlanService = new ProcessMapPlanService<ProcessMapPlanWellDrillingDto>(wellSectionTypeRepositoryMock,
processMapPlanRepositoryMock, wellSectionPlanRepositoryMock);
wellSectionPlanRepositoryMock.GetByIdWellAsync(Arg.Any<int>(), Arg.Any<CancellationToken>())
.ReturnsForAnyArgs(fakeCollectionWellSectionPlan);
wellSectionTypeRepositoryMock.GetAllAsync(Arg.Any<CancellationToken>())
.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<int>(), Arg.Any<CancellationToken>())
.ReturnsForAnyArgs(fakeCollectionProcessMapPlanWellDrilling);
//act
var result = (await processMapPlanService.GetAsync(idWell, CancellationToken.None)).ToArray();
//assert
Assert.Equal(isValidCollection, result.All(r => r.IsValid));
Assert.Single(result);
}
}

View File

@ -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<TelemetryDataSaubDto> fakeTelemetries = new[]
{
new TelemetryDataSaubDto()
};
private readonly IServiceProvider serviceProviderMock = Substitute.For<IServiceProvider>();
private readonly TelemetryDataCache<TelemetryDataSaubDto> telemetryDataCache;
private readonly Type telemetryDataCacheType;
public TelemetryDataSaubCacheTests()
{
serviceProviderMock.GetService<BackgroundWorker>().Returns(new BackgroundWorker(serviceProviderMock));
telemetryDataCache = TelemetryDataCache<TelemetryDataSaubDto>.GetInstance<TelemetryDataSaub>(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());
}
}

View File

@ -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<TrajectoryGeoPlanDto> trajectoryPlanRepositoryMock = Substitute.For<ITrajectoryEditableRepository<TrajectoryGeoPlanDto>>();
private readonly ITrajectoryEditableRepository<TrajectoryGeoFactDto> trajectoryFactRepositoryMock = Substitute.For<ITrajectoryEditableRepository<TrajectoryGeoFactDto>>();
private readonly ITrajectoryNnbRepository trajectoryNnbRepositoryMock = Substitute.For<ITrajectoryNnbRepository>();
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<int>(), Arg.Any<CancellationToken>())
.ReturnsForAnyArgs(plannedTrajectory);
trajectoryFactRepositoryMock.GetAsync(Arg.Any<int>(), Arg.Any<CancellationToken>())
.ReturnsForAnyArgs(actualTrajectory);
trajectoryNnbRepositoryMock.GetAsync(Arg.Any<int>(), Arg.Any<CancellationToken>())
.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<int>(), Arg.Any<CancellationToken>())
.ReturnsForAnyArgs(plannedTrajectory);
trajectoryFactRepositoryMock.GetAsync(Arg.Any<int>(), Arg.Any<CancellationToken>())
.ReturnsForAnyArgs(actualTrajectory);
trajectoryNnbRepositoryMock.GetAsync(Arg.Any<int>(), Arg.Any<CancellationToken>())
.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<int>(), Arg.Any<CancellationToken>())
.ReturnsForAnyArgs(plannedTrajectory);
trajectoryFactRepositoryMock.GetAsync(Arg.Any<int>(), Arg.Any<CancellationToken>())
.ReturnsForAnyArgs(actualTrajectory);
trajectoryNnbRepositoryMock.GetAsync(Arg.Any<int>(), Arg.Any<CancellationToken>())
.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);
}
}

View File

@ -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<byte>());
private static readonly WellFinalDocumentDto wellFinalDocument = new()
{
IdCategory = idWellFinalDocCategory,
PermissionToUpload = true,
Publishers = new List<UserDto>
{
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<IUserRepository>();
private readonly IFileCategoryService fileCategoryServiceMock = Substitute.For<IFileCategoryService>();
private readonly ICrudRepository<NotificationCategoryDto> notificationCategoryRepositoryMock = Substitute.For<ICrudRepository<NotificationCategoryDto>>();
private readonly IFileRepository fileRepositoryMock = Substitute.For<IFileRepository>();
private readonly IWellFinalDocumentsRepository wellFinalDocumentsRepositoryMock = Substitute.For<IWellFinalDocumentsRepository>();
private readonly IWellService wellServiceMock = Substitute.For<IWellService>();
private readonly INotificationRepository notificationRepositoryMock = Substitute.For<INotificationRepository>();
private readonly INotificationTransportService notificationTransportServiceMock = Substitute.For<INotificationTransportService>();
private readonly IFileStorageRepository fileStorageRepositoryMock = Substitute.For<IFileStorageRepository>();
private readonly WellFinalDocumentsService wellFinalDocumentsService;
private readonly FileService fileService;
private readonly NotificationService notificationService;
public WellFinalDocumentsServiceTest()
{
wellFinalDocumentsRepositoryMock.GetByWellIdAsync(Arg.Any<int>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
.ReturnsForAnyArgs(wellCase);
wellFinalDocumentsRepositoryMock.GetCategoryAsync(Arg.Any<int>(), Arg.Any<int>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
.ReturnsForAnyArgs(wellFinalDocumentDB);
fileRepositoryMock.InsertAsync(Arg.Any<FileInfoDto>(), Arg.Any<CancellationToken>())
.ReturnsForAnyArgs(validInsertedFileId);
fileRepositoryMock.GetOrDefaultAsync(validInsertedFileId, Arg.Any<CancellationToken>())
.ReturnsForAnyArgs(new FileInfoDto { Id = validInsertedFileId });
userRepositoryMock.GetAllAsync(Arg.Any<CancellationToken>())
.ReturnsForAnyArgs(new[] { user });
userRepositoryMock.GetOrDefault(Arg.Any<int>())
.ReturnsForAnyArgs(user);
userRepositoryMock.GetOrDefaultAsync(Arg.Any<int>(), Arg.Any<CancellationToken>())
.ReturnsForAnyArgs(user);
userRepositoryMock.HasPermission(user.Id, editPublisherPermission)
.ReturnsForAnyArgs(true);
wellServiceMock.GetOrDefaultAsync(Arg.Any<int>(), Arg.Any<CancellationToken>())
.ReturnsForAnyArgs(well);
notificationCategoryRepositoryMock.GetOrDefaultAsync(Arg.Any<int>(),
Arg.Any<CancellationToken>())
.ReturnsForAnyArgs(notificationCategory);
fileCategoryServiceMock.GetOrDefaultAsync(idWellFinalDocCategory, Arg.Any<CancellationToken>())
.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);
}
}

View File

@ -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<IWellService>();
private readonly IWellOperationRepository wellOperationRepositoryMock = Substitute.For<IWellOperationRepository>();
private readonly ITelemetryDataCache<TelemetryDataSaubDto> telemetryDataCacheMock = Substitute.For<ITelemetryDataCache<TelemetryDataSaubDto>>();
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<WellRequest>(), Arg.Any<CancellationToken>())
.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<WellRequest>(), Arg.Any<CancellationToken>())
.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<WellRequest>(), Arg.Any<CancellationToken>())
.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<IEnumerable<int>>(), Arg.Any<CancellationToken>())
.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<WellRequest>(), Arg.Any<CancellationToken>())
.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<int>())
.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<WellRequest>(), Arg.Any<CancellationToken>())
.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<IEnumerable<int>>(), Arg.Any<CancellationToken>())
.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<int>())
.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);
}
}