Merge pull request '#13686550 Рефакторинг тестов' (#162) from feature/tests into dev

Reviewed-on: http://test.digitaldrilling.ru:8080/DDrilling/AsbCloudServer/pulls/162
This commit is contained in:
Никита Фролов 2023-11-28 14:08:44 +05:00
commit 399dab884f
39 changed files with 1110 additions and 2601 deletions

View File

@ -20,15 +20,4 @@ public interface IHelpPageRepository : ICrudRepository<HelpPageDto>
Task<HelpPageDto?> GetOrDefaultByUrlPageAndIdCategoryAsync(string key,
int idCategory,
CancellationToken cancellationToken);
/// <summary>
/// Проверяет наличие справки для страницы
/// </summary>
/// <param name="key"></param>
/// <param name="idCategory"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<bool> IsExistingAsync(string key,
int idCategory,
CancellationToken cancellationToken);
}

View File

@ -31,9 +31,4 @@ public class HelpPageRepository : CrudRepositoryBase<HelpPageDto, HelpPage>,
return helpPage.Adapt<HelpPageDto>();
}
public Task<bool> IsExistingAsync(string key, int idCategory, CancellationToken cancellationToken) =>
dbContext.HelpPages.AnyAsync(h => h.UrlPage == key &&
h.IdCategory == idCategory,
cancellationToken);
}

View File

@ -6,7 +6,6 @@ using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using AsbCloudApp.Exceptions;
namespace AsbCloudInfrastructure.Services;
@ -82,7 +81,6 @@ public class HelpPageService : IHelpPageService
/// <param name="idCategory"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
/// <exception cref="NotFoundException"></exception>
public async Task<(Stream stream, string fileName)?> GetFileStreamAsync(string pageKey,
int idCategory,
CancellationToken cancellationToken)

View File

@ -9,12 +9,7 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="6.0.8" />
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="6.0.8" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="6.0.8" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.3.1" />
<PackageReference Include="MockQueryable.Moq" Version="6.0.1" />
<PackageReference Include="Moq" Version="4.18.2" />
<PackageReference Include="NSubstitute" Version="5.1.0" />
<PackageReference Include="xunit" Version="2.4.2" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.5">

View File

@ -1,157 +0,0 @@
namespace AsbCloudWebApi.Tests.ControllersTests
{
//public class AnalyticsControllerTests
//{
// private readonly Mock<ITelemetryAnalyticsService> analyticsService;
// private readonly Mock<IWellService> wellService;
// private readonly TelemetryAnalyticsController controller;
// private readonly List<WellDepthToDayDto> depthToDayDtos;
// // fills class fields with data. Each test inside can change this data themselves for their needs
// public AnalyticsControllerTests()
// {
// analyticsService = new Mock<ITelemetryAnalyticsService>();
// wellService = new Mock<IWellService>();
// depthToDayDtos = new List<WellDepthToDayDto>()
// {
// new WellDepthToDayDto { WellDepth = 1000.0, BitDepth = 1000.0, Date = DateTime.Now },
// new WellDepthToDayDto { WellDepth = 2000.0, BitDepth = 2000.0, Date = DateTime.Now },
// new WellDepthToDayDto { WellDepth = 3000.0, BitDepth = 3000.0, Date = DateTime.Now }
// };
// analyticsService.Setup(s => s.GetWellDepthToDayAsync(It.IsAny<int>(), CancellationToken.None).Result)
// .Returns(depthToDayDtos);
// wellService.Setup(s => s.IsCompanyInvolvedInWell(It.IsAny<int>(), It.IsAny<int>()))
// .Returns(true);
// wellService.Setup(s => s.IsCompanyInvolvedInWellAsync(It.IsAny<int>(), It.IsAny<int>(), It.IsAny<CancellationToken>()))
// .Returns(Task.FromResult(true));
// controller = new TelemetryAnalyticsController(analyticsService.Object,
// wellService.Object);
// controller.AddUser();
// }
// [Fact]
// public void It_should_return_depth_to_day_analytics()
// {
// var result = controller.GetWellDepthToDayAsync(1).Result;
// var okResult = result as OkObjectResult;
// Assert.NotNull(okResult);
// }
// [Fact]
// public void It_should_return_correct_count_depth_to_day_analytics()
// {
// var result = controller.GetWellDepthToDayAsync(1).Result;
// var okResult = result as OkObjectResult;
// var resultCount = ((List<WellDepthToDayDto>)okResult.Value).Count;
// Assert.Equal(3, resultCount);
// }
// [Fact]
// public void It_should_return_403_if_no_idCompany()
// {
// var emptyUserController = new TelemetryAnalyticsController(analyticsService.Object,
// wellService.Object);
// var user = new ClaimsPrincipal(new ClaimsIdentity(new Claim[] { }, "mock"));
// emptyUserController.ControllerContext = new ControllerContext()
// {
// HttpContext = new DefaultHttpContext() { User = user }
// };
// var result = emptyUserController.GetOperationsByWellAsync(1).Result;
// var forbidResult = result as ForbidResult;
// Assert.NotNull(forbidResult);
// }
// [Fact]
// public void It_should_return_403_if_user_doesnt_own_well()
// {
// var wellServiceReturnsFalse = new Mock<IWellService>();
// wellServiceReturnsFalse.Setup(s => s.IsCompanyInvolvedInWell(It.IsAny<int>(), It.IsAny<int>()))
// .Returns(false);
// var newControllerInstance = new TelemetryAnalyticsController(analyticsService.Object,
// wellServiceReturnsFalse.Object);
// var user = new ClaimsPrincipal(new ClaimsIdentity(new Claim[]
// {
// new Claim("idCompany", "1"),
// }, "mock"));
// newControllerInstance.ControllerContext = new ControllerContext()
// {
// HttpContext = new DefaultHttpContext() { User = user }
// };
// var result = newControllerInstance.GetWellDepthToDayAsync(1).Result;
// var forbidResult = result as ForbidResult;
// Assert.NotNull(forbidResult);
// }
// [Fact]
// public void It_should_return_204_if_dtos_is_empty()
// {
// var emptyAnalyticsService = new Mock<ITelemetryAnalyticsService>();
// emptyAnalyticsService.Setup(s => s.GetWellDepthToDayAsync(It.IsAny<int>(), CancellationToken.None).Result)
// .Returns(new List<WellDepthToDayDto>());
// var newControllerInstance = new TelemetryAnalyticsController(emptyAnalyticsService.Object,
// wellService.Object);
// var user = new ClaimsPrincipal(new ClaimsIdentity(new Claim[]
// {
// new Claim("idCompany", "1"),
// }, "mock"));
// newControllerInstance.ControllerContext = new ControllerContext()
// {
// HttpContext = new DefaultHttpContext() { User = user }
// };
// var result = newControllerInstance.GetWellDepthToDayAsync(1).Result;
// var notFoundResult = result as NoContentResult;
// Assert.NotNull(notFoundResult);
// }
// [Fact]
// public void It_should_return_204_if_dtos_is_null()
// {
// var emptyAnalyticsService = new Mock<ITelemetryAnalyticsService>();
// emptyAnalyticsService.Setup(s => s.GetWellDepthToDayAsync(It.IsAny<int>(), CancellationToken.None))
// .Returns(Task.FromResult<IEnumerable<WellDepthToDayDto>>(null));
// var newControllerInstance = new TelemetryAnalyticsController(emptyAnalyticsService.Object,
// wellService.Object);
// var user = new ClaimsPrincipal(new ClaimsIdentity(new Claim[]
// {
// new Claim("idCompany", "1"),
// }, "mock"));
// newControllerInstance.ControllerContext = new ControllerContext()
// {
// HttpContext = new DefaultHttpContext() { User = user }
// };
// var result = newControllerInstance.GetWellDepthToDayAsync(1).Result;
// var notFoundResult = result as NoContentResult;
// Assert.NotNull(notFoundResult);
// }
//}
}

View File

@ -1,26 +0,0 @@
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
namespace AsbCloudWebApi.Tests.ControllersTests
{
static class ControllerExtentions
{
public static void AddUser(this ControllerBase controller)
{
var claims = new Claim[] { new Claim("idCompany", "1") };
controller.AddUser(claims);
}
public static void AddUser(this ControllerBase controller, Claim[] claims)
{
var identity = new ClaimsIdentity(claims, "mock");
var user = new ClaimsPrincipal(identity);
controller.ControllerContext = new ControllerContext()
{
HttpContext = new DefaultHttpContext() { User = user }
};
}
}
}

View File

@ -1,26 +0,0 @@
using AsbCloudApp.Data.SAUB;
using AsbCloudApp.Services;
using AsbCloudWebApi.SignalR;
using Microsoft.AspNetCore.SignalR;
using Moq;
namespace AsbCloudWebApi.Tests.ControllersTests
{
public class TelemetryDataSaubControllerTests
{
private readonly Mock<ITelemetryService> telemetryService;
private readonly Mock<ITelemetryDataService<TelemetryDataSaubDto>> telemetryDataService;
private readonly Mock<IWellService> wellService;
private readonly Mock<IHubContext<TelemetryHub>> telemetryHubContext;
public TelemetryDataSaubControllerTests()
{
telemetryService = new Mock<ITelemetryService>();
telemetryDataService = new Mock<ITelemetryDataService<TelemetryDataSaubDto>>();
wellService = new Mock<IWellService>();
telemetryHubContext = new Mock<IHubContext<TelemetryHub>>();
}
}
}

View File

@ -1,17 +0,0 @@
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace AsbCloudWebApi.Tests
{
public interface IRepositoryFactory<TDto>
{
Task<int> DeleteAsync(int id, CancellationToken token);
Task<IEnumerable<TDto>> GetAllAsync(CancellationToken token);
TDto? GetOrDefault(int id);
Task<TDto?> GetOrDefaultAsync(int id, CancellationToken token);
Task<int> InsertAsync(TDto newItem, CancellationToken token);
Task<int> InsertRangeAsync(IEnumerable<TDto> newItems, CancellationToken token);
Task<int> UpdateAsync(TDto item, CancellationToken token);
}
}

View File

