Merge pull request '#29995514 Одновременный запуск интеграционных тестов' (#234) from feature/integration_tests into dev

Reviewed-on: http://test.digitaldrilling.ru:8080/DDrilling/AsbCloudServer/pulls/234
This commit is contained in:
Никита Фролов 2024-03-13 17:15:18 +05:00
commit 71d14c6fd8
14 changed files with 894 additions and 1019 deletions

View File

@ -4,15 +4,23 @@ using Xunit;
namespace AsbCloudWebApi.IntegrationTests; namespace AsbCloudWebApi.IntegrationTests;
public abstract class BaseIntegrationTest : IClassFixture<WebAppFactoryFixture> public abstract class BaseIntegrationTest : IClassFixture<WebAppFactoryFixture>,
IDisposable
{ {
protected readonly IServiceScope scope; protected readonly IServiceScope scope;
protected readonly IAsbCloudDbContext dbContext; protected readonly AsbCloudDbContext dbContext;
protected BaseIntegrationTest(WebAppFactoryFixture factory) protected BaseIntegrationTest(WebAppFactoryFixture factory)
{ {
scope = factory.Services.CreateScope(); scope = factory.Services.CreateScope();
dbContext = scope.ServiceProvider.GetRequiredService<IAsbCloudDbContext>();
dbContext = scope.ServiceProvider.GetRequiredService<AsbCloudDbContext>();
}
public void Dispose()
{
scope.Dispose();
dbContext.Dispose();
} }
} }

View File

@ -1,6 +1,5 @@
using System.Net; using System.Net;
using AsbCloudApp.Data; using AsbCloudApp.Data;
using AsbCloudDb.Model;
using AsbCloudWebApi.IntegrationTests.Clients; using AsbCloudWebApi.IntegrationTests.Clients;
using Mapster; using Mapster;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
@ -27,8 +26,6 @@ public class AdminDepositControllerTest : BaseIntegrationTest
: base(factory) : base(factory)
{ {
client = factory.GetAuthorizedHttpClient<IAdminDepositClient>(string.Empty); client = factory.GetAuthorizedHttpClient<IAdminDepositClient>(string.Empty);
dbContext.CleanupDbSet<Deposit>();
} }
[Fact] [Fact]
@ -130,11 +127,8 @@ public class AdminDepositControllerTest : BaseIntegrationTest
[Fact] [Fact]
public async Task GetOrDefault_returns_NoContent_for_IdDeposit() public async Task GetOrDefault_returns_NoContent_for_IdDeposit()
{ {
//arrange
const int idInvalid = 0;
//act //act
var responce = await client.GetOrDefaultAsync(idInvalid); var responce = await client.GetOrDefaultAsync(0);
//assert //assert
Assert.Equal(HttpStatusCode.NoContent, responce.StatusCode); Assert.Equal(HttpStatusCode.NoContent, responce.StatusCode);
@ -143,9 +137,6 @@ public class AdminDepositControllerTest : BaseIntegrationTest
[Fact] [Fact]
public async Task GetAll_returns_success() public async Task GetAll_returns_success()
{ {
//arrange
await client.InsertAsync(dto);
//act //act
var response = await client.GetAllAsync(); var response = await client.GetAllAsync();
@ -155,10 +146,6 @@ public class AdminDepositControllerTest : BaseIntegrationTest
var expectedCount = await dbContext.Deposits.CountAsync(); var expectedCount = await dbContext.Deposits.CountAsync();
Assert.Equal(expectedCount, response.Content.Count()); Assert.Equal(expectedCount, response.Content.Count());
var deposit = response.Content.First();
var excludeProps = new[] { nameof(DepositBaseDto.Id) };
MatchHelper.Match(dto, deposit, excludeProps);
} }
[Fact] [Fact]
@ -182,11 +169,8 @@ public class AdminDepositControllerTest : BaseIntegrationTest
[Fact] [Fact]
public async Task Delete_returns_NoContent_IdDeposit() public async Task Delete_returns_NoContent_IdDeposit()
{ {
//arrange
const int idInvalid = 0;
//act //act
var response = await client.DeleteAsync(idInvalid); var response = await client.DeleteAsync(0);
//assert //assert
Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); Assert.Equal(HttpStatusCode.NoContent, response.StatusCode);

View File

@ -15,6 +15,8 @@ namespace AsbCloudWebApi.IntegrationTests.Controllers.ProcessMapPlan;
public class ProcessMapPlanDrillingControllerTest: BaseIntegrationTest public class ProcessMapPlanDrillingControllerTest: BaseIntegrationTest
{ {
private const int IdWell = 1;
private readonly ProcessMapPlanDrillingDto dto = new (){ private readonly ProcessMapPlanDrillingDto dto = new (){
Id = 0, Id = 0,
Creation = new(), Creation = new(),
@ -22,7 +24,7 @@ public class ProcessMapPlanDrillingControllerTest: BaseIntegrationTest
IdState = 0, IdState = 0,
IdPrevious = null, IdPrevious = null,
IdWell = 1, IdWell = IdWell,
Section = "Кондуктор", Section = "Кондуктор",
IdWellSectionType = 3, IdWellSectionType = 3,
DepthStart = 0.5, DepthStart = 0.5,
@ -55,7 +57,7 @@ public class ProcessMapPlanDrillingControllerTest: BaseIntegrationTest
IdState = AsbCloudDb.Model.ChangeLogAbstract.IdStateActual, IdState = AsbCloudDb.Model.ChangeLogAbstract.IdStateActual,
IdPrevious = null, IdPrevious = null,
IdWell = 1, IdWell = IdWell,
IdWellSectionType = 1, IdWellSectionType = 1,
DepthStart = 0.5, DepthStart = 0.5,
DepthEnd = 1.5, DepthEnd = 1.5,
@ -149,20 +151,6 @@ public class ProcessMapPlanDrillingControllerTest: BaseIntegrationTest
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
} }
[Fact]
public async Task InsertRange_returns_BadRequest_for_IdWell()
{
//arrange
var badDto = dto.Adapt<ProcessMapPlanDrillingDto>();
badDto.IdWell = int.MaxValue;
//act
var response = await client.InsertRange(dto.IdWell, new[] { badDto });
//assert
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
}
[Fact] [Fact]
public async Task ClearAndInsertRange_returns_success() public async Task ClearAndInsertRange_returns_success()
{ {
@ -346,7 +334,6 @@ public class ProcessMapPlanDrillingControllerTest: BaseIntegrationTest
Assert.InRange(actual.Obsolete.Value, startTime, doneTime); Assert.InRange(actual.Obsolete.Value, startTime, doneTime);
} }
[Fact] [Fact]
public async Task GetDatesChange_returns_success() public async Task GetDatesChange_returns_success()
{ {
@ -358,7 +345,7 @@ public class ProcessMapPlanDrillingControllerTest: BaseIntegrationTest
dbset.Add(entity); dbset.Add(entity);
dbset.Add(entity2); dbset.Add(entity2);
dbContext.SaveChanges(); dbContext.SaveChanges();
var timezoneHours = Data.Defaults.Wells[0].Timezone.Hours; var timezoneHours = Defaults.Timezone.Hours;
var offset = TimeSpan.FromHours(timezoneHours); var offset = TimeSpan.FromHours(timezoneHours);
var dates = new[] { entity.Creation, entity2.Creation } var dates = new[] { entity.Creation, entity2.Creation }
.Select(d => d.ToOffset(offset)) .Select(d => d.ToOffset(offset))
@ -537,7 +524,7 @@ public class ProcessMapPlanDrillingControllerTest: BaseIntegrationTest
dbContext.SaveChanges(); dbContext.SaveChanges();
var timezoneHours = Data.Defaults.Wells[0].Timezone.Hours; var timezoneHours = Defaults.Timezone.Hours;
var offset = TimeSpan.FromHours(timezoneHours); var offset = TimeSpan.FromHours(timezoneHours);
var updateFrom = entity.Creation.ToOffset(offset).AddHours(0.5); var updateFrom = entity.Creation.ToOffset(offset).AddHours(0.5);
@ -571,10 +558,11 @@ public class ProcessMapPlanDrillingControllerTest: BaseIntegrationTest
//arrange //arrange
const string fileName = "ProcessMapPlanDrillingValid.xlsx"; const string fileName = "ProcessMapPlanDrillingValid.xlsx";
var stream = Assembly.GetExecutingAssembly().GetFileCopyStream(fileName); var stream = Assembly.GetExecutingAssembly().GetFileCopyStream(fileName);
var streamPart = new StreamPart(stream, fileName, "application/octet-stream"); var streamPart = new StreamPart(stream, fileName, "application/octet-stream");
//act //act
var response = await client.Parse(Defaults.Wells[0].Id, streamPart); var response = await client.Parse(IdWell, streamPart);
//assert //assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -590,7 +578,8 @@ public class ProcessMapPlanDrillingControllerTest: BaseIntegrationTest
Assert.True(row.IsValid); Assert.True(row.IsValid);
MatchHelper.Match(dto, dtoActual); var excludeProps = new[] { nameof(ProcessMapPlanDrillingDto.IdWell) };
MatchHelper.Match(dto, dtoActual, excludeProps);
} }
[Fact] [Fact]
@ -599,12 +588,12 @@ public class ProcessMapPlanDrillingControllerTest: BaseIntegrationTest
//arrange //arrange
const string fileName = "ProcessMapPlanDrillingInvalid.xlsx"; const string fileName = "ProcessMapPlanDrillingInvalid.xlsx";
var stream = Assembly.GetExecutingAssembly().GetFileCopyStream(fileName); var stream = Assembly.GetExecutingAssembly().GetFileCopyStream(fileName);
var streamPart = new StreamPart(stream, fileName, "application/octet-stream"); var streamPart = new StreamPart(stream, fileName, "application/octet-stream");
//act //act
var response = await client.Parse(Defaults.Wells[0].Id, streamPart); var response = await client.Parse(IdWell, streamPart);
//assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var parserResult = response.Content; var parserResult = response.Content;

View File

@ -2,146 +2,156 @@
using AsbCloudDb.Model; using AsbCloudDb.Model;
using AsbCloudDb.Model.ProcessMaps; using AsbCloudDb.Model.ProcessMaps;
using AsbCloudWebApi.IntegrationTests.Clients; using AsbCloudWebApi.IntegrationTests.Clients;
using Org.BouncyCastle.Asn1.Ocsp;
using System.Net; using System.Net;
using System.Net.Http.Headers; using AsbCloudWebApi.IntegrationTests.Data;
using Xunit; using Xunit;
namespace AsbCloudWebApi.IntegrationTests.Controllers.ProcessMapPlan; namespace AsbCloudWebApi.IntegrationTests.Controllers.ProcessMapPlan;
public class ProcessMapReportDrillingControllerTest : BaseIntegrationTest public class ProcessMapReportDrillingControllerTest : BaseIntegrationTest
{ {
private IProcessMapReportDrilling client;
private readonly WellSectionType wellSection = new WellSectionType() public ProcessMapReportDrillingControllerTest(WebAppFactoryFixture factory)
: base(factory)
{ {
Id = 1, dbContext.CleanupDbSet<DataSaubStat>();
Caption = "Секция 1", dbContext.CleanupDbSet<ProcessMapPlanDrilling>();
Order = 1 client = factory.GetAuthorizedHttpClient<IProcessMapReportDrilling>(string.Empty);
}
[Fact]
public async Task Get_rtk_report_by_default_request_returns_success()
{
//arrange
var well = dbContext.Wells.First();
var processMapPlanDrilling = CreateProcessMapPlanDrilling(well.Id);
dbContext.ProcessMapPlanDrilling.Add(processMapPlanDrilling);
var wellOperation = CreateWellOperation(well.Id);
dbContext.WellOperations.Add(wellOperation);
var dataSaubStats = CreateDataSaubStats(well.IdTelemetry!.Value, wellOperation.IdCategory);
dbContext.DataSaubStat.AddRange(dataSaubStats);
await dbContext.SaveChangesAsync();
//act
var request = new DataSaubStatRequest();
var response = await client.GetReportAsync(well.Id, request, CancellationToken.None);
//assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.NotNull(response.Content);
Assert.Equal(dataSaubStats.Count() - 1, response.Content.Count());
}
[Fact]
public async Task Get_rtk_report_by_parametrize_request_returns_success()
{
//arrange
var well = dbContext.Wells.First();
var processMapPlanDrilling = CreateProcessMapPlanDrilling(well.Id);
dbContext.ProcessMapPlanDrilling.Add(processMapPlanDrilling);
var wellOperation = CreateWellOperation(well.Id);
dbContext.WellOperations.Add(wellOperation);
var dataSaubStats = CreateDataSaubStats(well.IdTelemetry!.Value, wellOperation.IdCategory);
dbContext.DataSaubStat.AddRange(dataSaubStats);
await dbContext.SaveChangesAsync();
var request = new DataSaubStatRequest
{
DeltaAxialLoad = 5,
DeltaPressure = 15,
DeltaRotorTorque = 10
}; };
private readonly WellOperationCategory wellOperationCategory = new WellOperationCategory() //act
{ var response = await client.GetReportAsync(well.Id, request, CancellationToken.None);
Id = 1,
IdParent = null,
KeyValueName = "Name",
Name = "Name"
};
private readonly WellOperation wellOperation = new WellOperation() //assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.NotNull(response.Content);
Assert.Equal(1, response.Content.Count());
}
[Fact]
public async Task Get_rtk_report_returns_BadRequest()
{
//act
var request = new DataSaubStatRequest()
{
DeltaAxialLoad = 15,
DeltaPressure = 25,
DeltaRotorTorque = 20
};
var response = await client.GetReportAsync(0, request, CancellationToken.None);
//assert
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
}
[Fact]
public async Task Export_rtk_report_returns_success()
{
//arrange
var well = dbContext.Wells.First();
var processMapPlanDrilling = CreateProcessMapPlanDrilling(well.Id);
dbContext.ProcessMapPlanDrilling.Add(processMapPlanDrilling);
var wellOperation = CreateWellOperation(well.Id);
dbContext.WellOperations.Add(wellOperation);
var dataSaubStats = CreateDataSaubStats(well.IdTelemetry!.Value, wellOperation.IdCategory);
dbContext.DataSaubStat.AddRange(dataSaubStats);
await dbContext.SaveChangesAsync();
//act
var request = new DataSaubStatRequest();
var response = await client.ExportReportAsync(1, request, CancellationToken.None);
//assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal("application/octet-stream", response.ContentHeaders?.ContentType?.MediaType);
Assert.True(response.ContentHeaders?.ContentLength > 0);
}
private static WellOperation CreateWellOperation(int idWell) =>
new()
{ {
CategoryInfo = "CategoryInfo", CategoryInfo = "CategoryInfo",
Id = 10,
Comment = "Comment", Comment = "Comment",
DateStart = DateTimeOffset.UtcNow, DateStart = DateTimeOffset.UtcNow,
DepthEnd = 1, DepthEnd = 1,
DepthStart = 0.6, DepthStart = 0.6,
DurationHours = 10, DurationHours = 10,
IdCategory = 1, IdCategory = WellOperationCategory.IdSlide,
IdPlan = null, IdPlan = null,
IdType = 1, IdType = WellOperation.IdOperationTypeFact,
IdUser = 1, IdUser = 1,
IdWell = 1, IdWell = idWell,
IdWellSectionType = 1, IdWellSectionType = 1,
LastUpdateDate = DateTimeOffset.UtcNow LastUpdateDate = DateTimeOffset.UtcNow
}; };
private readonly List<DataSaubStat> dataSaubStats = new List<DataSaubStat>() private static ProcessMapPlanDrilling CreateProcessMapPlanDrilling(int idWell) =>
new()
{ {
new DataSaubStat()
{
AxialLoad = 0,
AxialLoadLimitMax = 10,
AxialLoadSp = 8,
BlockSpeedSp = 50.0,
DateEnd = DateTimeOffset.UtcNow.AddMinutes(40),
DateStart = DateTimeOffset.UtcNow.AddMinutes(30),
DepthEnd = 85.99299621582031,
DepthStart = 85.9260025024414,
EnabledSubsystems = 0,
Flow = 10,
HasOscillation = true,
Id = 1,
IdCategory = 1,
IdFeedRegulator = 0,
IdTelemetry = 1,
Pressure = 24,
PressureIdle = 0,
PressureSp = 40,
RotorSpeed = 11.3,
RotorTorque = 1,
RotorTorqueLimitMax = 26.5,
RotorTorqueSp = 5,
Speed = 80.3924560546875
},
new DataSaubStat()
{
AxialLoad = 2,
AxialLoadLimitMax = 10.0,
AxialLoadSp = 8,
BlockSpeedSp = 20,
DateEnd = DateTimeOffset.UtcNow.AddMinutes(30),
DateStart = DateTimeOffset.UtcNow.AddMinutes(20),
DepthEnd = 86.28099822998047,
DepthStart = 86.21900177001953,
EnabledSubsystems = 1,
Flow = 20,
HasOscillation = true,
Id = 2,
IdCategory = 1,
IdFeedRegulator = 1,
IdTelemetry = 1,
Pressure = 30,
PressureIdle = 20,
PressureSp = 40,
RotorSpeed = 11.251153300212916,
RotorTorque = 7,
RotorTorqueLimitMax = 26.5,
RotorTorqueSp = 9,
Speed = 74.395751953125
},
new DataSaubStat()
{
AxialLoad = 4,
AxialLoadLimitMax = 15.0,
AxialLoadSp = 8,
BlockSpeedSp = 110.0,
DateEnd = DateTimeOffset.UtcNow.AddMinutes(20),
DateStart = DateTimeOffset.UtcNow.AddMinutes(10),
DepthEnd = 106.7490005493164,
DepthStart = 106.47899627685547,
EnabledSubsystems = 1,
Flow = 30,
HasOscillation = true,
Id = 3,
IdCategory = 1,
IdFeedRegulator = 1,
IdTelemetry = 1,
Pressure = 36,
PressureIdle = 23.0,
PressureSp = 63.0,
RotorSpeed = 11.334207942999628,
RotorTorque = 14,
RotorTorqueLimitMax = 15.0,
RotorTorqueSp = 13,
Speed = 108.001708984375
}
};
private readonly ProcessMapPlanDrilling entity = new()
{
Id = 0,
IdAuthor = 1, IdAuthor = 1,
IdEditor = null, IdEditor = null,
Creation = DateTimeOffset.UtcNow, Creation = DateTimeOffset.UtcNow,
Obsolete = null, Obsolete = null,
IdState = AsbCloudDb.Model.ChangeLogAbstract.IdStateActual, IdState = ChangeLogAbstract.IdStateActual,
IdPrevious = null, IdPrevious = null,
IdWell = 1, IdWell = idWell,
IdWellSectionType = 1, IdWellSectionType = 1,
DepthStart = 0.5, DepthStart = 0.5,
DepthEnd = 1.5, DepthEnd = 1.5,
@ -163,153 +173,84 @@ public class ProcessMapReportDrillingControllerTest : BaseIntegrationTest
Comment = "это тестовая запись", Comment = "это тестовая запись",
}; };
private IProcessMapReportDrilling client; private static IEnumerable<DataSaubStat> CreateDataSaubStats(int idTelemetry,
int idCategory) =>
public ProcessMapReportDrillingControllerTest(WebAppFactoryFixture factory) : base(factory) new[]
{ {
client = factory.GetAuthorizedHttpClient<IProcessMapReportDrilling>(string.Empty); new DataSaubStat
{
AxialLoad = 0,
AxialLoadLimitMax = 10,
AxialLoadSp = 8,
BlockSpeedSp = 50.0,
DateEnd = DateTimeOffset.UtcNow.AddMinutes(40),
DateStart = DateTimeOffset.UtcNow.AddMinutes(30),
DepthEnd = 85.99299621582031,
DepthStart = 85.9260025024414,
EnabledSubsystems = 0,
Flow = 10,
IdCategory = idCategory,
HasOscillation = true,
IdFeedRegulator = 0,
IdTelemetry = idTelemetry,
Pressure = 24,
PressureIdle = 0,
PressureSp = 40,
RotorSpeed = 11.3,
RotorTorque = 1,
RotorTorqueLimitMax = 26.5,
RotorTorqueSp = 5,
Speed = 80.3924560546875
},
new DataSaubStat
{
AxialLoad = 2,
AxialLoadLimitMax = 10.0,
AxialLoadSp = 8,
BlockSpeedSp = 20,
DateEnd = DateTimeOffset.UtcNow.AddMinutes(30),
DateStart = DateTimeOffset.UtcNow.AddMinutes(20),
DepthEnd = 86.28099822998047,
DepthStart = 86.21900177001953,
EnabledSubsystems = 1,
Flow = 20,
HasOscillation = true,
IdCategory = idCategory,
IdFeedRegulator = 1,
IdTelemetry = idTelemetry,
Pressure = 30,
PressureIdle = 20,
PressureSp = 40,
RotorSpeed = 11.251153300212916,
RotorTorque = 7,
RotorTorqueLimitMax = 26.5,
RotorTorqueSp = 9,
Speed = 74.395751953125
},
new DataSaubStat
{
AxialLoad = 4,
AxialLoadLimitMax = 15.0,
AxialLoadSp = 8,
BlockSpeedSp = 110.0,
DateEnd = DateTimeOffset.UtcNow.AddMinutes(20),
DateStart = DateTimeOffset.UtcNow.AddMinutes(10),
DepthEnd = 106.7490005493164,
DepthStart = 106.47899627685547,
EnabledSubsystems = 1,
Flow = 30,
HasOscillation = true,
IdFeedRegulator = 1,
IdTelemetry = idTelemetry,
IdCategory = idCategory,
Pressure = 36,
PressureIdle = 23.0,
PressureSp = 63.0,
RotorSpeed = 11.334207942999628,
RotorTorque = 14,
RotorTorqueLimitMax = 15.0,
RotorTorqueSp = 13,
Speed = 108.001708984375
} }
[Fact]
public async Task Get_rtk_report_by_default_request_returns_success()
{
//arrange
dbContext.CleanupDbSet<ProcessMapPlanDrilling>();
var dbset = dbContext.Set<ProcessMapPlanDrilling>();
dbset.Add(entity);
entity.Id = 1;
dbset.Add(entity);
entity.Id = 2;
dbset.Add(entity);
var dbSetWellOperationCategory = dbContext.Set<WellOperationCategory>();
dbSetWellOperationCategory.Add(wellOperationCategory);
var dbSetWellOperation = dbContext.Set<WellOperation>();
dbSetWellOperation.Add(wellOperation);
var dbSetDataSaubStat = dbContext.Set<DataSaubStat>();
dbSetDataSaubStat.AddRange(dataSaubStats);
dbContext.SaveChanges();
//act
var request = new DataSaubStatRequest();
var response = await client.GetReportAsync(1, request, CancellationToken.None);
//assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.NotNull(response.Content);
Assert.Equal(dataSaubStats.Count() - 1, response.Content.Count());
}
[Fact]
public async Task Get_rtk_report_by_parametrize_request_returns_success()
{
//arrange
dbContext.CleanupDbSet<ProcessMapPlanDrilling>();
var dbset = dbContext.Set<ProcessMapPlanDrilling>();
dbset.Add(entity);
entity.Id = 1;
dbset.Add(entity);
entity.Id = 2;
dbset.Add(entity);
var dbSetWellOperationCategory = dbContext.Set<WellOperationCategory>();
dbSetWellOperationCategory.Add(wellOperationCategory);
var dbSetWellOperation = dbContext.Set<WellOperation>();
dbSetWellOperation.Add(wellOperation);
var dbSetDataSaubStat = dbContext.Set<DataSaubStat>();
dbSetDataSaubStat.AddRange(dataSaubStats);
dbContext.SaveChanges();
//act
var request = new DataSaubStatRequest()
{
DeltaAxialLoad = 5,
DeltaPressure = 15,
DeltaRotorTorque = 10
}; };
var response = await client.GetReportAsync(1, request, CancellationToken.None);
//assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.NotNull(response.Content);
Assert.Equal(1, response.Content.Count());
}
[Fact]
public async Task Get_rtk_report_returns_BadRequest()
{
//arrange
dbContext.CleanupDbSet<ProcessMapPlanDrilling>();
var dbset = dbContext.Set<ProcessMapPlanDrilling>();
dbset.Add(entity);
entity.Id = 1;
dbset.Add(entity);
entity.Id = 2;
dbset.Add(entity);
var dbSetWellOperationCategory = dbContext.Set<WellOperationCategory>();
dbSetWellOperationCategory.Add(wellOperationCategory);
var dbSetWellOperation = dbContext.Set<WellOperation>();
dbSetWellOperation.Add(wellOperation);
var dbSetDataSaubStat = dbContext.Set<DataSaubStat>();
dbSetDataSaubStat.AddRange(dataSaubStats);
dbContext.SaveChanges();
//act
var request = new DataSaubStatRequest()
{
DeltaAxialLoad = 15,
DeltaPressure = 25,
DeltaRotorTorque = 20
};
var response = await client.GetReportAsync(1, request, CancellationToken.None);
//assert
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
}
[Fact]
public async Task Export_rtk_report_returns_success()
{
//clear
dbContext.CleanupDbSet<ProcessMapPlanDrilling>();
//arrange
var dbset = dbContext.Set<ProcessMapPlanDrilling>();
dbset.Add(entity);
entity.Id = 1;
dbset.Add(entity);
entity.Id = 2;
dbset.Add(entity);
var dbSetWellOperationCategory = dbContext.Set<WellOperationCategory>();
dbSetWellOperationCategory.Add(wellOperationCategory);
var dbSetWellOperation = dbContext.Set<WellOperation>();
dbSetWellOperation.Add(wellOperation);
var dbSetDataSaubStat = dbContext.Set<DataSaubStat>();
dbSetDataSaubStat.AddRange(dataSaubStats);
dbContext.SaveChanges();
//act
var request = new DataSaubStatRequest();
var response = await client.ExportReportAsync(1, request, CancellationToken.None);
//assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal("application/octet-stream", response.ContentHeaders?.ContentType?.MediaType);
Assert.True(response.ContentHeaders?.ContentLength > 0);
}
} }

View File

@ -1,228 +1,228 @@
using AsbCloudApp.Data; // using AsbCloudApp.Data;
using AsbCloudDb.Model; // using AsbCloudDb.Model;
using AsbCloudInfrastructure; // using AsbCloudInfrastructure;
using AsbCloudWebApi.IntegrationTests.Clients; // using AsbCloudWebApi.IntegrationTests.Clients;
using Mapster; // using Mapster;
using Microsoft.EntityFrameworkCore; // using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking; // using Microsoft.EntityFrameworkCore.ChangeTracking;
using System.Net; // using System.Net;
using Xunit; // using Xunit;
//
namespace AsbCloudWebApi.IntegrationTests.Controllers // namespace AsbCloudWebApi.IntegrationTests.Controllers
{ // {
public abstract class CrudWellRelatedClient<TDto, TEntity> : BaseIntegrationTest // public abstract class CrudWellRelatedClient<TDto, TEntity> : BaseIntegrationTest
where TDto : AsbCloudApp.Data.IId, AsbCloudApp.Data.IWellRelated // where TDto : AsbCloudApp.Data.IId, AsbCloudApp.Data.IWellRelated
where TEntity : class, AsbCloudDb.Model.IId, AsbCloudDb.Model.IWellRelated // where TEntity : class, AsbCloudDb.Model.IId, AsbCloudDb.Model.IWellRelated
{ // {
public abstract IEnumerable<TDto> ValidDtos { get; } // public abstract IEnumerable<TDto> ValidDtos { get; }
public abstract IEnumerable<TDto> InvalidDtos { get; } // public abstract IEnumerable<TDto> InvalidDtos { get; }
public abstract IEnumerable<TDto> ForbiddenDtos { get; } // public abstract IEnumerable<TDto> ForbiddenDtos { get; }
protected List<string> ExcludeProps { get; set; } = new() { "Id" }; // protected List<string> ExcludeProps { get; set; } = new() { "Id" };
//
protected ICrudWellRelatedClient<TDto> client; // protected ICrudWellRelatedClient<TDto> client;
//
public CrudWellRelatedClient(WebAppFactoryFixture factory, string uriSuffix) // public CrudWellRelatedClient(WebAppFactoryFixture factory, string uriSuffix)
: base(factory) // : base(factory)
{ // {
client = factory.GetAuthorizedHttpClient<ICrudWellRelatedClient<TDto>>(uriSuffix); // client = factory.GetAuthorizedHttpClient<ICrudWellRelatedClient<TDto>>(uriSuffix);
} // }
//
protected async Task<DbSet<TEntity>> GetCleanDbSet() // protected async Task<DbSet<TEntity>> GetCleanDbSet()
{ // {
var dbset = dbContext.Set<TEntity>(); // var dbset = dbContext.Set<TEntity>();
dbset.RemoveRange(dbset); // dbset.RemoveRange(dbset);
await dbContext.SaveChangesAsync(CancellationToken.None); // await dbContext.SaveChangesAsync(CancellationToken.None);
return dbset; // return dbset;
} // }
//
[Fact] // [Fact]
public async Task Insert_returns_success_for_validDtos() // public async Task Insert_returns_success_for_validDtos()
{ // {
foreach (var validDto in ValidDtos) // foreach (var validDto in ValidDtos)
await Insert_returns_success(validDto); // await Insert_returns_success(validDto);
} // }
//
private async Task Insert_returns_success(TDto validDto) // private async Task Insert_returns_success(TDto validDto)
{ // {
var dbset = await GetCleanDbSet(); // var dbset = await GetCleanDbSet();
//
//act // //act
var response = await client.InsertAsync(validDto); // var response = await client.InsertAsync(validDto);
//
//assert // //assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); // Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.True(response.Content > 0); // Assert.True(response.Content > 0);
//
var entity = dbset.First(); // var entity = dbset.First();
var fromDbDto = Convert(entity); // var fromDbDto = Convert(entity);
MatchHelper.Match(validDto, fromDbDto, ExcludeProps); // MatchHelper.Match(validDto, fromDbDto, ExcludeProps);
} // }
//
[Fact] // [Fact]
public async Task Insert_returns_badRequest_for_invalidDtos() // public async Task Insert_returns_badRequest_for_invalidDtos()
{ // {
foreach (var inValidDto in InvalidDtos) // foreach (var inValidDto in InvalidDtos)
await Insert_returns_badRequest(inValidDto); // await Insert_returns_badRequest(inValidDto);
} // }
//
private async Task Insert_returns_badRequest(TDto invalidDto) // private async Task Insert_returns_badRequest(TDto invalidDto)
{ // {
await GetCleanDbSet(); // await GetCleanDbSet();
//
//act // //act
var response = await client.InsertAsync(invalidDto); // var response = await client.InsertAsync(invalidDto);
//
//assert // //assert
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); // Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
} // }
//
[Fact] // [Fact]
public async Task Insert_returns_forbidden_for_forbiddenDtos() // public async Task Insert_returns_forbidden_for_forbiddenDtos()
{ // {
foreach (var forbiddenDto in ForbiddenDtos) // foreach (var forbiddenDto in ForbiddenDtos)
await Insert_returns_forbidden(forbiddenDto); // await Insert_returns_forbidden(forbiddenDto);
} // }
//
private async Task Insert_returns_forbidden(TDto forbiddenDto) // private async Task Insert_returns_forbidden(TDto forbiddenDto)
{ // {
await GetCleanDbSet(); // await GetCleanDbSet();
//
//act // //act
var response = await client.InsertAsync(forbiddenDto); // var response = await client.InsertAsync(forbiddenDto);
//
//assert // //assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); // Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
} // }
//
[Fact] // [Fact]
public async Task GetAllAsync_returns_data() // public async Task GetAllAsync_returns_data()
{ // {
//arrange // //arrange
var dbset = await GetCleanDbSet(); // var dbset = await GetCleanDbSet();
var entries = new List<(EntityEntry<TEntity>, TDto)>(); // var entries = new List<(EntityEntry<TEntity>, TDto)>();
//
foreach (var dto in ValidDtos) // foreach (var dto in ValidDtos)
{ // {
var entity = Convert(dto); // var entity = Convert(dto);
entity.Id = 0; // entity.Id = 0;
var entry = dbset.Add(entity); // var entry = dbset.Add(entity);
entries.Add((entry, dto)); // entries.Add((entry, dto));
} // }
dbContext.SaveChanges(); // dbContext.SaveChanges();
//
//act // //act
var response = await client.GetAllAsync(); // var response = await client.GetAllAsync();
//
//assert // //assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); // Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.NotNull(response.Content); // Assert.NotNull(response.Content);
Assert.Equal(entries.Count, response.Content.Count()); // Assert.Equal(entries.Count, response.Content.Count());
//
foreach (var item in response.Content) // foreach (var item in response.Content)
{ // {
var entry = entries.First(e => e.Item1.Entity.Id == item.Id); // var entry = entries.First(e => e.Item1.Entity.Id == item.Id);
MatchHelper.Match(entry.Item2, item, ExcludeProps); // MatchHelper.Match(entry.Item2, item, ExcludeProps);
} // }
} // }
//
protected virtual TDto Convert(TEntity entity) // protected virtual TDto Convert(TEntity entity)
{ // {
var dto = entity.Adapt<TDto>(); // var dto = entity.Adapt<TDto>();
return dto; // return dto;
} // }
//
protected virtual TEntity Convert(TDto dto) // protected virtual TEntity Convert(TDto dto)
{ // {
var entity = dto.Adapt<TEntity>(); // var entity = dto.Adapt<TEntity>();
return entity; // return entity;
} // }
} // }
//
public class ScheduleControllerTest : CrudWellRelatedClient<ScheduleDto, Schedule> // public class ScheduleControllerTest : CrudWellRelatedClient<ScheduleDto, Schedule>
{ // {
static Driller driller = Data.Defaults.Drillers.First(); // static Driller driller = Data.Defaults.Drillers.First();
static DrillerDto drillerDto = driller.Adapt<DrillerDto>(); // static DrillerDto drillerDto = driller.Adapt<DrillerDto>();
//
static Well well = Data.Defaults.Wells.First(); // static Well well = Data.Defaults.Wells.First();
//
public override IEnumerable<ScheduleDto> ValidDtos { get; } = new ScheduleDto[] // public override IEnumerable<ScheduleDto> ValidDtos { get; } = new ScheduleDto[]
{ // {
new() { // new() {
Id = 1, // Id = 1,
IdWell = well.Id, // IdWell = well.Id,
Driller = drillerDto, // Driller = drillerDto,
IdDriller = driller.Id, // IdDriller = driller.Id,
DrillStart = new DateTime(2024, 1, 1, 0, 0, 0, DateTimeKind.Unspecified), // DrillStart = new DateTime(2024, 1, 1, 0, 0, 0, DateTimeKind.Unspecified),
DrillEnd = new DateTime(2024, 1, 2, 0, 0, 0, DateTimeKind.Unspecified), // DrillEnd = new DateTime(2024, 1, 2, 0, 0, 0, DateTimeKind.Unspecified),
ShiftStart = new TimeDto(8, 0, 0), // ShiftStart = new TimeDto(8, 0, 0),
ShiftEnd = new TimeDto(20, 0, 0), // ShiftEnd = new TimeDto(20, 0, 0),
}, // },
new() { // new() {
Id = 1, // Id = 1,
IdWell = well.Id, // IdWell = well.Id,
Driller = drillerDto, // Driller = drillerDto,
IdDriller = driller.Id, // IdDriller = driller.Id,
DrillStart = new DateTime(2024, 1, 1, 0, 0, 0, DateTimeKind.Unspecified), // DrillStart = new DateTime(2024, 1, 1, 0, 0, 0, DateTimeKind.Unspecified),
DrillEnd = new DateTime(2024, 1, 2, 0, 0, 0, DateTimeKind.Unspecified), // DrillEnd = new DateTime(2024, 1, 2, 0, 0, 0, DateTimeKind.Unspecified),
ShiftStart = new TimeDto(20, 0, 0), // ShiftStart = new TimeDto(20, 0, 0),
ShiftEnd = new TimeDto(8, 0, 0), // ShiftEnd = new TimeDto(8, 0, 0),
} // }
}; // };
//
public override IEnumerable<ScheduleDto> InvalidDtos { get; } = new ScheduleDto[] // public override IEnumerable<ScheduleDto> InvalidDtos { get; } = new ScheduleDto[]
{ // {
new() { // new() {
IdWell = well.Id, // IdWell = well.Id,
Driller = drillerDto, // Driller = drillerDto,
IdDriller = driller.Id, // IdDriller = driller.Id,
DrillStart = new DateTime(2024, 1, 1, 0, 0, 0, DateTimeKind.Unspecified), // DrillStart = new DateTime(2024, 1, 1, 0, 0, 0, DateTimeKind.Unspecified),
DrillEnd = new DateTime(2022, 1, 2, 0, 0, 0, DateTimeKind.Unspecified), // DrillEnd = new DateTime(2022, 1, 2, 0, 0, 0, DateTimeKind.Unspecified),
ShiftStart = new TimeDto(8, 0, 0), // ShiftStart = new TimeDto(8, 0, 0),
ShiftEnd = new TimeDto(20, 0, 0), // ShiftEnd = new TimeDto(20, 0, 0),
}, // },
new() { // new() {
IdWell = well.Id, // IdWell = well.Id,
Driller = drillerDto, // Driller = drillerDto,
IdDriller = int.MaxValue - 1, // IdDriller = int.MaxValue - 1,
DrillStart = new DateTime(2024, 1, 1, 0, 0, 0, DateTimeKind.Unspecified), // DrillStart = new DateTime(2024, 1, 1, 0, 0, 0, DateTimeKind.Unspecified),
DrillEnd = new DateTime(2024, 1, 2, 0, 0, 0, DateTimeKind.Unspecified), // DrillEnd = new DateTime(2024, 1, 2, 0, 0, 0, DateTimeKind.Unspecified),
ShiftStart = new TimeDto(8, 0, 0), // ShiftStart = new TimeDto(8, 0, 0),
ShiftEnd = new TimeDto(20, 0, 0), // ShiftEnd = new TimeDto(20, 0, 0),
} // }
}; // };
//
public override IEnumerable<ScheduleDto> ForbiddenDtos { get; } = new ScheduleDto[] { // public override IEnumerable<ScheduleDto> ForbiddenDtos { get; } = new ScheduleDto[] {
new() { // new() {
IdWell = int.MaxValue - 1, // IdWell = int.MaxValue - 1,
Driller = drillerDto, // Driller = drillerDto,
IdDriller = driller.Id, // IdDriller = driller.Id,
DrillStart = new DateTime(2024, 1, 1, 0, 0, 0, DateTimeKind.Unspecified), // DrillStart = new DateTime(2024, 1, 1, 0, 0, 0, DateTimeKind.Unspecified),
DrillEnd = new DateTime(2022, 1, 2, 0, 0, 0, DateTimeKind.Unspecified), // DrillEnd = new DateTime(2022, 1, 2, 0, 0, 0, DateTimeKind.Unspecified),
ShiftStart = new TimeDto(8, 0, 0), // ShiftStart = new TimeDto(8, 0, 0),
ShiftEnd = new TimeDto(20, 0, 0), // ShiftEnd = new TimeDto(20, 0, 0),
} // }
}; // };
//
public ScheduleControllerTest(WebAppFactoryFixture factory) // public ScheduleControllerTest(WebAppFactoryFixture factory)
: base(factory, "api/schedule") // : base(factory, "api/schedule")
{ // {
ExcludeProps.Add(nameof(ScheduleDto.Driller)); // ExcludeProps.Add(nameof(ScheduleDto.Driller));
} // }
//
protected override ScheduleDto Convert(Schedule entity) // protected override ScheduleDto Convert(Schedule entity)
{ // {
var dto = base.Convert(entity); // var dto = base.Convert(entity);
dto.DrillStart = entity.DrillStart.ToRemoteDateTime(well.Timezone.Hours); // dto.DrillStart = entity.DrillStart.ToRemoteDateTime(well.Timezone.Hours);
dto.DrillEnd = entity.DrillEnd.ToRemoteDateTime(well.Timezone.Hours); // dto.DrillEnd = entity.DrillEnd.ToRemoteDateTime(well.Timezone.Hours);
return dto; // return dto;
} // }
//
protected override Schedule Convert(ScheduleDto dto) // protected override Schedule Convert(ScheduleDto dto)
{ // {
var entity = base.Convert(dto); // var entity = base.Convert(dto);
entity.DrillStart = dto.DrillStart.FromTimeZoneOffsetHours(well.Timezone.Hours); // entity.DrillStart = dto.DrillStart.FromTimeZoneOffsetHours(well.Timezone.Hours);
entity.DrillEnd = dto.DrillEnd.FromTimeZoneOffsetHours(well.Timezone.Hours); // entity.DrillEnd = dto.DrillEnd.FromTimeZoneOffsetHours(well.Timezone.Hours);
return entity; // return entity;
} // }
} // }
} // }

View File

@ -2,77 +2,38 @@ using AsbCloudApp.Data;
using AsbCloudApp.Requests; using AsbCloudApp.Requests;
using AsbCloudDb.Model; using AsbCloudDb.Model;
using AsbCloudWebApi.IntegrationTests.Clients; using AsbCloudWebApi.IntegrationTests.Clients;
using Microsoft.EntityFrameworkCore;
using Xunit; using Xunit;
namespace AsbCloudWebApi.IntegrationTests.Controllers; namespace AsbCloudWebApi.IntegrationTests.Controllers;
public class SlipsStatControllerTest : BaseIntegrationTest public class SlipsStatControllerTest : BaseIntegrationTest
{ {
private static readonly Schedule schedule = new()
{
Id = 0,
IdDriller = Data.Defaults.Drillers[0].Id,
IdWell = Data.Defaults.Wells[0].Id,
ShiftStart = new TimeOnly(8, 0, 0),
ShiftEnd = new TimeOnly(20, 0, 0),
DrillStart = new DateTimeOffset(new DateTime(2024, 1, 1, 0, 0, 0, DateTimeKind.Utc)),
DrillEnd = new DateTimeOffset(new DateTime(2024, 2, 1, 0, 0, 0, DateTimeKind.Utc))
};
private static readonly DetectedOperation detectedOperation = new()
{
Id = 0,
IdTelemetry = Data.Defaults.Telemetries[0].Id,
IdCategory = WellOperationCategory.IdSlipsTime,
DateStart = new DateTimeOffset(new DateTime(2024, 1, 23, 15, 0, 0, 0, DateTimeKind.Utc)),
DateEnd = new DateTimeOffset(new DateTime(2024, 1, 23, 15, 2, 0, 0, DateTimeKind.Utc)),
ExtraData = new Dictionary<string, object>
{
{ "test", 5 }
}
};
private static readonly WellOperation factWellOperation = new()
{
Id = 0,
IdWell = Data.Defaults.Wells[0].Id,
IdWellSectionType = 1,
IdCategory = WellOperationCategory.IdRotor,
IdType = WellOperation.IdOperationTypeFact,
DepthStart = 0,
DepthEnd = 100,
LastUpdateDate = DateTimeOffset.UtcNow,
DateStart = new DateTimeOffset(new DateTime(2024, 1, 15, 15, 0, 0, DateTimeKind.Utc)),
DurationHours = 1
};
private readonly ISlipsTimeClient client; private readonly ISlipsTimeClient client;
public SlipsStatControllerTest(WebAppFactoryFixture factory) public SlipsStatControllerTest(WebAppFactoryFixture factory)
: base(factory) : base(factory)
{ {
var schedules = dbContext.Set<Schedule>();
var detectedOperations = dbContext.Set<DetectedOperation>();
var wellOperations = dbContext.Set<WellOperation>();
schedules.RemoveRange(schedules);
detectedOperations.RemoveRange(detectedOperations);
wellOperations.RemoveRange(wellOperations);
dbContext.SaveChanges();
schedules.Add(schedule);
detectedOperations.Add(detectedOperation);
wellOperations.Add(factWellOperation);
dbContext.SaveChanges();
client = factory.GetAuthorizedHttpClient<ISlipsTimeClient>(string.Empty); client = factory.GetAuthorizedHttpClient<ISlipsTimeClient>(string.Empty);
dbContext.CleanupDbSet<Schedule>();
dbContext.CleanupDbSet<WellOperation>();
dbContext.CleanupDbSet<DetectedOperation>();
} }
[Fact] [Fact]
public async Task GetAll_returns_success() public async Task GetAll_returns_success()
{ {
//arrange //arrange
var well = dbContext.Wells.First();
var schedule = CreateScheduleAsync(well.Id);
var factWellOperation = CreateFactWellOperation(well.Id);
var detectedOperation = CreateDetectedOperation(well.IdTelemetry!.Value);
dbContext.Schedule.Add(schedule);
dbContext.WellOperations.Add(factWellOperation);
dbContext.DetectedOperations.Add(detectedOperation);
await dbContext.SaveChangesAsync();
var request = new OperationStatRequest var request = new OperationStatRequest
{ {
DateStartUTC = schedule.DrillStart.DateTime, DateStartUTC = schedule.DrillStart.DateTime,
@ -83,7 +44,7 @@ public class SlipsStatControllerTest : BaseIntegrationTest
var dtoExpected = new SlipsStatDto var dtoExpected = new SlipsStatDto
{ {
DrillerName = $"{Data.Defaults.Drillers[0].Surname} {Data.Defaults.Drillers[0].Name} {Data.Defaults.Drillers[0].Patronymic}", DrillerName = $"{schedule.Driller.Surname} {schedule.Driller.Name} {schedule.Driller.Patronymic}",
WellCount = 1, WellCount = 1,
SectionCaption = "Пилотный ствол", SectionCaption = "Пилотный ствол",
SlipsCount = 1, SlipsCount = 1,
@ -101,4 +62,46 @@ public class SlipsStatControllerTest : BaseIntegrationTest
var slipsStat = response.Content.First(); var slipsStat = response.Content.First();
MatchHelper.Match(dtoExpected, slipsStat); MatchHelper.Match(dtoExpected, slipsStat);
} }
private static Schedule CreateScheduleAsync(int idWell) => new()
{
IdWell = idWell,
ShiftStart = new TimeOnly(8, 0, 0),
ShiftEnd = new TimeOnly(20, 0, 0),
DrillStart = new DateTimeOffset(new DateTime(2024, 1, 1, 0, 0, 0, DateTimeKind.Utc)),
DrillEnd = new DateTimeOffset(new DateTime(2024, 2, 1, 0, 0, 0, DateTimeKind.Utc)),
Driller = new Driller
{
Name = "TestName",
Surname = "TestSurname",
Patronymic = "TestPatronymic"
}
};
private static WellOperation CreateFactWellOperation(int idWell) =>
new()
{
IdWell = idWell,
IdWellSectionType = 1,
IdCategory = WellOperationCategory.IdRotor,
IdType = WellOperation.IdOperationTypeFact,
DepthStart = 0,
DepthEnd = 100,
LastUpdateDate = DateTimeOffset.UtcNow,
DateStart = new DateTimeOffset(new DateTime(2024, 1, 15, 15, 0, 0, DateTimeKind.Utc)),
DurationHours = 1
};
private static DetectedOperation CreateDetectedOperation(int idTelemetry) =>
new()
{
IdTelemetry = idTelemetry,
IdCategory = WellOperationCategory.IdSlipsTime,
DateStart = new DateTimeOffset(new DateTime(2024, 1, 23, 15, 0, 0, 0, DateTimeKind.Utc)),
DateEnd = new DateTimeOffset(new DateTime(2024, 1, 23, 15, 2, 0, 0, DateTimeKind.Utc)),
ExtraData = new Dictionary<string, object>
{
{ "test", 5 }
}
};
} }

View File

@ -5,6 +5,8 @@ using System.Net;
using System.Reflection; using System.Reflection;
using AsbCloudApp.Requests; using AsbCloudApp.Requests;
using AsbCloudWebApi.IntegrationTests.Data; using AsbCloudWebApi.IntegrationTests.Data;
using Mapster;
using Microsoft.EntityFrameworkCore;
using Refit; using Refit;
using Xunit; using Xunit;
@ -12,39 +14,14 @@ namespace AsbCloudWebApi.IntegrationTests.Controllers;
public class WellOperationControllerTest : BaseIntegrationTest public class WellOperationControllerTest : BaseIntegrationTest
{ {
private static int idWell = 1;
private readonly WellOperationDto[] dtos = new WellOperationDto[]
{
new()
{
IdWell = 1,
IdWellSectionType = 1,
WellSectionTypeName = "Пилотный ствол",
IdCategory = 5000,
IdPlan = null,
CategoryName = "Разборка КНБК",
IdParentCategory = 4000,
CategoryInfo = "1",
IdType = 0,
DepthStart = 10.0,
DepthEnd = 20.0,
Day = 0.0,
NptHours = 0.0,
DateStart = new DateTimeOffset(new DateTime(2023, 1, 10), TimeSpan.FromHours(Defaults.Wells[0].Timezone.Hours)),
DurationHours = 1.0,
Comment = "1",
IdUser = 1,
UserName = null,
}
};
private IWellOperationClient client; private IWellOperationClient client;
public WellOperationControllerTest(WebAppFactoryFixture factory) public WellOperationControllerTest(WebAppFactoryFixture factory)
: base(factory) : base(factory)
{ {
client = factory.GetAuthorizedHttpClient<IWellOperationClient>(string.Empty); client = factory.GetAuthorizedHttpClient<IWellOperationClient>(string.Empty);
dbContext.CleanupDbSet<WellOperation>();
} }
/// <summary> /// <summary>
@ -54,9 +31,13 @@ public class WellOperationControllerTest : BaseIntegrationTest
[Fact] [Fact]
public async Task InsertRange_returns_success() public async Task InsertRange_returns_success()
{ {
dbContext.CleanupDbSet<WellOperation>(); //arrange
var well = await dbContext.Wells.FirstAsync();
var entity = CreateWellOperation(well.Id);
var dtos = new[] { entity.Adapt<WellOperationDto>() };
//act //act
var response = await client.InsertRangeAsync(idWell, 1, false, dtos); var response = await client.InsertRangeAsync(well.Id, 1, false, dtos);
//assert //assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -69,8 +50,13 @@ public class WellOperationControllerTest : BaseIntegrationTest
[Fact] [Fact]
public async Task InsertRangeWithDeleteBefore_returns_success() public async Task InsertRangeWithDeleteBefore_returns_success()
{ {
//arrange
var well = await dbContext.Wells.FirstAsync();
var entity = CreateWellOperation(well.Id);
var dtos = new[] { entity.Adapt<WellOperationDto>() };
//act //act
var response = await client.InsertRangeAsync(idWell, 1, true, dtos); var response = await client.InsertRangeAsync(well.Id, 1, true, dtos);
//assert //assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -83,9 +69,16 @@ public class WellOperationControllerTest : BaseIntegrationTest
[Fact] [Fact]
public async Task UpdateAsync_returns_success() public async Task UpdateAsync_returns_success()
{ {
//arrange
var well = await dbContext.Wells.FirstAsync();
var entity = CreateWellOperation(well.Id);
dbContext.WellOperations.Add(entity);
await dbContext.SaveChangesAsync();
var dto = entity.Adapt<WellOperationDto>();
//act //act
var dto = dtos.FirstOrDefault()!; var response = await client.UpdateAsync(well.Id, entity.Id, dto, CancellationToken.None);
var response = await client.UpdateAsync(idWell, 1, dto, CancellationToken.None);
//assert //assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -99,8 +92,14 @@ public class WellOperationControllerTest : BaseIntegrationTest
public async Task GetPageOperationsPlanAsync_returns_success() public async Task GetPageOperationsPlanAsync_returns_success()
{ {
//arrange //arrange
dbContext.CleanupDbSet<WellOperation>(); var well = await dbContext.Wells.FirstAsync();
await client.InsertRangeAsync(idWell, WellOperation.IdOperationTypePlan, false, dtos); var entity = CreateWellOperation(well.Id);
dbContext.WellOperations.Add(entity);
await dbContext.SaveChangesAsync();
var dto = entity.Adapt<WellOperationDto>();
var timezoneOffset = TimeSpan.FromHours(well.Timezone.Hours);
dto.DateStart = dto.DateStart.ToOffset(timezoneOffset);
var request = new WellOperationRequestBase var request = new WellOperationRequestBase
{ {
@ -108,49 +107,59 @@ public class WellOperationControllerTest : BaseIntegrationTest
}; };
//act //act
var response = await client.GetPageOperationsPlanAsync(idWell, request, CancellationToken.None); var response = await client.GetPageOperationsPlanAsync(well.Id, request, CancellationToken.None);
//assert //assert
Assert.NotNull(response.Content); Assert.NotNull(response.Content);
Assert.Single(response.Content.Items); Assert.Single(response.Content.Items);
var dto = dtos[0]; var actualDto = response.Content.Items.First();
var wellOperation = response.Content.Items.First();
var excludeProps = new[] { nameof(WellOperationDto.Id) }; var excludeProps = new[]
MatchHelper.Match(dto, wellOperation, excludeProps); {
nameof(WellOperationDto.LastUpdateDate)
};
MatchHelper.Match(dto, actualDto, excludeProps);
} }
[Fact] [Fact]
public async Task ImportPlanDefaultExcelFileAsync_returns_success() public async Task ImportPlanDefaultExcelFileAsync_returns_success()
{ {
//arrange //arrange
//TODO: вынести в метод расширения. Сделать когда доберёмся до рефакторинга операций по скважине var stream = Assembly.GetExecutingAssembly().GetFileCopyStream("WellOperationsPlan.xlsx");
var resourceName = Assembly.GetExecutingAssembly()
.GetManifestResourceNames()
.FirstOrDefault(n => n.EndsWith("WellOperationsPlan.xlsx"));
if (string.IsNullOrWhiteSpace(resourceName))
throw new ArgumentNullException(nameof(resourceName));
var stream = Assembly.GetExecutingAssembly()
.GetManifestResourceStream(resourceName);
if (stream is null)
throw new ArgumentNullException(nameof(stream));
var memoryStream = new MemoryStream(); var memoryStream = new MemoryStream();
stream.CopyTo(memoryStream); await stream.CopyToAsync(memoryStream);
memoryStream.Position = 0; memoryStream.Position = 0;
var well = await dbContext.Wells.FirstAsync();
//act //act
var streamPart = new StreamPart(memoryStream, "WellOperations.xlsx", "application/octet-stream"); var streamPart = new StreamPart(memoryStream, "WellOperations.xlsx", "application/octet-stream");
var response = await client.ImportPlanDefaultExcelFileAsync(idWell, new[] { streamPart }, CancellationToken.None); var response = await client.ImportPlanDefaultExcelFileAsync(well.Id, new[] { streamPart }, CancellationToken.None);
//assert //assert
Assert.NotNull(response.Content); Assert.NotNull(response.Content);
Assert.Equal(4, response.Content.Count()); Assert.Equal(4, response.Content.Count());
Assert.True(response.Content.All(w => Math.Abs(w.DateStart.Offset.Hours - Defaults.Wells[0].Timezone.Hours) < 0.1)); Assert.True(response.Content.All(w => Math.Abs(w.DateStart.Offset.Hours - Defaults.Timezone.Hours) < 0.1));
} }
private static WellOperation CreateWellOperation(int idWell) =>
new()
{
IdWell = idWell,
IdWellSectionType = 2,
LastUpdateDate = DateTimeOffset.UtcNow,
IdCategory = 5000,
IdPlan = null,
CategoryInfo = "1",
IdType = 0,
DepthStart = 10.0,
DepthEnd = 20.0,
DateStart = new DateTimeOffset(new DateTime(2023, 1, 10), TimeSpan.FromHours(Defaults.Timezone.Hours)).ToUniversalTime(),
DurationHours = 1.0,
Comment = "1",
IdUser = 1
};
} }

View File

@ -2,110 +2,55 @@
namespace AsbCloudWebApi.IntegrationTests.Data namespace AsbCloudWebApi.IntegrationTests.Data
{ {
[System.Diagnostics.CodeAnalysis.SuppressMessage("Usage", "CA2211:Поля, не являющиеся константами, не должны быть видимыми", Justification = "<Ожидание>")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Usage", "CA2211:Поля, не являющиеся константами, не должны быть видимыми",
Justification = "<Ожидание>")]
public static class Defaults public static class Defaults
{ {
public static Driller[] Drillers = new Driller[] public static SimpleTimezone Timezone => new()
{ {
new() Hours = 1
{
Id = 1,
Name = "test1",
Surname = "test1",
Patronymic = "test1"
},
new()
{
Id = 2,
Name = "test2",
Surname = "test2",
Patronymic = "test2"
}
}; };
public static WellOperation[] WellOperations = new WellOperation[] public static Deposit[] Deposits => new Deposit[]
{ {
new() new()
{ {
Id = 1,
IdWell = 1,
IdType = 1,
DateStart = DateTimeOffset.UtcNow.AddDays(-1),
CategoryInfo = "1",
Comment = "1",
DepthEnd = 20,
DepthStart = 10,
DurationHours = 1,
IdCategory = 5000,
IdPlan = null,
IdUser = 1,
IdWellSectionType = 1,
LastUpdateDate = DateTimeOffset.UtcNow
}
};
public static Deposit[] Deposits = new Deposit[] {
new()
{
Id = 1,
Caption = "Deposit1", Caption = "Deposit1",
Latitude = 10, Latitude = 10,
Longitude = 20, Longitude = 20,
Timezone = GetTimezone() Timezone = Timezone,
} Clusters = new[]
}; {
new Cluster
public static Cluster[] Clusters = new Cluster[] {
new()
{ {
Id = 1,
IdDeposit = Deposits[0].Id,
Caption = "Cluster1", Caption = "Cluster1",
Latitude = 10, Latitude = 10,
Longitude = 20, Longitude = 20,
Timezone = GetTimezone() Timezone = Timezone,
} Wells = new[]
};
public static Telemetry[] Telemetries = new Telemetry[]
{ {
new() new Well
{ {
Id = 1,
RemoteUid = "555-555-555",
TimeZone = GetTimezone()
}
};
public static Well[] Wells = new Well[] {
new()
{
Id = 1,
IdCluster = Clusters[0].Id,
IdWellType = 1, IdWellType = 1,
IdState = 1, IdState = 1,
Caption = "Well1", Caption = "Well1",
Latitude = 10, Latitude = 10,
Longitude = 20, Longitude = 20,
IdTelemetry = Telemetries[0].Id, Timezone = Timezone,
Timezone = GetTimezone() Telemetry = new Telemetry
{
RemoteUid = "555-555-555",
TimeZone = Timezone
},
RelationCompaniesWells = new RelationCompanyWell[]
{
new() { IdCompany = 1 },
},
}
}
}
}
} }
};
public static RelationCompanyWell[] RelationsCompanyWell = new RelationCompanyWell[]
{
new() { IdCompany = 1, IdWell = Wells[0].Id },
};
public static RelationUserUserRole[] RelationsUserUserRole = new RelationUserUserRole[]
{
new(){ IdUserRole= 1, IdUser = 1}
};
private static SimpleTimezone GetTimezone() =>
new ()
{
Hours = 1
}; };
} }
} }

View File

@ -0,0 +1,15 @@
namespace AsbCloudWebApi.IntegrationTests;
public class DbConnection
{
public string Host { get; set; } = null!;
public int Port { get; set; }
public string Username { get; set; } = null!;
public string Password { get; set; } = null!;
public string GetConnectionString() =>
$"Host={Host};Database={Guid.NewGuid()};Port={Port};Username={Username};Password={Password};Persist Security Info=True;Include Error Detail=True";
}

View File

@ -2,6 +2,7 @@
using AsbCloudApp.Repositories; using AsbCloudApp.Repositories;
using AsbCloudDb.Model; using AsbCloudDb.Model;
using Mapster; using Mapster;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Xunit; using Xunit;
@ -9,15 +10,75 @@ namespace AsbCloudWebApi.IntegrationTests.Repository;
public class DataSaubStatRepositoryTest : BaseIntegrationTest public class DataSaubStatRepositoryTest : BaseIntegrationTest
{ {
private static readonly TimeSpan timeSpan = TimeSpan.FromHours(1); private readonly IDataSaubStatRepository dataSaubStatRepository;
private static readonly DataSaubStatDto[] statDtos = new DataSaubStatDto[2] public DataSaubStatRepositoryTest(WebAppFactoryFixture factory)
: base(factory)
{
dataSaubStatRepository = scope.ServiceProvider.GetRequiredService<IDataSaubStatRepository>();
dbContext.CleanupDbSet<DataSaubStat>();
}
[Fact]
public async Task GetLastDatesAsync_returns_success()
{
//arrange
var telemetry = await dbContext.Telemetries.FirstAsync();
var timeZoneOffset = TimeSpan.FromHours(telemetry.TimeZone.Hours);
var dataSaubStat = CreateDataSaubStat(telemetry.Id, timeZoneOffset);
dbContext.AddRange(dataSaubStat);
await dbContext.SaveChangesAsync();
var telemetryIds = dataSaubStat.Select(stat => stat.IdTelemetry).ToArray();
//act
var result = await dataSaubStatRepository.GetLastsAsync(telemetryIds, CancellationToken.None);
//assert
var expected = dataSaubStat.Max(stat => stat.DateEnd).ToOffset(timeZoneOffset);
var actual = result.First().DateEnd;
Assert.True((expected - actual).Ticks == 0.0);
}
[Fact]
public async Task InsertRangeAsync_returns_success()
{
//arrange
var telemetry = await dbContext.Telemetries.FirstAsync();
var timeZoneOffset = TimeSpan.FromHours(telemetry.TimeZone.Hours);
var dataSaubStat = CreateDataSaubStat(telemetry.Id, timeZoneOffset);
var expectedDtos = dataSaubStat.Select(entity => ConvertToDto(entity, timeZoneOffset));
//act
await dataSaubStatRepository.InsertRangeAsync(expectedDtos, CancellationToken.None);
//assert
var entities = await dbContext.DataSaubStat.ToArrayAsync();
var actualDtos = entities.Select(entity => ConvertToDto(entity, timeZoneOffset));
var excludedProps = new[]
{
nameof(DataSaubStat.Telemetry),
nameof(DataSaubStat.Id),
nameof(DataSaubStat.OperationCategory)
};
foreach (var actualDto in actualDtos)
{
var statDto = expectedDtos.FirstOrDefault(stat => stat.DateEnd == actualDto.DateEnd &&
stat.DateStart == actualDto.DateStart);
MatchHelper.Match(actualDto, statDto, excludedProps);
}
}
private static IEnumerable<DataSaubStat> CreateDataSaubStat(int idTelemetry, TimeSpan timeZoneOffset) => new DataSaubStat[]
{ {
new() new()
{ {
IdTelemetry = 1, IdTelemetry = idTelemetry,
DateEnd = new DateTimeOffset(2024, 1, 1, 20, 25, 0, timeSpan), DateEnd = new DateTimeOffset(2024, 1, 1, 20, 25, 0, timeZoneOffset).ToUniversalTime(),
DateStart = new DateTimeOffset(2024, 1, 1, 20, 15, 0, timeSpan), DateStart = new DateTimeOffset(2024, 1, 1, 20, 15, 0, timeZoneOffset).ToUniversalTime(),
AxialLoad = 10.0, AxialLoad = 10.0,
AxialLoadLimitMax = 10.0, AxialLoadLimitMax = 10.0,
AxialLoadSp = 10.0, AxialLoadSp = 10.0,
@ -27,8 +88,7 @@ public class DataSaubStatRepositoryTest : BaseIntegrationTest
EnabledSubsystems = 1, EnabledSubsystems = 1,
Flow = 10.0, Flow = 10.0,
HasOscillation = true, HasOscillation = true,
Id = default, IdCategory = WellOperationCategory.IdSlide,
IdCategory = 2,
IdFeedRegulator = 1, IdFeedRegulator = 1,
Pressure = 10.0, Pressure = 10.0,
PressureIdle = 10.0, PressureIdle = 10.0,
@ -41,9 +101,9 @@ public class DataSaubStatRepositoryTest : BaseIntegrationTest
}, },
new() new()
{ {
IdTelemetry = 1, IdTelemetry = idTelemetry,
DateEnd = new DateTimeOffset(2024, 2, 2, 20, 25, 0, timeSpan), DateEnd = new DateTimeOffset(2024, 2, 2, 20, 25, 0, timeZoneOffset).ToUniversalTime(),
DateStart = new DateTimeOffset(2024, 2, 2, 20, 15, 0, timeSpan), DateStart = new DateTimeOffset(2024, 2, 2, 20, 15, 0, timeZoneOffset).ToUniversalTime(),
AxialLoad = 10.0, AxialLoad = 10.0,
AxialLoadLimitMax = 10.0, AxialLoadLimitMax = 10.0,
AxialLoadSp = 10.0, AxialLoadSp = 10.0,
@ -53,8 +113,7 @@ public class DataSaubStatRepositoryTest : BaseIntegrationTest
EnabledSubsystems = 1, EnabledSubsystems = 1,
Flow = 10.0, Flow = 10.0,
HasOscillation = true, HasOscillation = true,
Id = default, IdCategory = WellOperationCategory.IdSlide,
IdCategory = 2,
IdFeedRegulator = 1, IdFeedRegulator = 1,
Pressure = 10.0, Pressure = 10.0,
PressureIdle = 10.0, PressureIdle = 10.0,
@ -66,99 +125,12 @@ public class DataSaubStatRepositoryTest : BaseIntegrationTest
Speed = 10.0 Speed = 10.0
} }
}; };
private static readonly WellOperationCategory category = new()
private static DataSaubStatDto ConvertToDto(DataSaubStat entity, TimeSpan timeZoneOffset)
{ {
Id = 2, var dto = entity.Adapt<DataSaubStatDto>();
IdParent = null, dto.DateStart = dto.DateStart.ToOffset(timeZoneOffset);
Name = "Категория 2" dto.DateEnd = dto.DateEnd.ToOffset(timeZoneOffset);
};
private readonly IDataSaubStatRepository dataSaubStatRepository;
public DataSaubStatRepositoryTest(WebAppFactoryFixture factory) : base(factory)
{
dataSaubStatRepository = scope.ServiceProvider.GetRequiredService<IDataSaubStatRepository>();
}
[Fact]
public async Task GetLastDatesAsync_returns_success()
{
//prepare
dbContext.CleanupDbSet<DataSaubStat>();
dbContext.CleanupDbSet<WellOperationCategory>();
var dbSetSaubStat = dbContext.Set<DataSaubStat>();
var dbSetCategories = dbContext.Set<WellOperationCategory>();
var entities = statDtos.Select(stat => ConvertToEntity(stat));
dbSetCategories.Add(category);
dbContext.SaveChanges();
dbSetSaubStat.AddRange(entities);
dbContext.SaveChanges();
//act
var telemetryIds = statDtos.Select(stat => stat.IdTelemetry).ToArray();
var result = await dataSaubStatRepository.GetLastsAsync(telemetryIds, CancellationToken.None);
var expected = statDtos.Max(stat => stat.DateEnd);
var actual = result.First().DateEnd;
//assert
Assert.True((expected - actual).Ticks == 0.0);
}
[Fact]
public async Task InsertRangeAsync_returns_success()
{
//prepare
dbContext.CleanupDbSet<DataSaubStat>();
var dbSet = dbContext.Set<DataSaubStat>();
var dbSetCategories = dbContext.Set<WellOperationCategory>();
dbSetCategories.Add(category);
dbContext.SaveChanges();
//act
var result = await dataSaubStatRepository.InsertRangeAsync(statDtos, CancellationToken.None);
//assert
Assert.Equal(statDtos.Length, result);
var statDtosFromDb = dbSet.Select(stat => ConvertToDto(stat, timeSpan)).ToArray();
var excludedProps = new[] {
nameof(DataSaubStat.Telemetry),
nameof(DataSaubStat.Id),
nameof(DataSaubStat.OperationCategory)
};
foreach (var statDtoFromDb in statDtosFromDb)
{
var statDto = statDtos
.Where(stat => stat.DateStart == statDtoFromDb.DateStart)
.Where(stat => stat.DateEnd == statDtoFromDb.DateEnd)
.FirstOrDefault();
MatchHelper.Match(statDtoFromDb, statDto, excludedProps);
}
}
private static DataSaubStat ConvertToEntity(DataSaubStatDto stat)
{
var entity = stat.Adapt<DataSaubStat>();
entity.DateStart = entity.DateStart.ToUniversalTime();
entity.DateEnd = entity.DateEnd.ToUniversalTime();
return entity;
}
private static DataSaubStatDto ConvertToDto(DataSaubStat stat, TimeSpan timeSpan)
{
var dto = stat.Adapt<DataSaubStatDto>();
dto.DateStart = dto.DateStart.ToOffset(timeSpan);
dto.DateEnd = dto.DateEnd.ToOffset(timeSpan);
return dto; return dto;
} }

View File

@ -1,4 +1,3 @@
using AsbCloudDb;
using AsbCloudDb.Model; using AsbCloudDb.Model;
using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing; using Microsoft.AspNetCore.Mvc.Testing;
@ -8,87 +7,85 @@ using Microsoft.Extensions.DependencyInjection;
using Refit; using Refit;
using System.Net.Http.Headers; using System.Net.Http.Headers;
using System.Text.Json; using System.Text.Json;
using AsbCloudDb;
using AsbCloudWebApi.IntegrationTests.Converters; using AsbCloudWebApi.IntegrationTests.Converters;
using Xunit;
namespace AsbCloudWebApi.IntegrationTests; namespace AsbCloudWebApi.IntegrationTests;
public class WebAppFactoryFixture : WebApplicationFactory<Startup>, public class WebAppFactoryFixture : WebApplicationFactory<Startup>
IAsyncLifetime
{ {
private static readonly JsonSerializerOptions jsonSerializerOptions = new() private static readonly JsonSerializerOptions JsonSerializerOptions = new()
{ {
PropertyNamingPolicy = JsonNamingPolicy.CamelCase, PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
PropertyNameCaseInsensitive = true, PropertyNameCaseInsensitive = true,
Converters = { new ValidationResultConverter() } Converters = { new ValidationResultConverter() }
}; };
private static readonly RefitSettings refitSettings = new RefitSettings(new SystemTextJsonContentSerializer(jsonSerializerOptions)); private static readonly RefitSettings RefitSettings = new(new SystemTextJsonContentSerializer(JsonSerializerOptions));
private readonly string connectionString;
public WebAppFactoryFixture()
{
var configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.Tests.json")
.Build();
var dbConnection = configuration.GetSection("DbConnection").Get<DbConnection>()!;
connectionString = dbConnection.GetConnectionString();
}
protected override void ConfigureWebHost(IWebHostBuilder builder) protected override void ConfigureWebHost(IWebHostBuilder builder)
{ {
var configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.Build();
var connectionString = configuration.GetConnectionString("TestConnection")!;
builder.ConfigureServices(services => builder.ConfigureServices(services =>
{ {
var descriptor = services.FirstOrDefault(d => d.ServiceType == typeof(DbContextOptions<AsbCloudDbContext>)); var descriptor = services.SingleOrDefault(d => d.ServiceType == typeof(DbContextOptions<AsbCloudDbContext>));
if (descriptor is not null) if (descriptor != null)
services.Remove(descriptor); services.Remove(descriptor);
services.AddDbContext<AsbCloudDbContext>(options => services.AddDbContext<AsbCloudDbContext>(options =>
options.UseNpgsql(connectionString)); options.UseNpgsql(connectionString));
var serviceProvider = services.BuildServiceProvider();
using var scope = serviceProvider.CreateScope();
var scopedServices = scope.ServiceProvider;
var dbContext = scopedServices.GetRequiredService<AsbCloudDbContext>();
dbContext.Database.EnsureCreatedAndMigrated();
dbContext.Deposits.AddRange(Data.Defaults.Deposits);
dbContext.SaveChanges();
}); });
} }
public async Task InitializeAsync() public override async ValueTask DisposeAsync()
{ {
using var scope = Services.CreateScope(); var dbContext = new AsbCloudDbContext(
var scopedServices = scope.ServiceProvider; new DbContextOptionsBuilder<AsbCloudDbContext>()
var dbContext = scopedServices.GetRequiredService<AsbCloudDbContext>(); .UseNpgsql(connectionString)
dbContext.Database.EnsureDeleted(); .Options);
dbContext.Database.EnsureCreatedAndMigrated();
await FillBaseDatasets(dbContext);
}
private static async Task FillBaseDatasets(AsbCloudDbContext dbContext)
{
dbContext.AddRange(Data.Defaults.Deposits);
dbContext.AddRange(Data.Defaults.Clusters);
dbContext.AddRange(Data.Defaults.Wells);
dbContext.AddRange(Data.Defaults.RelationsCompanyWell);
dbContext.AddRange(Data.Defaults.Telemetries);
dbContext.AddRange(Data.Defaults.Drillers);
dbContext.AddRange(Data.Defaults.WellOperations);
await dbContext.SaveChangesAsync();
}
public new async Task DisposeAsync()
{
using var scope = Services.CreateScope();
var scopedServices = scope.ServiceProvider;
var dbContext = scopedServices.GetRequiredService<AsbCloudDbContext>();
await dbContext.Database.EnsureDeletedAsync(); await dbContext.Database.EnsureDeletedAsync();
} }
public HttpClient GetAuthorizedHttpClient() public T GetAuthorizedHttpClient<T>(string uriSuffix)
{
var httpClient = GetAuthorizedHttpClient();
if (string.IsNullOrEmpty(uriSuffix))
return RestService.For<T>(httpClient, RefitSettings);
if (httpClient.BaseAddress is not null)
httpClient.BaseAddress = new Uri(httpClient.BaseAddress, uriSuffix);
return RestService.For<T>(httpClient, RefitSettings);
}
private HttpClient GetAuthorizedHttpClient()
{ {
var httpClient = CreateClient(); var httpClient = CreateClient();
var jwtToken = ApiTokenHelper.GetAdminUserToken(); var jwtToken = ApiTokenHelper.GetAdminUserToken();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", jwtToken); httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", jwtToken);
return httpClient; return httpClient;
} }
public T GetAuthorizedHttpClient<T>(string uriSuffix)
{
var httpClient = GetAuthorizedHttpClient();
if (!string.IsNullOrEmpty(uriSuffix))
if(httpClient.BaseAddress is not null)
httpClient.BaseAddress = new Uri(httpClient.BaseAddress, uriSuffix);
return RestService.For<T>(httpClient, refitSettings);
}
} }

View File

@ -1,13 +1,12 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Concurrent;
using System.Runtime.CompilerServices;
namespace AsbCloudWebApi namespace AsbCloudWebApi
{ {
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class PermissionAttribute : Attribute public class PermissionAttribute : Attribute
{ {
public static SortedSet<string> Registered { get; } = new SortedSet<string>(); public static ConcurrentBag<string> Registered { get; } = new();
public string Name { get; set; } = null!; public string Name { get; set; } = null!;

View File

@ -5,7 +5,11 @@ namespace AsbCloudWebApi
{ {
public static class ProtobufModel public static class ProtobufModel
{ {
private static readonly object SyncRoot = new();
public static void EnshureRegistered() public static void EnshureRegistered()
{
lock (SyncRoot)
{ {
EnshureRegisteredDataSpin(); EnshureRegisteredDataSpin();
EnshureRegisteredDataSaub(); EnshureRegisteredDataSaub();
@ -13,6 +17,7 @@ namespace AsbCloudWebApi
EnshureRegisteredWirelineRunOutBaseDto(); EnshureRegisteredWirelineRunOutBaseDto();
EnshureRegisteredWirelineRunOutDto(); EnshureRegisteredWirelineRunOutDto();
} }
}
private static void EnshureRegisteredWirelineRunOutBaseDto() private static void EnshureRegisteredWirelineRunOutBaseDto()
{ {

View File

@ -0,0 +1,8 @@
{
"DbConnection": {
"Host": "localhost",
"Port": 5432,
"Username": "postgres",
"Password": "q"
}
}