@ -17,6 +17,7 @@ using Xunit;
namespace AsbCloudWebApi.Tests.Middlware
{
//TODO: переписать как интеграционный тест. Использовать WebApplicationFactory.
public class UserConnectionsLimitMiddlwareTest
{
const int iterations2Block = 8;

View File

@ -1,42 +0,0 @@
using AsbCloudApp.Services;
using Moq;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace AsbCloudWebApi.Tests
{
public class RepositoryFactory
{
public static Mock<TRepository> Make<TRepository, TDto>(ICollection<TDto> data)
where TDto : AsbCloudApp.Data.IId
where TRepository : class, ICrudRepository<TDto>
{
var repositoryMock = new Mock<TRepository>();
repositoryMock.Setup(x => x.InsertAsync(It.IsAny<TDto>(), It.IsAny<CancellationToken>()))
.Returns((TDto dto, CancellationToken token) => {
var id = data.Max(x => x.Id);
dto.Id = ++id;
data.Add(dto);
return Task.FromResult(dto.Id);
});
repositoryMock.Setup(x => x.DeleteAsync(It.IsAny<int>(), It.IsAny<CancellationToken>()))
.Returns((int idFile, CancellationToken token) => {
var cnt = data.Count;
var dto = data.FirstOrDefault(x => x.Id == idFile);
data.Remove(dto);
return Task.FromResult(cnt - data.Count);
});
repositoryMock.Setup(x => x.GetAllAsync(It.IsAny<CancellationToken>())).ReturnsAsync(data);
repositoryMock.Setup(x => x.GetOrDefaultAsync(It.IsAny<int>(), It.IsAny<CancellationToken>()))
.Returns((int idFile, CancellationToken token) => {
return Task.FromResult(data.FirstOrDefault(x => x.Id == idFile));
});
return repositoryMock;
}
}
}

View File

@ -1,113 +0,0 @@
using AsbCloudInfrastructure.Background;
using Microsoft.Extensions.DependencyInjection;
using NSubstitute;
using System;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace AsbCloudWebApi.Tests.Services;
public class BackgroundWorkerTest
{
private IServiceProvider provider;
private BackgroundWorker service;
public BackgroundWorkerTest()
{
provider = Substitute.For<IServiceProvider, ISupportRequiredService>();
var serviceScope = Substitute.For<IServiceScope>();
var serviceScopeFactory = Substitute.For<IServiceScopeFactory>();
serviceScopeFactory.CreateScope().Returns(serviceScope);
((ISupportRequiredService)provider).GetRequiredService(typeof(IServiceScopeFactory)).Returns(serviceScopeFactory);
service = new BackgroundWorker(provider);
typeof(BackgroundWorker)
.GetField("minDelay", BindingFlags.NonPublic | BindingFlags.Instance)
.SetValue(service, TimeSpan.FromMilliseconds(1));
}
[Fact]
public async Task Enqueue_n_works()
{
var workCount = 10;
var result = 0;
Task workAction(string id, IServiceProvider services, Action<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);
service.Enqueue(work);
}
await service.ExecuteTask;
//assert
Assert.Equal(workCount, result);
}
[Fact]
public async Task Enqueue_continues_after_exceptions()
{
var expectadResult = 42;
var result = 0;
Task workAction(string id, IServiceProvider services, Action<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
service.Enqueue(badWork);
service.Enqueue(goodWork);
await service.ExecuteTask;
//assert
Assert.Equal(expectadResult, result);
Assert.Equal(1, service.Felled.Count);
Assert.Equal(1, service.Done.Count);
}
[Fact]
public async Task TryRemove()
{
var 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);
service.Enqueue(work);
}
var removed = service.TryRemoveFromQueue((workCount - 1).ToString());
await service.ExecuteTask;
//assert
Assert.True(removed);
Assert.Equal(workCount - 1, result);
Assert.Equal(workCount - 1, service.Done.Count);
}
}

View File

@ -1,94 +0,0 @@
using AsbCloudApp.Services;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace AsbCloudWebApi.Tests.ServicesTests
{
public abstract class CrudServiceTestAbstract<TDto>
where TDto : AsbCloudApp.Data.IId
{
private readonly ICrudRepository<TDto> service;
public CrudServiceTestAbstract()
{
AsbCloudInfrastructure.DependencyInjection.MapsterSetup();
service = MakeService();
}
protected abstract ICrudRepository<TDto> MakeService();
protected abstract TDto MakeNewItem();
[Fact]
public async Task<int> Insert()
{
var newItem = MakeNewItem();
var id = await service.InsertAsync(newItem, CancellationToken.None);
Assert.True(id > 0);
return id;
}
[Fact]
public async Task InsertRange()
{
var items = new TDto[2];
items[0] = MakeNewItem();
items[1] = MakeNewItem();
var count = await service.InsertRangeAsync(items, CancellationToken.None);
Assert.Equal(2, count);
}
[Fact]
public async Task GetById()
{
var id = await Insert();
var gotItem = await service.GetOrDefaultAsync(id, CancellationToken.None);
Assert.True(id > 0);
Assert.Equal(id, gotItem.Id);
}
[Fact]
public async Task GetAll()
{
var items = await service.GetAllAsync(CancellationToken.None);
var count = items.Count();
await Insert();
var newItems = await service.GetAllAsync(CancellationToken.None);
var newCount = newItems.Count();
Assert.True(newCount > 0);
Assert.Equal(count + 1, newCount);
}
[Fact]
public async Task UpdateAsync_returns_notfound()
{
var item = MakeNewItem();
item.Id = int.MaxValue - 1;
var updatedId = await service.UpdateAsync(item, CancellationToken.None);
Assert.True(updatedId < 0);
}
[Fact]
public async Task UpdateAsync()
{
var newItem = MakeNewItem();
newItem.Id = await service.InsertAsync(newItem, CancellationToken.None);
var item = MakeNewItem();
item.Id = newItem.Id;
var updatedId = await service.UpdateAsync(item, CancellationToken.None);
Assert.True(newItem.Id > 0);
Assert.Equal(newItem.Id, updatedId);
}
[Fact]
public async Task DeleteAsync()
{
var newItem = MakeNewItem();
var id = await service.InsertAsync(newItem, CancellationToken.None);
var deletedId = await service.DeleteAsync(id, CancellationToken.None);
Assert.True(id > 0);
Assert.Equal(id, deletedId);
}
}
}

View File

@ -1,28 +0,0 @@
using AsbCloudApp.Data;
using AsbCloudApp.Services;
using AsbCloudDb.Model;
using AsbCloudInfrastructure.Repository;
namespace AsbCloudWebApi.Tests.ServicesTests
{
public class DepositCrudCacheServiceTest : CrudServiceTestAbstract<DepositDto>
{
protected override DepositDto MakeNewItem()
{
var item = new DepositDto
{
Caption = "test deposit",
Latitude = 1,
Longitude = 2,
Timezone = new SimpleTimezoneDto { Hours = 5, TimezoneId = "test Never-land" }
};
return item;
}
protected override ICrudRepository<DepositDto> MakeService()
{
var dbContext = TestHelpter.MakeRealTestContext();
return new CrudCacheRepositoryBase<DepositDto, Deposit>(dbContext, TestHelpter.MemoryCache);
}
}
}

View File

@ -1,182 +0,0 @@
using AsbCloudApp.Data;
using AsbCloudApp.Requests;
using AsbCloudApp.Services;
using AsbCloudDb.Model;
using AsbCloudInfrastructure.Repository;
using AsbCloudInfrastructure.Services.DetectOperations;
using Moq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace AsbCloudWebApi.Tests.ServicesTests
{
public class DetectedOperationServiceTest
{
private readonly AsbCloudDbContext context;
private readonly DetectedOperationService service;
private readonly DetectedOperationRequest request;
private Deposit deposit = new Deposit { Id = 1, Caption = "Депозит 1" };
private Cluster cluster = new Cluster { Id = 1, Caption = "Кластер 1", IdDeposit = 1, Timezone = new SimpleTimezone() };
private WellDto wellDto = new WellDto
{
Id = 1,
Caption = "Test well 1",
IdTelemetry = 1,
IdCluster = 1,
Timezone = new SimpleTimezoneDto { Hours = 5 }
};
private Well well = new Well
{
Id = 1,
Caption = "Test well 1",
IdTelemetry = 1,
IdCluster = 1,
Timezone = new SimpleTimezone { Hours = 5 }
};
private Driller driller = new Driller
{
Id = 1,
Name = "Тестовый",
Patronymic = "Тест",
Surname = "Тестович"
};
private List<DetectedOperation> do1 = new List<DetectedOperation> {
new DetectedOperation
{
Id = 1,
IdCategory = 1,
IdTelemetry = 1,
DateStart = DateTimeOffset.Parse("2022-05-16T10:00:00.286Z"),
DateEnd = DateTimeOffset.Parse("2022-05-16T18:00:00.286Z"),
DepthStart = 100,
Value = 50,
DepthEnd = 1000
},
new DetectedOperation
{
Id = 2,
IdCategory = 1,
IdTelemetry = 1,
DateStart = DateTimeOffset.Parse("2022-05-16T10:00:00.286Z"),
DateEnd = DateTimeOffset.Parse("2022-05-16T18:00:00.286Z"),
DepthStart = 100,
Value = 10,
DepthEnd = 1000
}};
private Telemetry telemetry = new Telemetry
{
Id = 1,
RemoteUid = Guid.NewGuid().ToString()
};
private OperationValue ovd = new OperationValue
{
Id = 1,
StandardValue = 200,
TargetValue = 100,
DepthEnd = 300,
DepthStart = 100,
IdOperationCategory=1,
IdWell = 1
};
private List<Schedule> sch = new List<Schedule> { new Schedule
{
Id = 1,
IdDriller = 1,
IdWell = 1,
DrillStart = DateTimeOffset.Parse("2022-05-16T10:00:00.286Z"),
DrillEnd = DateTimeOffset.Parse("2022-05-16T18:00:00.286Z"),
ShiftStart = new TimeOnly(10, 00),
ShiftEnd = new TimeOnly(18, 00)
}, new Schedule
{
Id = 2,
IdDriller = 1,
IdWell = 1,
DrillStart = DateTimeOffset.Parse("2022-05-17T10:00:00.286Z"),
DrillEnd = DateTimeOffset.Parse("2022-05-17T18:00:00.286Z"),
ShiftStart = new TimeOnly(10, 00),
ShiftEnd = new TimeOnly(18, 00)
} };
public DetectedOperationServiceTest()
{
context = TestHelpter.MakeRealTestContext();
context.SaveChanges();
context.Telemetries.Add(telemetry);
context.Deposits.Add(deposit);
context.Clusters.Add(cluster);
context.Wells.Add(well);
context.Drillers.Add(driller);
context.DetectedOperations.AddRange(do1);
context.OperationValues.Add(ovd);
context.Schedule.AddRange(sch);
context.SaveChanges();
var timezone = new SimpleTimezoneDto { Hours = 5 };
var wellServiceMock = new Mock<IWellService>();
wellServiceMock.Setup(s => s.GetTimezone(It.IsAny<int>())).Returns(timezone);
wellServiceMock.Setup(s => s.GetOrDefaultAsync(It.IsAny<int>(),CancellationToken.None)).Returns(Task.Run(() => wellDto));
//var operationValueService = new OperationValueService(context);
var scheduleService = new ScheduleRepository(context, wellServiceMock.Object);
service = new DetectedOperationService(context, wellServiceMock.Object, /*operationValueService*/ null, scheduleService);
request = new DetectedOperationRequest
{
IdWell = 1,
IdsCategories = new int[] { 1 },
};
AsbCloudInfrastructure.DependencyInjection.MapsterSetup();
}
~DetectedOperationServiceTest()
{
}
[Fact]
public async Task Count_grouping_by_driller()
{
var list = await service.GetAsync(request, CancellationToken.None);
Assert.Equal(2, list.Stats.First().Count);
}
[Fact]
public async Task AvgVal_grouping_by_driller()
{
var list = await service.GetAsync(request, CancellationToken.None);
Assert.Equal(30, list.Stats.First().AverageValue);
}
[Fact]
public async Task AvgTargetVal_grouping_by_driller()
{
var list = await service.GetAsync(request, CancellationToken.None);
Assert.Equal(100, list.Stats.First().AverageTargetValue);
}
[Fact]
public async Task Loss_grouping_by_driller()
{
var list = await service.GetAsync(request, CancellationToken.None);
Assert.Equal(0, list.Stats.First().Loss);
}
[Fact]
public async Task Efficiency_grouping_by_driller()
{
var list = await service.GetAsync(request, CancellationToken.None);
Assert.Equal(100, list.Stats.First().Efficiency);
}
[Fact]
public async Task GroupCount_grouping_by_driller()
{
var list = await service.GetAsync(request, CancellationToken.None);
Assert.Equal(1, list.Stats.Count());
}
}
}

View File

@ -1,93 +0,0 @@
using AsbCloudApp.Data;
using AsbCloudApp.Services;
using Moq;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace AsbCloudWebApi.Tests.ServicesTests
{
public class DrillerServiceTest
{
private static List<DrillerDto> Drillers = new List<DrillerDto> {
new DrillerDto
{
Id = 1,
Name = "Тестовый",
Patronymic = "Тест",
Surname = "Тестович"
},
new DrillerDto
{
Id = 1,
Name = "Тестовый",
Patronymic = "Тест",
Surname = "Тестович"
}
};
private ICrudRepository<DrillerDto> service;
public DrillerServiceTest()
{
var repositoryMock = RepositoryFactory.Make<ICrudRepository<DrillerDto>, DrillerDto>(Drillers);
repositoryMock.Setup(x => x.GetAllAsync(It.IsAny<CancellationToken>()))
.Returns(() => {
var data = Drillers;
return Task.FromResult(data.AsEnumerable());
});
repositoryMock.Setup(x => x.InsertAsync(It.IsAny<DrillerDto>(), It.IsAny<CancellationToken>()))
.Returns((DrillerDto dto, CancellationToken token) => {
Drillers.Add(dto);
return Task.FromResult(Drillers.Count());
});
repositoryMock.Setup(x => x.UpdateAsync(It.IsAny<DrillerDto>(), It.IsAny<CancellationToken>()))
.Returns((DrillerDto dto, CancellationToken token) => {
var baseDto = Drillers.First(x => x.Id == dto.Id);
Drillers.Remove(baseDto);
Drillers.Add(dto);
return Task.FromResult(Drillers.Count());
});
service = repositoryMock.Object;
}
~DrillerServiceTest()
{
}
[Fact]
public async Task GetListAsync_count()
{
var data = await service.GetAllAsync(CancellationToken.None);
Assert.Equal(2, data.Count());
}
[Fact]
public async Task InsertAsync_returns_id()
{
var dto = new DrillerDto {
Id = 3,
Name = "Тестовый",
Patronymic = "Тест",
Surname = "Тестович"
};
var cnt = await service.InsertAsync(dto, CancellationToken.None);
Assert.Equal(3, cnt);
}
[Fact]
public async Task UpdateAsync_not_add_if_exists()
{
var dto = Drillers.First(x => x.Id == 1);
dto.Name = "Edit";
var oldCount = Drillers.Count();
var count = await service.UpdateAsync(dto, CancellationToken.None);
Assert.Equal(oldCount, count);
}
}
}

View File

@ -1,444 +0,0 @@
using AsbCloudApp.Data;
using AsbCloudApp.Data.User;
using AsbCloudApp.Repositories;
using AsbCloudApp.Services;
using AsbCloudDb.Model;
using AsbCloudInfrastructure.Background;
using AsbCloudInfrastructure.Services.DrillingProgram;
using Mapster;
using Microsoft.Extensions.Configuration;
using Moq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using AsbCloudApp.Services.Notifications;
using Xunit;
namespace AsbCloudWebApi.Tests.ServicesTests
{
public class DrillingProgramServiceTest
{
private const int idWell = 3001;
private static readonly SimpleTimezone baseTimezone = new() { Hours = 5d };
private readonly AsbCloudDbContext db;
private static readonly List<Well> wells = new()
{
new Well { Id = 3001, Caption = "well 1", Timezone = baseTimezone },
new Well { Id = 3002, Caption = "well 2", Timezone = baseTimezone },
};
private static readonly List<Company> companies = new() {
new Company { Id = 3001, Caption = "company name", IdCompanyType = 2, },
new Company { Id = 3002, Caption = "company name", IdCompanyType = 2, },
new Company { Id = 3003, Caption = "company name", IdCompanyType = 2, },
};
private static readonly User publisher1 = new() { Id = 3001, IdCompany = 3001, Login = "user 1", Email = "aa@aa.aa", IdState = 2 };
private static readonly User approver1 = new() { Id = 3002, IdCompany = 3001, Login = "user 2", Email = "aa@aa.aa", IdState = 2 };
private static readonly User approver2 = new() { Id = 3003, IdCompany = 3002, Login = "user 3", Email = "aa@aa.aa", IdState = 2 };
private static readonly List<User> users = new()
{
publisher1,
approver1,
approver2,
new User { Id = 3004, IdCompany = 3001, Login = "wrong 1", Email = "", IdState = 2 },
new User { Id = 3005, IdCompany = 3003, Login = "wrong 2", Email = "aa@aa.aa", IdState = 2 },
};
private static readonly FileInfo file1001 = new()
{
Id = 3001,
IdWell = idWell,
IdCategory = 1001,
IdAuthor = publisher1.Id,
IsDeleted = false,
Name = "file1.xlsx",
Size = 1024,
UploadDate = System.DateTimeOffset.UtcNow,
};
private static readonly FileInfo file1002 = new()
{
Id = 3002,
IdWell = idWell,
IdCategory = 1002,
IdAuthor = publisher1.Id,
IsDeleted = false,
Name = "file2.xlsx",
Size = 1024,
UploadDate = System.DateTimeOffset.UtcNow,
};
private static readonly List<RelationCompanyWell> relationsCompanyWell = new()
{
new RelationCompanyWell { IdCompany = 3001, IdWell = 3001, },
new RelationCompanyWell { IdCompany = 3002, IdWell = 3001, },
new RelationCompanyWell { IdCompany = 3002, IdWell = 3002, },
new RelationCompanyWell { IdCompany = 3003, IdWell = 3002, },
};
private readonly Mock<FileService> fileServiceMock;
private readonly Mock<IUserRepository> userRepositoryMock;
private readonly Mock<IWellService> wellServiceMock;
private readonly Mock<IConfiguration> configurationMock;
private readonly Mock<BackgroundWorker> backgroundWorkerMock;
private readonly Mock<NotificationService> notificationServiceMock;
public DrillingProgramServiceTest()
{
AsbCloudInfrastructure.DependencyInjection.MapsterSetup();
db = TestHelpter.MakeRealTestContext();
db.Wells.AddRange(wells);
db.Companies.AddRange(companies);
db.SaveChanges();
db.Users.AddRange(users);
db.RelationCompaniesWells.AddRange(relationsCompanyWell);
db.SaveChanges();
fileServiceMock = new Mock<FileService>();
userRepositoryMock = new Mock<IUserRepository>();
wellServiceMock = new Mock<IWellService>();
configurationMock = new Mock<IConfiguration>();
backgroundWorkerMock = new Mock<BackgroundWorker>();
notificationServiceMock = new Mock<NotificationService>();
}
[Fact]
public async Task GetAvailableUsers_returns_3_users()
{
var service = new DrillingProgramService(
db,
fileServiceMock.Object,
userRepositoryMock.Object,
wellServiceMock.Object,
configurationMock.Object,
backgroundWorkerMock.Object,
notificationServiceMock.Object);
var users = await service.GetAvailableUsers(idWell, CancellationToken.None);
Assert.Equal(3, users.Count());
}
[Fact]
public async Task AddPartsAsync_returns_2()
{
var service = new DrillingProgramService(
db,
fileServiceMock.Object,
userRepositoryMock.Object,
wellServiceMock.Object,
configurationMock.Object,
backgroundWorkerMock.Object,
notificationServiceMock.Object);
var result = await service.AddPartsAsync(idWell, new int[] { 1001, 1002 }, CancellationToken.None);
Assert.Equal(2, result);
}
[Fact]
public async Task RemovePartsAsync_returns_1()
{
db.DrillingProgramParts.Add(new DrillingProgramPart { IdFileCategory = 1005, IdWell = idWell });
db.SaveChanges();
var service = new DrillingProgramService(
db,
fileServiceMock.Object,
userRepositoryMock.Object,
wellServiceMock.Object,
configurationMock.Object,
backgroundWorkerMock.Object,
notificationServiceMock.Object);
var result = await service.RemovePartsAsync(idWell, new int[] { 1005 }, CancellationToken.None);
Assert.Equal(1, result);
}
[Fact]
public async Task AddUserAsync_returns_1()
{
db.DrillingProgramParts.Add(new DrillingProgramPart { IdFileCategory = 1001, IdWell = idWell });
db.SaveChanges();
userRepositoryMock.Setup((s) => s.GetOrDefaultAsync(It.IsAny<int>(), It.IsAny<CancellationToken>()))
.Returns(Task.FromResult(publisher1.Adapt<UserExtendedDto>()));
var service = new DrillingProgramService(
db,
fileServiceMock.Object,
userRepositoryMock.Object,
wellServiceMock.Object,
configurationMock.Object,
backgroundWorkerMock.Object,
notificationServiceMock.Object);
var result = await service.AddUserAsync(idWell, 1001, publisher1.Id, 1, CancellationToken.None);
Assert.Equal(1, result);
}
[Fact]
public async Task RemoveUserAsync_returns_1()
{
const int idUserRole = 1;
const int idFileCategory = 1001;
var entry = db.DrillingProgramParts.Add(new DrillingProgramPart
{
IdFileCategory = idFileCategory,
IdWell = idWell
});
db.SaveChanges();
db.RelationDrillingProgramPartUsers.Add(new RelationUserDrillingProgramPart
{
IdUser = publisher1.Id,
IdDrillingProgramPart = entry.Entity.Id,
IdUserRole = idUserRole
});
db.SaveChanges();
userRepositoryMock.Setup((s) => s.GetOrDefaultAsync(It.IsAny<int>(), It.IsAny<CancellationToken>()))
.Returns(Task.FromResult(publisher1.Adapt<UserExtendedDto>()));
var service = new DrillingProgramService(
db,
fileServiceMock.Object,
userRepositoryMock.Object,
wellServiceMock.Object,
configurationMock.Object,
backgroundWorkerMock.Object,
notificationServiceMock.Object);
var result = await service.RemoveUserAsync(idWell, idFileCategory, publisher1.Id, idUserRole, CancellationToken.None);
Assert.Equal(1, result);
}
[Fact]
public async Task AddOrReplaceFileMarkAsync_returns_1()
{
ConfigureNotApproved();
fileServiceMock
.Setup(s => s.GetOrDefaultAsync(It.IsAny<int>(), It.IsAny<CancellationToken>()))
.Returns(Task.FromResult(file1002.Adapt<FileInfoDto>()));
fileServiceMock
.Setup(s => s.CreateFileMarkAsync(It.IsAny<FileMarkDto>(), It.IsAny<int>(), It.IsAny<CancellationToken>()))
.Returns(Task.FromResult(1));
var service = new DrillingProgramService(
db,
fileServiceMock.Object,
userRepositoryMock.Object,
wellServiceMock.Object,
configurationMock.Object,
backgroundWorkerMock.Object,
notificationServiceMock.Object);
var fileMark = new FileMarkDto
{
IdFile = file1002.Id,
IdMarkType = 1,
DateCreated = DateTime.Now,
};
var affected = await service.AddOrReplaceFileMarkAsync(fileMark, approver1.Id, CancellationToken.None);
Assert.Equal(1, affected);
}
[Fact]
public async Task AddOrReplaceFileMarkAsync_as_replace_returns_1()
{
ConfigureNotApproved();
fileServiceMock
.Setup(s => s.GetOrDefaultAsync(It.IsAny<int>(), It.IsAny<CancellationToken>()))
.Returns(Task.FromResult(file1002.Adapt<FileInfoDto>()));
fileServiceMock
.Setup(s => s.CreateFileMarkAsync(It.IsAny<FileMarkDto>(), It.IsAny<int>(), It.IsAny<CancellationToken>()))
.Returns(Task.FromResult(1));
var service = new DrillingProgramService(
db,
fileServiceMock.Object,
userRepositoryMock.Object,
wellServiceMock.Object,
configurationMock.Object,
backgroundWorkerMock.Object,
notificationServiceMock.Object);
var fileMark = new FileMarkDto
{
IdFile = file1001.Id,
IdMarkType = 0,
DateCreated = DateTime.Now,
};
await service.AddOrReplaceFileMarkAsync(fileMark, approver1.Id, CancellationToken.None);
var fileMark2 = new FileMarkDto
{
IdFile = file1001.Id,
IdMarkType = 1,
DateCreated = DateTime.Now.AddHours(1),
};
var affected = await service.AddOrReplaceFileMarkAsync(fileMark2, approver1.Id, CancellationToken.None);
Assert.Equal(1, affected);
}
[Fact]
public async Task MarkAsDeletedFileMarkAsync_returns_1()
{
ConfigureNotApproved();
fileServiceMock
.Setup(s => s.GetByMarkId(It.IsAny<int>(), It.IsAny<CancellationToken>()))
.Returns(Task.FromResult(file1002.Adapt<FileInfoDto>()));
fileServiceMock
.Setup(s => s.MarkFileMarkAsDeletedAsync(It.IsAny<int>(), It.IsAny<CancellationToken>()))
.Returns(Task.FromResult(1));
var service = new DrillingProgramService(
db,
fileServiceMock.Object,
userRepositoryMock.Object,
wellServiceMock.Object,
configurationMock.Object,
backgroundWorkerMock.Object,
notificationServiceMock.Object);
var fileMark = new FileMarkDto
{
IdFile = file1001.Id,
IdMarkType = 0,
DateCreated = DateTime.Now,
};
int idMark = 0;
var affected = await service.MarkAsDeletedFileMarkAsync(idMark, CancellationToken.None);
Assert.Equal(1, affected);
}
[Fact]
public async Task GetStateAsync_returns_state_1()
{
ConfigureNotApproved();
var service = new DrillingProgramService(
db,
fileServiceMock.Object,
userRepositoryMock.Object,
wellServiceMock.Object,
configurationMock.Object,
backgroundWorkerMock.Object,
notificationServiceMock.Object);
var state = await service.GetStateAsync(idWell, publisher1.Id, CancellationToken.None);
Assert.Equal(1, state.IdState);
}
[Fact]
public async Task GetStateAsync_returns_state_2()
{
ConfigureNotApproved();
db.FileMarks.AddRange(
new FileMark { IdFile = file1002.Id, IdUser = approver1.Id, IdMarkType = 1, DateCreated = System.DateTimeOffset.UtcNow },
new FileMark { IdFile = file1002.Id, IdUser = approver2.Id, IdMarkType = 1, DateCreated = System.DateTimeOffset.UtcNow }
);
await db.SaveChangesAsync();
wellServiceMock.Setup(s => s.GetOrDefaultAsync(It.IsAny<int>(), It.IsAny<CancellationToken>()))
.Returns(Task.FromResult(new WellDto { Caption = "test well", Cluster = "test cluster" }));
var service = new DrillingProgramService(
db,
fileServiceMock.Object,
userRepositoryMock.Object,
wellServiceMock.Object,
configurationMock.Object,
backgroundWorkerMock.Object,
notificationServiceMock.Object);
var state = await service.GetStateAsync(idWell, publisher1.Id, CancellationToken.None);
Assert.Equal(2, state.IdState);
backgroundWorkerMock.Verify(s => s.Enqueue(It.IsAny<Work>()));
}
[Fact]
public async Task GetStateAsync_returns_state_3()
{
ConfigureNotApproved();
db.FileMarks.AddRange(
new FileMark { IdFile = file1002.Id, IdUser = approver1.Id, IdMarkType = 1, DateCreated = DateTimeOffset.UtcNow },
new FileMark { IdFile = file1002.Id, IdUser = approver2.Id, IdMarkType = 1, DateCreated = DateTimeOffset.UtcNow }
);
db.Files.AddRange(new FileInfo { IdCategory = 1000, IdWell = idWell, Name = "DrillingProgram.xalsx", Size = 1024 * 1024, UploadDate = DateTimeOffset.UtcNow });
await db.SaveChangesAsync();
wellServiceMock.Setup(s => s.GetOrDefaultAsync(It.IsAny<int>(), It.IsAny<CancellationToken>()))
.Returns(Task.FromResult(new WellDto { Caption = "test well", Cluster = "test cluster" }));
var service = new DrillingProgramService(
db,
fileServiceMock.Object,
userRepositoryMock.Object,
wellServiceMock.Object,
configurationMock.Object,
backgroundWorkerMock.Object,
notificationServiceMock.Object);
var state = await service.GetStateAsync(idWell, publisher1.Id, CancellationToken.None);
Assert.Equal(3, state.IdState);
backgroundWorkerMock.VerifyNoOtherCalls();
}
private void ConfigureNotApproved()
{
db.DrillingProgramParts.RemoveRange(db.DrillingProgramParts);
db.Files.RemoveRange(db.Files);
//db.RelationDrillingProgramPartUsers.RemoveRange(db.RelationDrillingProgramPartUsers);
db.SaveChanges();
var entry1 = db.DrillingProgramParts.Add(new DrillingProgramPart { IdWell = idWell, IdFileCategory = 1001 });
var entry2 = db.DrillingProgramParts.Add(new DrillingProgramPart { IdWell = idWell, IdFileCategory = 1002 });
db.SaveChanges();
db.RelationDrillingProgramPartUsers.AddRange(new List<RelationUserDrillingProgramPart>{
new RelationUserDrillingProgramPart{
IdDrillingProgramPart = entry1.Entity.Id,
IdUser = publisher1.Id,
IdUserRole = 1,
},
new RelationUserDrillingProgramPart{
IdDrillingProgramPart = entry2.Entity.Id,
IdUser = publisher1.Id,
IdUserRole = 1,
},
new RelationUserDrillingProgramPart{
IdDrillingProgramPart = entry2.Entity.Id,
IdUser = approver1.Id,
IdUserRole = 2,
},
new RelationUserDrillingProgramPart{
IdDrillingProgramPart = entry2.Entity.Id,
IdUser = approver2.Id,
IdUserRole = 2,
},
});
db.Files.AddRange(new List<FileInfo>{
file1001,
file1002
});
db.SaveChanges();
}
}
}

View File

@ -1,34 +0,0 @@
using AsbCloudDb.Model;
using AsbCloudInfrastructure.Services;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace AsbCloudWebApi.Tests.ServicesTests
{
public class FileCategoryServiceTest
{
private readonly AsbCloudDbContext context;
private FileCategoryService service;
public FileCategoryServiceTest()
{
context = TestHelpter.MakeRealTestContext();
context.SaveChanges();
service = new FileCategoryService(context, TestHelpter.MemoryCache);
}
~FileCategoryServiceTest()
{
}
[Fact]
public async Task GetWellCategoryAsync_return_cnt_file_category()
{
var cnt = (await service.GetWellCaseCategoriesAsync(CancellationToken.None)).Count();
Assert.NotEqual(0, cnt);
}
}
}

View File

@ -1,201 +0,0 @@
using AsbCloudApp.Data;
using AsbCloudApp.Data.User;
using AsbCloudApp.Repositories;
using AsbCloudApp.Requests;
using AsbCloudApp.Services;
using Moq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace AsbCloudWebApi.Tests.ServicesTests
{
public class FileServiceTest
{
private FileService fileService;
private static UserDto Author = new UserDto {
Id = 1,
IdCompany = 1
};
private static List<FileMarkDto> FileMarks = new List<FileMarkDto> {
new FileMarkDto
{
Id = 132,
IdFile = 1742,
User = Author,
Comment = "qqq",
IdMarkType = 1,
DateCreated = DateTime.Now,
IsDeleted = false
},
new FileMarkDto
{
Id = 133,
IdFile = 1742,
User = Author,
Comment = "qqq3",
IdMarkType = 1,
DateCreated = DateTime.Now,
IsDeleted = false
}
};
private static List<FileInfoDto> Files = new List<FileInfoDto> {
new FileInfoDto {
Id = 1742,
IdAuthor = 1,
Author = Author,
IdWell = 90,
IdCategory = 10040,
Name = "test.txt",
Size = 0,
UploadDate = DateTime.Now,
FileMarks = FileMarks
},
new FileInfoDto
{
Id = 1743,
IdAuthor = 1,
Author = Author,
IdWell = 90,
IdCategory = 10021,
Name = "test1.txt",
Size = 0,
UploadDate = DateTime.Now
}
};
public FileServiceTest()
{
var repositoryMock = RepositoryFactory.Make<IFileRepository, FileInfoDto>(Files);
repositoryMock.Setup(x => x.GetByMarkId(It.IsAny<int>(), It.IsAny<CancellationToken>()))
.Returns((int idMark, CancellationToken token) => {
var data = Files.FirstOrDefault(x => x.FileMarks.Any(m => m.Id == idMark));
return Task.FromResult(data);
});
repositoryMock.Setup(x => x.GetInfoByIdsAsync(It.IsAny<IEnumerable<int>>(), It.IsAny<CancellationToken>()))
.Returns((int[] idsFile, CancellationToken token) => {
var data = Files.Where(x => idsFile.Contains(x.Id));
return Task.FromResult(data);
});
repositoryMock.Setup(x => x.DeleteAsync(It.IsAny<IEnumerable<int>>(), It.IsAny<CancellationToken>()))
.Returns((int[] idsFile, CancellationToken token) => {
var dtos = Files.Where(x => idsFile.Contains(x.Id)).ToArray();
Files.RemoveAll(x => dtos.Select(d => d.Id).Contains(x.Id));
return Task.FromResult(dtos.AsEnumerable());
});
repositoryMock.Setup(x => x.MarkFileMarkAsDeletedAsync(It.IsAny<IEnumerable<int>>(), It.IsAny<CancellationToken>()))
.Returns((int[] idsMarks, CancellationToken token) => {
var data = FileMarks.Where(m => idsMarks.Contains(m.Id));
foreach (var fileMark in data)
fileMark.IsDeleted = true;
var result = data.All(x => x.IsDeleted) ? 1 : 0;
return Task.FromResult(result);
});
repositoryMock.Setup(x => x.MarkAsDeletedAsync(It.IsAny<int>(), It.IsAny<CancellationToken>()))
.Returns((int idFile, CancellationToken token) => {
var result = Files.Where(x => x.Id == idFile).Any() ? 1 : 0;
return Task.FromResult(result);
});
repositoryMock.Setup(x => x.GetInfosAsync(It.IsAny<FileRequest>(), It.IsAny<CancellationToken>()))
.Returns((FileRequest request, CancellationToken token) => {
var data = Files.Where(x => x.IdWell == request.IdWell);
return Task.FromResult(data);
});
repositoryMock.Setup(x => x.CreateFileMarkAsync(It.IsAny<FileMarkDto>(), It.IsAny<int>(), It.IsAny<CancellationToken>()))
.Returns((FileMarkDto dto, int idUser, CancellationToken token) => {
dto.Id = FileMarks.Max(x => x.Id) + 1;
dto.DateCreated = DateTime.UtcNow;
dto.User = null;
FileMarks.Add(dto);
var result = FileMarks.Any(x => x.Id == dto.Id) ? 1 : 0;
return Task.FromResult(result);
});
var storageRepositoryMock = new Mock<IFileStorageRepository>();
storageRepositoryMock.Setup(x => x.GetFilePath(It.IsAny<int>(), It.IsAny<int>(), It.IsAny<int>(), It.IsAny<string>()))
.Returns((int idWell, int idCategory, int idFile, string dotExtention) => {
return Path.Combine("files", idWell.ToString(), idCategory.ToString(), $"{idFile}{dotExtention}");
});
fileService = new FileService(repositoryMock.Object, storageRepositoryMock.Object);
}
[Fact]
public async Task GetByMarkId_returns_FileInfo_by_idMark()
{
var data = await fileService.GetByMarkId(133, CancellationToken.None);
Assert.NotNull(data);
}
[Fact]
public async Task GetOrDefaultAsync_returns_FileInfo()
{
var data = await fileService.GetOrDefaultAsync(1742, CancellationToken.None);
Assert.NotNull(data);
}
[Fact]
public async Task GetInfoByIdsAsync_returns_FileInfo()
{
var data = await fileService.GetInfoByIdsAsync(new int[] { 1742, 1743 }, CancellationToken.None);
Assert.NotNull(data);
}
[Fact]
public async Task SaveAsync_returns_FileInfo()
{
using var stream = new MemoryStream(Array.Empty<byte>());
var data = await fileService.SaveAsync(90, 1, 10040, "test.txt", stream, CancellationToken.None);
Assert.NotNull(data);
}
[Fact]
public async Task DeleteAsync()
{
var result = await fileService.DeleteAsync(new int[] { 1743 }, CancellationToken.None);
Assert.True(result > 0);
}
[Fact]
public async Task MarkFileMarkAsDeletedAsync()
{
var result = await fileService.MarkFileMarkAsDeletedAsync(new int[] { 132, 133 }, CancellationToken.None);
Assert.True(result > 0);
}
[Fact]
public async Task MarkAsDeletedAsync()
{
var result = await fileService.MarkAsDeletedAsync(1742, CancellationToken.None);
Assert.True(result > 0);
}
[Fact]
public async Task CreateFileMarkAsync()
{
var dto = new FileMarkDto {
Comment = "test",
IdFile = 1742,
IdMarkType = 1
};
var result = await fileService.CreateFileMarkAsync(dto, 1, CancellationToken.None);
Assert.True(result > 0);
}
}
}

View File

@ -1,145 +0,0 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using AsbCloudApp.Data;
using AsbCloudApp.Repositories;
using AsbCloudApp.Services;
using AsbCloudInfrastructure.Services;
using Microsoft.Extensions.Configuration;
using Moq;
using Xunit;
namespace AsbCloudWebApi.Tests.ServicesTests;
public class HelpPageServiceTest
{
private static Dictionary<string, string> configSettings = new (){
{"DirectoryNameHelpPageFiles", "helpPages"}
};
private static List<HelpPageDto> HelpPages = new()
{
new()
{
Id = 123,
IdCategory = 20000,
Name = "Справка1.pdf",
Size = 54000,
UrlPage = "test"
},
new()
{
Id = 134,
IdCategory = 20000,
Name = "Справка2.pdf",
Size = 51000,
UrlPage = "test1"
},
new()
{
Id = 178,
IdCategory = 10000,
Name = "Справка3.pdf",
Size = 49000,
UrlPage = "test2"
}
};
private readonly Mock<IHelpPageRepository> helpPageRepository = new();
private readonly Mock<IFileStorageRepository> fileStorageRepository = new();
private readonly IHelpPageService helpPageService;
public HelpPageServiceTest()
{
IConfiguration configuration = new ConfigurationBuilder()
.AddInMemoryCollection(configSettings)
.Build();
helpPageService = new HelpPageService(helpPageRepository.Object,
fileStorageRepository.Object,
configuration);
}
[Fact]
public async Task AddOrUpdateAsync_ShouldReturn_NewHelpPage()
{
//arrange
int idHelpPage = new Random().Next(1, 100);
string urlPage = "test";
int idCategory = 20000;
string fileName = "test.pdf";
MemoryStream fileStream = new MemoryStream(Array.Empty<byte>());
helpPageRepository.Setup(x => x.GetOrDefaultByUrlPageAndIdCategoryAsync(It.IsAny<string>(),
It.IsAny<int>(), It.IsAny<CancellationToken>()))
.Returns(() =>
{
var helpPage = HelpPages.FirstOrDefault(x =>
x.UrlPage == urlPage &&
x.IdCategory == idCategory);
return Task.FromResult(helpPage);
});
helpPageRepository.Setup(x => x.InsertAsync(It.IsAny<HelpPageDto>(),
It.IsAny<CancellationToken>()))
.Returns(() => Task.FromResult(idHelpPage));
fileStorageRepository.Setup(x => x.SaveFileAsync(It.IsAny<string>(),
It.IsAny<Stream>(),
It.IsAny<CancellationToken>()));
//act
int result = await helpPageService.AddOrUpdateAsync(urlPage,
idCategory,
fileName,
fileStream,
CancellationToken.None);
//assert
Assert.True(result > 0);
}
[Fact]
public async Task UpdateAsync_ShouldReturn_UpdatedHelpPage()
{
//arrange
int idHelpPage = new Random().Next(1, 100);
string urlPage = "test";
int newIdCategory = 20000;
string newFileName = "test.pdf";
MemoryStream newFileStream = new MemoryStream(Array.Empty<byte>());
HelpPageDto existingHelpPage = HelpPages.First(x =>
x.UrlPage == urlPage &&
x.IdCategory == newIdCategory);
helpPageRepository.Setup(x => x.GetOrDefaultByUrlPageAndIdCategoryAsync(It.IsAny<string>(),
It.IsAny<int>(), It.IsAny<CancellationToken>()))
.Returns(() => Task.FromResult(existingHelpPage)!);
helpPageRepository.Setup(x => x.InsertAsync(It.IsAny<HelpPageDto>(),
It.IsAny<CancellationToken>()))
.Returns(() => Task.FromResult(idHelpPage));
fileStorageRepository.Setup(x => x.SaveFileAsync(It.IsAny<string>(),
It.IsAny<Stream>(),
It.IsAny<CancellationToken>()));
//act
await helpPageService.AddOrUpdateAsync(urlPage,
newIdCategory,
newFileName,
newFileStream,
CancellationToken.None);
//assert
Assert.Equal(newFileName, existingHelpPage.Name);
Assert.Equal(newIdCategory, existingHelpPage.IdCategory);
Assert.Equal(newFileStream.Length, existingHelpPage.Size);
}
}

View File

@ -1,94 +0,0 @@
using AsbCloudApp.Data;
using AsbCloudApp.Repositories;
using AsbCloudApp.Requests;
using AsbCloudApp.Services;
using AsbCloudDb.Model;
using AsbCloudInfrastructure.Repository;
using AsbCloudInfrastructure.Services;
using Moq;
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace AsbCloudWebApi.Tests.ServicesTests
{
public class LimitingParameterServiceTest
{
private readonly Mock<IAsbCloudDbContext> dbMock;
private readonly ILimitingParameterRepository limitingParameterRepository;
private readonly Mock<IWellService> wellServiceMock;
private readonly LimitingParameterService limitingParameterService;
private readonly WellDto[] wellDtos = new WellDto[] {
new WellDto {
Id = 64,
IdTelemetry = 139,
Timezone = new SimpleTimezoneDto {
Hours = 5,
IsOverride = false
}
}
};
private readonly LimitingParameter[] limitingParametersData = new LimitingParameter[] {
new LimitingParameter{
IdTelemetry = 139,
IdFeedRegulator = 1,
DateStart = DateTimeOffset.Parse("2022-01-02T10:00:00.286Z"),
DateEnd = DateTimeOffset.Parse("2022-01-12T10:00:00.286Z"),
DepthStart = 1000,
DepthEnd = 2000
},
new LimitingParameter{
IdTelemetry = 139,
IdFeedRegulator = 1,
DateStart = DateTimeOffset.Parse("2022-01-12T10:00:00.286Z"),
DateEnd = DateTimeOffset.Parse("2022-01-14T10:00:00.286Z"),
DepthStart = 2000,
DepthEnd = 2500
},
new LimitingParameter{
IdTelemetry = 139,
IdFeedRegulator = 1,
DateStart = DateTimeOffset.Parse("2022-01-14T10:00:00.286Z"),
DateEnd = DateTimeOffset.Parse("2022-01-18T10:00:00.286Z"),
DepthStart = 2500,
DepthEnd = 4000
}
};
private readonly LimitingParameterRequest limitingParameterRequest = new LimitingParameterRequest {
IdWell = 64,
GtDate = DateTime.Parse("2022-01-08T10:00:00.286Z"),
LtDate = DateTime.Parse("2022-01-15T10:00:00.286Z")
};
public LimitingParameterServiceTest()
{
dbMock = new Mock<IAsbCloudDbContext>();
dbMock.AddDbSetMock(limitingParametersData);
limitingParameterRepository = new LimitingParameterRepository(dbMock.Object);
wellServiceMock = new Mock<IWellService>();
wellServiceMock.Setup(x => x.GetOrDefaultAsync(It.IsAny<int>(), It.IsAny<CancellationToken>()))
.Returns((int idWell, CancellationToken token) => {
var data = wellDtos.FirstOrDefault(x => x.Id == idWell);
return Task.FromResult(data);
});
limitingParameterService = new LimitingParameterService(limitingParameterRepository, wellServiceMock.Object);
}
[Fact]
public async Task GetList()
{
var data = await limitingParameterService.GetStatAsync(limitingParameterRequest, CancellationToken.None);
Assert.NotNull(data);
Assert.Single(data);
Assert.Equal(1275, data.First().Depth);
Assert.Equal(10080, data.First().TotalMinutes);
}
}
}

View File

@ -1,129 +0,0 @@
using AsbCloudApp.Data;
using AsbCloudApp.Repositories;
using AsbCloudInfrastructure.Services.Trajectory;
using Moq;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace AsbCloudWebApi.Tests.ServicesTests
{
public class TrajectoryVisualizationServiceTest
{
private Mock<T> MakeTrajectoryRepositoryMock<T, V>(IEnumerable<V> dateForGetMethod)
where V : TrajectoryGeoDto
where T : class, ITrajectoryRepository<V>
{
var mock = new Mock<T>();
mock.Setup(r => r.GetAsync(It.IsAny<int>(), It.IsAny<CancellationToken>()))
.Returns(Task.FromResult(dateForGetMethod));
return mock;
}
[Fact]
public async Task GetTrajectoryAsync_SameCounts()
{
var plannedTrajectory = new TrajectoryGeoPlanDto[]
{
new TrajectoryGeoPlanDto() { WellboreDepth = 0d, ZenithAngle = 0d, AzimuthGeo = 0d },
new TrajectoryGeoPlanDto() { WellboreDepth = 0d, ZenithAngle = 0d, AzimuthGeo = 10d },
new TrajectoryGeoPlanDto() { WellboreDepth = 0d, ZenithAngle = 30d, AzimuthGeo = 20d },
new TrajectoryGeoPlanDto() { WellboreDepth = 30d, ZenithAngle = 0d, AzimuthGeo = 30d },
new TrajectoryGeoPlanDto() { WellboreDepth = 30d, ZenithAngle = 90d, AzimuthGeo = 40d },
new TrajectoryGeoPlanDto() { WellboreDepth = 0d, ZenithAngle = 0d, AzimuthGeo = 50d },
};
var actualTrajectory = new TrajectoryGeoFactDto[]
{
new TrajectoryGeoFactDto() { WellboreDepth = 0, ZenithAngle = 0, AzimuthGeo = 0 },
new TrajectoryGeoFactDto() { WellboreDepth = 30, ZenithAngle = 30, AzimuthGeo = 10 },
new TrajectoryGeoFactDto() { WellboreDepth = 0, ZenithAngle = 0, AzimuthGeo = 20 },
};
var mockPlan = MakeTrajectoryRepositoryMock<ITrajectoryPlanRepository, TrajectoryGeoPlanDto>(plannedTrajectory);
var mockFact = MakeTrajectoryRepositoryMock<ITrajectoryFactRepository, TrajectoryGeoFactDto>(actualTrajectory);
var service = new TrajectoryService(mockPlan.Object, mockFact.Object);
var result = await service.GetTrajectoryCartesianAsync(1, CancellationToken.None);
Assert.Equal(plannedTrajectory.Length, result.Plan?.Count());
Assert.Equal(actualTrajectory.Length, result.Fact?.Count());
}
[Fact]
public async Task GetTrajectoryAsync_StraightBore()
{
var plannedTrajectory = new TrajectoryGeoPlanDto[]
{
new TrajectoryGeoPlanDto() { WellboreDepth = 0, ZenithAngle = 0, AzimuthGeo = 0 },
new TrajectoryGeoPlanDto() { WellboreDepth = 0, ZenithAngle = 0, AzimuthGeo = 0 },
new TrajectoryGeoPlanDto() { WellboreDepth = 20, ZenithAngle = 0, AzimuthGeo = 0 },
new TrajectoryGeoPlanDto() { WellboreDepth = 20, ZenithAngle = 0, AzimuthGeo = 0 },
new TrajectoryGeoPlanDto() { WellboreDepth = 30, ZenithAngle = 0, AzimuthGeo = 0 },
new TrajectoryGeoPlanDto() { WellboreDepth = 50, ZenithAngle = 0, AzimuthGeo = 0 },
};
var actualTrajectory = new TrajectoryGeoFactDto[]
{
new TrajectoryGeoFactDto() { WellboreDepth = 0, ZenithAngle = 0, AzimuthGeo = 0 },
new TrajectoryGeoFactDto() { WellboreDepth = 0, ZenithAngle = 0, AzimuthGeo = 0 },
new TrajectoryGeoFactDto() { WellboreDepth = 20, ZenithAngle = 0, AzimuthGeo = 0 },
new TrajectoryGeoFactDto() { WellboreDepth = 20, ZenithAngle = 0, AzimuthGeo = 0 },
new TrajectoryGeoFactDto() { WellboreDepth = 30, ZenithAngle = 0, AzimuthGeo = 0 },
new TrajectoryGeoFactDto() { WellboreDepth = 50, ZenithAngle = 0, AzimuthGeo = 0 },
};
var mockPlan = MakeTrajectoryRepositoryMock<ITrajectoryPlanRepository, TrajectoryGeoPlanDto>(plannedTrajectory);
var mockFact = MakeTrajectoryRepositoryMock<ITrajectoryFactRepository, TrajectoryGeoFactDto>(actualTrajectory);
var service = new TrajectoryService(mockPlan.Object, mockFact.Object);
var result = await service.GetTrajectoryCartesianAsync(1, CancellationToken.None);
var lastPointPlan = result.Plan!.Last();
var lastPointFact = result.Fact!.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);
}
[Fact]
public async Task GetTrajectoryAsync_Match()
{
var plannedTrajectory = new TrajectoryGeoPlanDto[]
{
new TrajectoryGeoPlanDto() { WellboreDepth = 0, ZenithAngle = 0, AzimuthGeo = 0 },
new TrajectoryGeoPlanDto() { WellboreDepth = 10, ZenithAngle = 30, AzimuthGeo = 30 },
new TrajectoryGeoPlanDto() { WellboreDepth = 20, ZenithAngle = 0, AzimuthGeo = 0 },
};
var actualTrajectory = new TrajectoryGeoFactDto[]
{
new TrajectoryGeoFactDto() { WellboreDepth = 0, ZenithAngle = 0, AzimuthGeo = 0 },
new TrajectoryGeoFactDto() { WellboreDepth = 10, ZenithAngle = 30, AzimuthGeo = 30 },
new TrajectoryGeoFactDto() { WellboreDepth = 20, ZenithAngle = 0, AzimuthGeo = 0 },
};
var mockPlanned = MakeTrajectoryRepositoryMock<ITrajectoryPlanRepository, TrajectoryGeoPlanDto>(plannedTrajectory);
var mockFactual = MakeTrajectoryRepositoryMock<ITrajectoryFactRepository, TrajectoryGeoFactDto>(actualTrajectory);
var service = new TrajectoryService(mockPlanned.Object, mockFactual.Object);
var result = await service.GetTrajectoryCartesianAsync(1, CancellationToken.None);
var lastPointPlan = result.Plan!.Last();
var lastPointFact = result.Fact!.Last();
var tolerancePlan = 0.001d;
var toleranceFact = 0.001d;
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);
}
}
}

View File

@ -1,80 +0,0 @@
using AsbCloudApp.Data;
using AsbCloudApp.Repositories;
using Moq;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace AsbCloudWebApi.Tests.ServicesTests
{
public class WellCompositeRepositoryTest
{
private readonly Mock<IWellCompositeRepository> wellCompositeRepository;
private static List<WellCompositeDto> Data = new List<WellCompositeDto> {
new WellCompositeDto {
IdWell = 90,
IdWellSrc = 4,
IdWellSectionType = 2
},
new WellCompositeDto
{
IdWell = 90,
IdWellSrc = 4,
IdWellSectionType = 3
},
new WellCompositeDto {
IdWell = 90,
IdWellSrc = 44,
IdWellSectionType = 6
},
new WellCompositeDto {
IdWell = 4,
IdWellSrc = 4,
IdWellSectionType = 6
}
};
public WellCompositeRepositoryTest()
{
wellCompositeRepository = new Mock<IWellCompositeRepository>();
wellCompositeRepository.Setup(x => x.GetAsync(It.IsAny<int>(), It.IsAny<CancellationToken>()))
.Returns((int idWell, CancellationToken token) => {
var data = Data.Where(x => x.IdWell == idWell);
return Task.FromResult(data);
});
wellCompositeRepository.Setup(x => x.SaveAsync(It.IsAny<int>(), It.IsAny<IEnumerable<WellCompositeDto>>(), It.IsAny<CancellationToken>()))
.Returns((int idWell, IEnumerable<WellCompositeDto> wellComposites, CancellationToken token) => {
Data.AddRange(wellComposites);
return Task.FromResult(Data.Count);
});
}
[Fact]
public async Task GetAsync_returns_WellCompositeDto()
{
var data = await wellCompositeRepository.Object.GetAsync(90, CancellationToken.None);
Assert.NotNull(data);
}
[Fact]
public async Task SaveAsync()
{
var cnt = Data.Count;
var dtos = new List<WellCompositeDto> {
new WellCompositeDto {
IdWell = 4,
IdWellSrc = 44,
IdWellSectionType = 6
}
};
var result = await wellCompositeRepository.Object.SaveAsync(4, dtos, CancellationToken.None);
Assert.True(cnt < Data.Count);
}
}
}

View File

@ -1,212 +0,0 @@
using AsbCloudApp.Data;
using AsbCloudApp.Services;
using AsbCloudInfrastructure.Services;
using Moq;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
using System.IO;
using System.Linq;
using AsbCloudApp.Repositories;
using System.Collections.Generic;
using AsbCloudApp.Data.User;
using AsbCloudApp.Services.Notifications;
namespace AsbCloudWebApi.Tests.ServicesTests
{
public class WellFinalDocumentsServiceTest
{
private const int validInsertedFileId = 555;
private const int idWellFinalDocCategory = 10_000;
private const string editPublisherPermission = "WellFinalDocuments.editPublisher";
private readonly WellFinalDocumentsService service;
private readonly Mock<IUserRepository> userRepositoryMock;
private readonly Mock<IWellService> wellServiceMock;
private readonly Mock<IFileCategoryService> fileCategoryService;
private readonly NotificationService notificationService;
private readonly Mock<ICrudRepository<NotificationCategoryDto>> notificationCategoryRepositoryMock;
private readonly Mock<INotificationTransportService> notificationTransportServiceMock;
private static readonly UserExtendedDto[] users = new[]{
new UserExtendedDto {
Id = 1,
IdCompany = 1,
Surname = "Tester 1",
Name = "Peppa",
Email = "test@test.com"
},
new UserExtendedDto {
Id = 3,
IdCompany = 1,
Surname = "Tester 3",
Name = "Jourge",
Email = "test1@test1.com"
}
};
private static readonly WellFinalDocumentDto[] wellFinalDocumentDto = new[]
{
new WellFinalDocumentDto {
IdCategory= idWellFinalDocCategory,
PermissionToUpload = true,
Publishers = new List<UserDto> {
new UserDto {
Id = 1
}
}
}
};
private static readonly WellCaseDto wellCaseDto = new WellCaseDto {
IdWell = 1,
PermissionToSetPubliher = true,
WellFinalDocuments = wellFinalDocumentDto
};
private static readonly WellFinalDocumentDBDto wellFinalDocumentDBDto = new WellFinalDocumentDBDto {
IdCategory = idWellFinalDocCategory,
IdUser = 1,
IdWell = 1
};
private readonly Mock<IFileRepository> fileRepositoryMock;
private readonly Mock<IFileStorageRepository> fileStorageRepositoryMock;
private readonly FileService fileService;
private readonly Mock<IWellFinalDocumentsRepository> wellFinalDocumentsRepository;
public WellFinalDocumentsServiceTest()
{
wellFinalDocumentsRepository = new Mock<IWellFinalDocumentsRepository>();
wellFinalDocumentsRepository.Setup(r => r.GetByWellIdAsync(It.IsAny<int>(), It.IsAny<int>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(wellCaseDto);
wellFinalDocumentsRepository.Setup(r => r.GetCategoryAsync(It.IsAny<int>(), It.IsAny<int>(), It.IsAny<int>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(wellFinalDocumentDBDto);
fileRepositoryMock = new Mock<IFileRepository>();
fileRepositoryMock.Setup(r => r.InsertAsync(It.IsAny<FileInfoDto>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(validInsertedFileId);
fileRepositoryMock.Setup(r => r.GetOrDefaultAsync(validInsertedFileId, It.IsAny<CancellationToken>()))
.ReturnsAsync(new FileInfoDto {Id = validInsertedFileId});
fileStorageRepositoryMock = new Mock<IFileStorageRepository>();
fileService = new FileService(fileRepositoryMock.Object, fileStorageRepositoryMock.Object);
userRepositoryMock = new Mock<IUserRepository>();
userRepositoryMock.Setup(x => x.GetAllAsync(It.IsAny<CancellationToken>()))
.ReturnsAsync(users);
userRepositoryMock.Setup(x => x.GetOrDefault(It.IsAny<int>()))
.Returns<int>(id => GetOrDefaultUserById(id));
userRepositoryMock.Setup(x => x.GetOrDefaultAsync(It.IsAny<int>(), It.IsAny<CancellationToken>()))
.ReturnsAsync((int id, CancellationToken token) => GetOrDefaultUserById(id));
UserExtendedDto? GetOrDefaultUserById(int id)
=> users
.Where(u => u.Id == id)
.Select(u => new UserExtendedDto {
Id = u.Id,
IdCompany = u.IdCompany,
Email = u.Email,
Name = u.Name,
Patronymic = u.Patronymic,
Surname = u.Surname,
IdState = u.IdState,
Login = u.Login,
Position = u.Position
})
.FirstOrDefault();
userRepositoryMock.Setup(x => x.HasPermission(users[0].Id, editPublisherPermission))
.Returns(true);
wellServiceMock = new Mock<IWellService>();
wellServiceMock.Setup(s => s.GetOrDefaultAsync(It.IsAny<int>(), It.IsAny<CancellationToken>()))
.ReturnsAsync((int id, CancellationToken _) => new WellDto {
Id = id,
Caption = "well 1",
Cluster = "cluster 1",
Deposit = "deposit 1" });
var configuration = new Microsoft.Extensions.Configuration.ConfigurationBuilder().Build();
notificationCategoryRepositoryMock = new Mock<ICrudRepository<NotificationCategoryDto>>();
notificationCategoryRepositoryMock.Setup(r => r.GetOrDefaultAsync(It.IsAny<int>(),
It.IsAny<CancellationToken>()))
.ReturnsAsync(new NotificationCategoryDto
{
Id = 20000,
Name = "Системные уведомления"
});
notificationTransportServiceMock = new Mock<INotificationTransportService>();
notificationTransportServiceMock.SetupGet(x => x.IdTransportType)
.Returns(1);
notificationService = new NotificationService(notificationCategoryRepositoryMock.Object,
new Mock<INotificationRepository>().Object,
new [] { notificationTransportServiceMock.Object });
fileCategoryService = new Mock<IFileCategoryService>();
fileCategoryService.Setup(s => s.GetOrDefaultAsync(idWellFinalDocCategory, It.IsAny<CancellationToken>()))
.ReturnsAsync((int id, CancellationToken _) => new FileCategoryDto
{
Id = idWellFinalDocCategory,
Name = "Проект на бурение транспортного и горизонтального участков скважины"
});
service = new WellFinalDocumentsService(
fileService: fileService,
userRepository: userRepositoryMock.Object,
wellService: wellServiceMock.Object,
configuration: configuration,
notificationService: notificationService,
fileCategoryService: fileCategoryService.Object,
wellFinalDocumentsRepository: wellFinalDocumentsRepository.Object);
}
[Fact]
public async Task GetHistoryFileByIdCategory_return_empty_hitory()
{
var data = await service.GetFilesHistoryByIdCategoryAsync(1, 13 * idWellFinalDocCategory, CancellationToken.None);
Assert.NotNull(data);
Assert.Empty(data.Files);
}
[Fact]
public async Task SaveCategoryFile_throws_wrong_user()
{
var content = new byte[] {0xAA, 0xBB};
var stream = new MemoryStream(content);
var data = await service.SaveCategoryFileAsync(1, idWellFinalDocCategory, users[0].Id, stream, "test.txt", CancellationToken.None);
Assert.Equal(555, data);
}
[Fact]
public async Task SaveCategoryFile_returns_file_id()
{
var content = new byte[] { 0xAA, 0xBB };
var stream = new MemoryStream(content);
var token = CancellationToken.None;
var idFile = await service.SaveCategoryFileAsync(1, idWellFinalDocCategory, users[0].Id, stream, "test.txt", CancellationToken.None);
Assert.Equal(validInsertedFileId, idFile);
fileRepositoryMock.Verify(m => m.InsertAsync(It.IsAny<FileInfoDto>(), token));
fileStorageRepositoryMock.Verify(m=>m.SaveFileAsync(It.IsAny<string>(), stream, token));
}
[Fact]
public async Task ReNotifyPublishersAsync_deny_to_non_editors()
{
var data = await service.ReNotifyPublishersAsync(1, users[1].Id, idWellFinalDocCategory, CancellationToken.None);
Assert.Equal(1, data);
}
[Fact]
public async Task ReNotifyPublishersAsync_deny_to_non_wrong_category()
{
var data = await service.ReNotifyPublishersAsync(1, users[0].Id, idWellFinalDocCategory, CancellationToken.None);
Assert.Equal(1, data);
}
}
}

View File

@ -1,222 +0,0 @@
using AsbCloudApp.Data;
using AsbCloudApp.Data.SAUB;
using AsbCloudApp.Repositories;
using AsbCloudApp.Requests;
using AsbCloudApp.Services;
using AsbCloudInfrastructure.Services;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace AsbCloudWebApi.Tests.ServicesTests
{
public class WellboreServiceTest
{
private IWellService wellService;
private IWellOperationRepository wellOperationRepository;
private ITelemetryDataCache<TelemetryDataSaubDto> telemetryDataCache;
private WellboreService wellboreService;
private WellDto well1 = new WellDto
{
Id = 1,
IdState = 1,
IdTelemetry = 1,
LastTelemetryDate = DateTime.Now,
Caption = "well 1"
};
private WellDto well2 = new WellDto
{
Id = 2,
IdState = 1,
IdTelemetry = 100,
LastTelemetryDate = DateTime.Now,
Caption = "well 2"
};
public WellboreServiceTest()
{
wellService = Substitute.For<IWellService>();
wellOperationRepository = Substitute.For<IWellOperationRepository>();
telemetryDataCache = Substitute.For<ITelemetryDataCache<TelemetryDataSaubDto>>();
wellboreService = new WellboreService(wellService, wellOperationRepository, telemetryDataCache);
}
[Fact]
public async Task GetWellboresAsync_returns_empty_collection()
{
var result = await wellboreService.GetWellboresAsync(new[] { 1 }, CancellationToken.None);
Assert.NotNull(result);
Assert.False(result.Any());
}
[Fact]
public async Task GetWellboresAsync_returns_one_bore_by_well_only()
{
wellService.GetAsync(Arg.Any<WellRequest>(), Arg.Any<CancellationToken>())
.Returns(new WellDto[] { 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_returns_two_bore_by_two_wells_only()
{
wellService.GetAsync(Arg.Any<WellRequest>(), Arg.Any<CancellationToken>())
.Returns(new WellDto[] { well1, well2 });
var result = await wellboreService.GetWellboresAsync(new[] { 1 }, CancellationToken.None);
Assert.Equal(2, result.Count());
}
[Fact]
public async Task GetWellboresAsync_returns_two_bore_by_well_with_sections()
{
wellService.GetAsync(Arg.Any<WellRequest>(), Arg.Any<CancellationToken>())
.Returns(new WellDto[] { 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 };
wellOperationRepository.GetSectionsAsync(Arg.Any<IEnumerable<int>>(), Arg.Any<CancellationToken>())
.Returns(new SectionByOperationsDto[]{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_returns_one_bore_by_well_with_telemetry()
{
wellService.GetAsync(Arg.Any<WellRequest>(), Arg.Any<CancellationToken>())
.Returns(new WellDto[] { 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, };
telemetryDataCache.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_returns_two_bore_by_well_with_all()
{
wellService.GetAsync(Arg.Any<WellRequest>(), Arg.Any<CancellationToken>())
.Returns(new WellDto[] { 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 };
wellOperationRepository.GetSectionsAsync(Arg.Any<IEnumerable<int>>(), Arg.Any<CancellationToken>())
.Returns(new SectionByOperationsDto[] { 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, };
telemetryDataCache.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);
}
}
}

View File

@ -1,150 +0,0 @@
using AsbCloudInfrastructure.Background;
using Microsoft.Extensions.DependencyInjection;
using NSubstitute;
using System;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace AsbCloudWebApi.Tests.Services
{
public class WorkTest
{
private IServiceProvider provider;
public WorkTest()
{
provider = Substitute.For<IServiceProvider, ISupportRequiredService>();
var serviceScope = Substitute.For<IServiceScope>();
var serviceScopeFactory = Substitute.For<IServiceScopeFactory>();
serviceScopeFactory.CreateScope().Returns(serviceScope);
((ISupportRequiredService)provider).GetRequiredService(typeof(IServiceScopeFactory)).Returns(serviceScopeFactory);
}
[Fact]
public async Task Work_done_with_success()
{
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(provider, 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 Work_calls_callback()
{
var expectedState = "42";
var 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(provider, 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 Work_fails_with_info()
{
var expectedState = "41";
var 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(provider, 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()
{
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(provider, 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(0, work.CountErrors);
Assert.Null(work.LastComplete);
Assert.Null(work.LastError);
}
}
}

View File

@ -1,54 +0,0 @@
using AsbCloudDb.Model;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Memory;
using MockQueryable.Moq;
using Moq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
namespace AsbCloudWebApi.Tests
{
internal static class TestHelpter
{
public static IMemoryCache MemoryCache = new MemoryCache(new MemoryCacheOptions());
public static AsbCloudDbContext MakeRealTestContext()
{
var options = new DbContextOptionsBuilder<AsbCloudDbContext>()
.UseNpgsql("Host=localhost;Database=tests;Username=postgres;Password=q;Persist Security Info=True;Include Error Detail=True")
.Options;
var context = new AsbCloudDbContext(options);
context.Database.EnsureCreated();
return context;
}
public static Mock<IAsbCloudDbContext> AddDbSetMock<T>(this Mock<IAsbCloudDbContext> contextMock, IEnumerable<T> dbSetData)
where T : class
{
var mockDbSet = dbSetData
.ToList()
.AsQueryable()
.BuildMockDbSet();
contextMock.Setup(o => o.Set<T>())
.Returns(mockDbSet.Object);
var dbSetProperty = typeof(IAsbCloudDbContext)
.GetProperties()
.FirstOrDefault(p => p.PropertyType.IsPublic && p.PropertyType == typeof(DbSet<T>));
if (dbSetProperty is not null)
{
// https://learn.microsoft.com/ru-ru/dotnet/api/system.linq.expressions.expression?view=net-7.0
var objParameterExpr = Expression.Parameter(typeof(IAsbCloudDbContext), "instance");
var propertyExpr = Expression.Property(objParameterExpr, dbSetProperty);
var expression = Expression.Lambda<Func<IAsbCloudDbContext, DbSet<T>>>(propertyExpr, objParameterExpr);
contextMock.SetupGet(expression).Returns(mockDbSet.Object);
}
return contextMock;
}
}
}

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.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,16 +1,16 @@
using AsbCloudInfrastructure.Background;
using DocumentFormat.OpenXml.Drawing.Charts;
using Microsoft.Extensions.DependencyInjection;
using NSubstitute;
using System;
using System;
using System.Diagnostics;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using AsbCloudInfrastructure.Background;
using Microsoft.Extensions.DependencyInjection;
using NSubstitute;
using Xunit;
namespace AsbCloudWebApi.Tests.Services;
namespace AsbCloudWebApi.Tests.UnitTests.Background;
//TODO: нужно поправить тесты, иногда они не проходят
public class PeriodicBackgroundWorkerTest
{
private IServiceProvider provider;
@ -35,10 +35,10 @@ public class PeriodicBackgroundWorkerTest
}
[Fact]
public async Task WorkRunsTwice()
public async Task WorkRunsTwice_ShouldReturn_WorkCount()
{
var workCount = 2;
var periodMs = 100d;
const int workCount = 2;
const double periodMs = 100d;
var period = TimeSpan.FromMilliseconds(periodMs);
@ -64,7 +64,7 @@ public class PeriodicBackgroundWorkerTest
[Fact]
public async Task Enqueue_continues_after_exceptions()
public async Task Enqueue_Continues_AfterExceptions()
{
var expectadResult = 42;
var result = 0;

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.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

@ -21,7 +21,7 @@ using AsbCloudInfrastructure.Services.DailyReport;
using NSubstitute;
using Xunit;
namespace AsbCloudWebApi.Tests.Services;
namespace AsbCloudWebApi.Tests.UnitTests.Services;
public class DailyReportServiceTest
{

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.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

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

@ -10,7 +10,7 @@ using Microsoft.Extensions.DependencyInjection;
using NSubstitute;
using Xunit;
namespace AsbCloudWebApi.Tests.ServicesTests.SAUB;
namespace AsbCloudWebApi.Tests.UnitTests.Services.SAUB;
public class TelemetryDataSaubCacheTests
{
@ -60,6 +60,6 @@ public class TelemetryDataSaubCacheTests
var lastTelemetry = telemetryDataCache.GetLastOrDefault(idTelemetry);
//assert
Assert.NotEqual(lastTelemetry, fakeTelemetries.Last());
Assert.Equal(lastTelemetry, fakeTelemetries.Last());
}
}

View File

@ -0,0 +1,147 @@
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using AsbCloudApp.Data;
using AsbCloudApp.Repositories;
using AsbCloudInfrastructure.Services.Trajectory;
using NSubstitute;
using Xunit;
namespace AsbCloudWebApi.Tests.UnitTests.Services;
public class TrajectoryVisualizationServiceTest
{
private readonly ITrajectoryPlanRepository trajectoryPlanRepositoryMock = Substitute.For<ITrajectoryPlanRepository>();
private readonly ITrajectoryFactRepository trajectoryFactRepositoryMock = Substitute.For<ITrajectoryFactRepository>();
private readonly TrajectoryService trajectoryService;
public TrajectoryVisualizationServiceTest()
{
trajectoryService = new TrajectoryService(trajectoryPlanRepositoryMock, trajectoryFactRepositoryMock);
}
[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 },
};
trajectoryPlanRepositoryMock.GetAsync(Arg.Any<int>(), Arg.Any<CancellationToken>())
.ReturnsForAnyArgs(plannedTrajectory);
trajectoryFactRepositoryMock.GetAsync(Arg.Any<int>(), Arg.Any<CancellationToken>())
.ReturnsForAnyArgs(actualTrajectory);
//act
var result = await trajectoryService.GetTrajectoryCartesianAsync(1, CancellationToken.None);
//assert
Assert.Equal(plannedTrajectory.Count(), result.Plan?.Count());
Assert.Equal(actualTrajectory.Count(), result.Fact?.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 },
};
trajectoryPlanRepositoryMock.GetAsync(Arg.Any<int>(), Arg.Any<CancellationToken>())
.ReturnsForAnyArgs(plannedTrajectory);
trajectoryFactRepositoryMock.GetAsync(Arg.Any<int>(), Arg.Any<CancellationToken>())
.ReturnsForAnyArgs(actualTrajectory);
//act
var result = await trajectoryService.GetTrajectoryCartesianAsync(1, CancellationToken.None);
//assert
var lastPointPlan = result.Plan!.Last();
var lastPointFact = result.Fact!.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);
}
[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 },
};
trajectoryPlanRepositoryMock.GetAsync(Arg.Any<int>(), Arg.Any<CancellationToken>())
.ReturnsForAnyArgs(plannedTrajectory);
trajectoryFactRepositoryMock.GetAsync(Arg.Any<int>(), Arg.Any<CancellationToken>())
.ReturnsForAnyArgs(actualTrajectory);
//act
var result = await trajectoryService.GetTrajectoryCartesianAsync(1, CancellationToken.None);
//assert
var lastPointPlan = result.Plan!.Last();
var lastPointFact = result.Fact!.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);
}
}

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.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

@ -0,0 +1,240 @@
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);
}
}

View File

@ -0,0 +1 @@
Доп инфо по тестированию: https://learn.microsoft.com/ru-ru/dotnet/architecture/modern-web-apps-azure/test-asp-net-core-mvc-apps

View File

@ -94,26 +94,4 @@ public class HelpPageController : ControllerBase
return File(file.Value.stream, "application/pdf", file.Value.fileName);
}
/// <summary>
/// Проверяет наличие справки для страницы
/// </summary>
/// <param name="key">Ключ страницы</param>
/// <param name="idCategory">Id категории файла. Допустимое значение параметра: 20000</param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
[HttpGet("isExisting")]
[ProducesResponseType(typeof(bool), (int)HttpStatusCode.OK)]
public async Task<IActionResult> IsExistingAsync(
[Required] string key,
[Range(minimum: 20000, maximum: 20000, ErrorMessage = "Категория файла недопустима. Допустимые: 20000")]
int idCategory,
CancellationToken cancellationToken)
{
var helpPage = await helpPageRepository.GetOrDefaultByUrlPageAndIdCategoryAsync(key,
idCategory,
cancellationToken);
return Ok(helpPage != null);
}
}