17 Commits

Author SHA1 Message Date
IlyasValiulov
e059136a60 лаба 5 усложненная 2025-04-04 08:41:51 +04:00
IlyasValiulov
dc11de1d85 Merge branch 'LabWork03_Storage_Hard' into LabWork04_Api_Hard 2025-04-03 10:57:58 +04:00
IlyasValiulov
c26b7017dc правка3 2025-03-22 15:34:11 +04:00
IlyasValiulov
d725cfc544 правка2 2025-03-22 15:28:06 +04:00
IlyasValiulov
0c05d06346 правка 1 2025-03-22 15:27:11 +04:00
IlyasValiulov
806490a3a4 забыл убрать комментарий 2025-03-22 15:14:46 +04:00
IlyasValiulov
0bd6c0910c правка проверки и списания компонент 2025-03-21 14:04:08 +04:00
IlyasValiulov
1f354d36bc правка storage 2025-03-21 11:38:12 +04:00
IlyasValiulov
1217527e35 лаба 4 2025-03-21 00:07:52 +04:00
IlyasValiulov
56ac4a9851 предварительный коммит 2025-03-20 01:17:51 +04:00
IlyasValiulov
b9f01be873 3 усложенная лаба 2025-03-11 23:05:33 +04:00
IlyasValiulov
12844dc03b Merge branch 'LabWork02_BusinessLogic_Hard' into LabWork03_Storage_Hard 2025-03-07 20:00:20 +04:00
IlyasValiulov
6d0e92cd35 Добавление проверки компонента 2025-03-06 20:39:51 +04:00
IlyasValiulov
ecb621bbbc 2 усложненная 2025-03-03 12:20:37 +04:00
IlyasValiulov
814b878d67 Объединение с первой усложненный веткой 2025-02-21 17:38:18 +04:00
IlyasValiulov
1b10b08b94 Добавление листов для таблицы многих ко многим в классы SuppliesDataModel и WarehouseDataModel 2025-02-21 12:25:24 +04:00
IlyasValiulov
21e7134953 усложненная лаба 2025-02-08 13:02:26 +04:00
135 changed files with 8188 additions and 483 deletions

View File

@@ -11,6 +11,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FurnitureAssemblyBusinessLo
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FurnitureAssemblyDatebase", "FurnitureAssemblyDatebase\FurnitureAssemblyDatebase.csproj", "{BDE6EBBB-E735-408D-B34B-490C2AE9201B}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FurnitureAssemblyWebApi", "FurnitureAssemblyWebApi\FurnitureAssemblyWebApi.csproj", "{17E280FB-248B-4B86-9CAF-40FCE2570BA0}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@@ -33,6 +35,10 @@ Global
{BDE6EBBB-E735-408D-B34B-490C2AE9201B}.Debug|Any CPU.Build.0 = Debug|Any CPU
{BDE6EBBB-E735-408D-B34B-490C2AE9201B}.Release|Any CPU.ActiveCfg = Release|Any CPU
{BDE6EBBB-E735-408D-B34B-490C2AE9201B}.Release|Any CPU.Build.0 = Release|Any CPU
{17E280FB-248B-4B86-9CAF-40FCE2570BA0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{17E280FB-248B-4B86-9CAF-40FCE2570BA0}.Debug|Any CPU.Build.0 = Debug|Any CPU
{17E280FB-248B-4B86-9CAF-40FCE2570BA0}.Release|Any CPU.ActiveCfg = Release|Any CPU
{17E280FB-248B-4B86-9CAF-40FCE2570BA0}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE

View File

@@ -8,6 +8,7 @@
<ItemGroup>
<InternalsVisibleTo Include="FurnitureAssemblyTests" />
<InternalsVisibleTo Include="FurnitureAssemblyWebApi" />
<InternalsVisibleTo Include="DynamicProxyGenAssembly2" />
</ItemGroup>

View File

@@ -8,9 +8,10 @@ using System.Text.Json;
namespace FurnitureAssemblyBusinessLogic.Implementations;
internal class FurnitureBusinessLogicContract(IFurnitureStorageContract furnitureStorageContract, ILogger logger) : IFurnitureBusinessLogicContract
internal class FurnitureBusinessLogicContract(IFurnitureStorageContract furnitureStorageContract, IWarehouseStorageContract warehouseStorageContract, ILogger logger) : IFurnitureBusinessLogicContract
{
IFurnitureStorageContract _furnitureStorageContract = furnitureStorageContract;
IWarehouseStorageContract _warehouseStorageContract = warehouseStorageContract;
private readonly ILogger _logger = logger;
public List<FurnitureDataModel> GetAllFurnitures()
@@ -38,6 +39,10 @@ internal class FurnitureBusinessLogicContract(IFurnitureStorageContract furnitur
_logger.LogInformation("New data: {json}", JsonSerializer.Serialize(furnitureDataModel));
ArgumentNullException.ThrowIfNull(furnitureDataModel);
furnitureDataModel.Validate();
if (!_warehouseStorageContract.CheckComponents(furnitureDataModel))
{
throw new InsufficientException("Dont have component in warehouse");
}
_furnitureStorageContract.AddElement(furnitureDataModel);
}
@@ -46,6 +51,10 @@ internal class FurnitureBusinessLogicContract(IFurnitureStorageContract furnitur
_logger.LogInformation("Update data: {json}", JsonSerializer.Serialize(furnitureDataModel));
ArgumentNullException.ThrowIfNull(furnitureDataModel);
furnitureDataModel.Validate();
if (!_warehouseStorageContract.CheckComponents(furnitureDataModel))
{
throw new InsufficientException("Dont have component in warehouse");
}
_furnitureStorageContract.UpdElement(furnitureDataModel);
}

View File

@@ -27,10 +27,10 @@ internal class PostBusinessLogicContract(IPostStorageContract postStorageContrac
return _postStorageContract.GetPostWithHistory(postId) ?? throw new NullListException();
}
public List<PostDataModel> GetAllPosts(bool onlyActive)
public List<PostDataModel> GetAllPosts()
{
_logger.LogInformation("GetAllPosts params: {onlyActive}", onlyActive);
return _postStorageContract.GetList(onlyActive) ?? throw new NullListException();
_logger.LogInformation("GetAllPosts");
return _postStorageContract.GetList() ?? throw new NullListException();
}
public PostDataModel GetPostByData(string data)

View File

@@ -0,0 +1,52 @@
using FurnitureAssemblyContracts.BusinessLogicsContracts;
using FurnitureAssemblyContracts.DataModels;
using FurnitureAssemblyContracts.Enums;
using FurnitureAssemblyContracts.Exceptions;
using FurnitureAssemblyContracts.Extentions;
using FurnitureAssemblyContracts.StoragesContracts;
using Microsoft.Extensions.Logging;
using System.Text.Json;
namespace FurnitureAssemblyBusinessLogic.Implementations;
public class SuppliesBusinessLogicContract(ISuppliesStorageContract suppliesStorageContract, ILogger logger) : ISuppliesBusinessLogicContract
{
private readonly ISuppliesStorageContract _suppliesStorageContract = suppliesStorageContract;
private readonly ILogger _logger = logger;
public List<SuppliesDataModel> GetAllComponents()
{
_logger.LogInformation("GetAllComponents");
return _suppliesStorageContract.GetList() ?? throw new NullListException();
}
public SuppliesDataModel GetComponentByData(string data)
{
_logger.LogInformation("Get element by data: {data}", data);
if (data.IsEmpty())
{
throw new ArgumentNullException(nameof(data));
}
if (!data.IsGuid())
{
throw new ElementNotFoundException(data);
}
return _suppliesStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data);
}
public void InsertComponent(SuppliesDataModel suppliesDataModel)
{
_logger.LogInformation("New data: {json}", JsonSerializer.Serialize(suppliesDataModel));
ArgumentNullException.ThrowIfNull(suppliesDataModel);
suppliesDataModel.Validate();
_suppliesStorageContract.AddElement(suppliesDataModel);
}
public void UpdateComponent(SuppliesDataModel suppliesDataModel)
{
_logger.LogInformation("Update data: {json}", JsonSerializer.Serialize(suppliesDataModel));
ArgumentNullException.ThrowIfNull(suppliesDataModel);
suppliesDataModel.Validate();
_suppliesStorageContract.UpdElement(suppliesDataModel);
}
}

View File

@@ -0,0 +1,65 @@
using FurnitureAssemblyContracts.BusinessLogicsContracts;
using FurnitureAssemblyContracts.DataModels;
using FurnitureAssemblyContracts.Enums;
using FurnitureAssemblyContracts.Exceptions;
using FurnitureAssemblyContracts.Extentions;
using FurnitureAssemblyContracts.StoragesContracts;
using Microsoft.Extensions.Logging;
using System.Text.Json;
namespace FurnitureAssemblyBusinessLogic.Implementations;
public class WarehouseBusinessLogicContract(IWarehouseStorageContract warehouseStorageContract, ILogger logger) : IWarehouseBusinessLogicContract
{
private readonly IWarehouseStorageContract _warehouseStorageContract = warehouseStorageContract;
private readonly ILogger _logger = logger;
public List<WarehouseDataModel> GetAllComponents()
{
_logger.LogInformation("GetAllComponents");
return _warehouseStorageContract.GetList() ?? throw new NullListException();
}
public WarehouseDataModel GetComponentByData(string data)
{
_logger.LogInformation("Get element by data: {data}", data);
if (data.IsEmpty())
{
throw new ArgumentNullException(nameof(data));
}
if (!data.IsGuid())
{
throw new ElementNotFoundException(data);
}
return _warehouseStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data);
}
public void InsertComponent(WarehouseDataModel warehouseDataModel)
{
_logger.LogInformation("New data: {json}", JsonSerializer.Serialize(warehouseDataModel));
ArgumentNullException.ThrowIfNull(warehouseDataModel);
warehouseDataModel.Validate();
_warehouseStorageContract.AddElement(warehouseDataModel);
}
public void UpdateComponent(WarehouseDataModel warehouseDataModel)
{
_logger.LogInformation("Update data: {json}", JsonSerializer.Serialize(warehouseDataModel));
ArgumentNullException.ThrowIfNull(warehouseDataModel);
warehouseDataModel.Validate();
_warehouseStorageContract.UpdElement(warehouseDataModel);
}
public void DeleteComponent(string id)
{
logger.LogInformation("Delete by id: {id}", id);
if (id.IsEmpty())
{
throw new ArgumentNullException(nameof(id));
}
if (!id.IsGuid())
{
throw new ValidationException("Id is not a unique identifier");
}
_warehouseStorageContract.DelElement(id);
}
}

View File

@@ -10,38 +10,19 @@ namespace FurnitureAssemblyBusinessLogic.Implementations;
internal class WorkerBusinessLogicContract(IWorkerStorageContract workerStorageContract, ILogger logger) : IWorkerBusinessLogicContract
{
private readonly IWorkerStorageContract _workerStorageContract = workerStorageContract;
private readonly ILogger _logger = logger;
private readonly IWorkerStorageContract _workerStorageContract = workerStorageContract;
public List<WorkerDataModel> GetAllWorkers(bool onlyActive = true)
{
logger.LogInformation("GetAllWorkers params: {onlyActive}", onlyActive);
_logger.LogInformation("GetAllWorkers params: {onlyActive}", onlyActive);
return _workerStorageContract.GetList(onlyActive) ?? throw new NullListException();
}
public List<WorkerDataModel> GetAllWorkersByBirthDate(DateTime fromDate, DateTime toDate, bool onlyActive = true)
{
_logger.LogInformation("GetAllWorkers params: {onlyActive}, { fromDate}, { toDate}", onlyActive, fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate);
}
return _workerStorageContract.GetList(onlyActive, fromBirthDate: fromDate, toBirthDate: toDate) ?? throw new NullListException();
}
public List<WorkerDataModel> GetAllWorkersByEmploymentDate(DateTime fromDate, DateTime toDate, bool onlyActive = true)
{
logger.LogInformation("GetAllWorkers params: {onlyActive}, { fromDate}, { toDate}", onlyActive, fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate);
}
return _workerStorageContract.GetList(onlyActive, fromEmploymentDate: fromDate, toEmploymentDate: toDate) ?? throw new NullListException();
}
public List<WorkerDataModel> GetAllWorkersByPost(string postId, bool onlyActive = true)
{
_logger.LogInformation("GetAllWorkers params: {postId}, { onlyActive},", postId, onlyActive);
_logger.LogInformation("GetAllWorkers params: {postId}, {onlyActive},", postId, onlyActive);
if (postId.IsEmpty())
{
throw new ArgumentNullException(nameof(postId));
@@ -53,6 +34,26 @@ internal class WorkerBusinessLogicContract(IWorkerStorageContract workerStorageC
return _workerStorageContract.GetList(onlyActive, postId) ?? throw new NullListException();
}
public List<WorkerDataModel> GetAllWorkersByBirthDate(DateTime fromDate, DateTime toDate, bool onlyActive = true)
{
_logger.LogInformation("GetAllWorkers params: {onlyActive}, {fromDate}, {toDate}", onlyActive, fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate);
}
return _workerStorageContract.GetList(onlyActive, fromBirthDate: fromDate, toBirthDate: toDate) ?? throw new NullListException();
}
public List<WorkerDataModel> GetAllWorkersByEmploymentDate(DateTime fromDate, DateTime toDate, bool onlyActive = true)
{
_logger.LogInformation("GetAllWorkers params: {onlyActive}, {fromDate}, {toDate}", onlyActive, fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate);
}
return _workerStorageContract.GetList(onlyActive, fromEmploymentDate: fromDate, toEmploymentDate: toDate) ?? throw new NullListException();
}
public WorkerDataModel GetWorkerByData(string data)
{
_logger.LogInformation("Get element by data: {data}", data);
@@ -78,7 +79,7 @@ internal class WorkerBusinessLogicContract(IWorkerStorageContract workerStorageC
public void UpdateWorker(WorkerDataModel workerDataModel)
{
logger.LogInformation("Update data: {json}", JsonSerializer.Serialize(workerDataModel));
_logger.LogInformation("Update data: {json}", JsonSerializer.Serialize(workerDataModel));
ArgumentNullException.ThrowIfNull(workerDataModel);
workerDataModel.Validate();
_workerStorageContract.UpdElement(workerDataModel);

View File

@@ -0,0 +1,13 @@
using FurnitureAssemblyContracts.AdapterContracts.OperationResponses;
using FurnitureAssemblyContracts.BindingModels;
namespace FurnitureAssemblyContracts.AdapterContracts;
public interface IComponentAdapter
{
ComponentOperationResponse GetAllComponents();
ComponentOperationResponse GetComponentByData(string data);
ComponentOperationResponse InsertComponent(ComponentBindingModel componentDataModel);
ComponentOperationResponse UpdateComponent(ComponentBindingModel componentDataModel);
ComponentOperationResponse DeleteComponent(string id);
}

View File

@@ -0,0 +1,14 @@
using FurnitureAssemblyContracts.AdapterContracts.OperationResponses;
using FurnitureAssemblyContracts.BindingModels;
using FurnitureAssemblyContracts.DataModels;
namespace FurnitureAssemblyContracts.AdapterContracts;
public interface IFurnitureAdapter
{
FurnitureOperationResponse GetAllFurnitures();
FurnitureOperationResponse GetFurnitureByData(string data);
FurnitureOperationResponse InsertFurniture(FurnitureBindingModel furnitureDataModel);
FurnitureOperationResponse UpdateFurniture(FurnitureBindingModel furnitureDataModel);
FurnitureOperationResponse DeleteFurniture(string id);
}

View File

@@ -0,0 +1,14 @@
using FurnitureAssemblyContracts.AdapterContracts.OperationResponses;
using FurnitureAssemblyContracts.BindingModels;
namespace FurnitureAssemblyContracts.AdapterContracts;
public interface IManifacturingFurnitureAdapter
{
ManifacturingFurnitureOperationResponse GetList(DateTime fromDate, DateTime toDate);
ManifacturingFurnitureOperationResponse GetAllManifacturingByWorkerByPeriod(string workerId, DateTime fromDate, DateTime toDate);
ManifacturingFurnitureOperationResponse GetAllManifacturingByFurnitureByPeriod(string furnitureId, DateTime fromDate, DateTime toDate);
ManifacturingFurnitureOperationResponse GetElement(string data);
ManifacturingFurnitureOperationResponse RegisterManifacturingFurniture(ManifacturingFurnitureBindingModel model);
ManifacturingFurnitureOperationResponse ChangeManifacturingFurniture(ManifacturingFurnitureBindingModel model);
}

View File

@@ -0,0 +1,15 @@
using FurnitureAssemblyContracts.AdapterContracts.OperationResponses;
using FurnitureAssemblyContracts.BindingModels;
namespace FurnitureAssemblyContracts.AdapterContracts;
public interface IPostAdapter
{
PostOperationResponse GetList();
PostOperationResponse GetHistory(string id);
PostOperationResponse GetElement(string data);
PostOperationResponse RegisterPost(PostBindingModel postModel);
PostOperationResponse ChangePostInfo(PostBindingModel postModel);
PostOperationResponse RemovePost(string id);
PostOperationResponse RestorePost(string id);
}

View File

@@ -0,0 +1,10 @@
using FurnitureAssemblyContracts.AdapterContracts.OperationResponses;
namespace FurnitureAssemblyContracts.AdapterContracts;
public interface ISalaryAdapter
{
SalaryOperationResponse GetListByPeriod(DateTime fromDate, DateTime toDate);
SalaryOperationResponse GetListByPeriodByWorker(DateTime fromDate, DateTime toDate, string workerId);
SalaryOperationResponse CalculateSalary(DateTime date);
}

View File

@@ -0,0 +1,13 @@
using FurnitureAssemblyContracts.AdapterContracts.OperationResponses;
using FurnitureAssemblyContracts.BindingModels;
using FurnitureAssemblyContracts.DataModels;
namespace FurnitureAssemblyContracts.AdapterContracts;
public interface ISuppliesAdapter
{
SuppliesOperationResponse GetAllComponents();
SuppliesOperationResponse GetComponentByData(string data);
SuppliesOperationResponse InsertComponent(SuppliesBindingModel componentDataModel);
SuppliesOperationResponse UpdateComponent(SuppliesBindingModel componentDataModel);
}

View File

@@ -0,0 +1,13 @@
using FurnitureAssemblyContracts.AdapterContracts.OperationResponses;
using FurnitureAssemblyContracts.BindingModels;
namespace FurnitureAssemblyContracts.AdapterContracts;
public interface IWarehouseAdapter
{
WarehouseOperationResponse GetAllComponents();
WarehouseOperationResponse GetComponentByData(string data);
WarehouseOperationResponse InsertComponent(WarehouseBindingModel warehouseDataModel);
WarehouseOperationResponse UpdateComponent(WarehouseBindingModel warehouseDataModel);
WarehouseOperationResponse DeleteComponent(string id);
}

View File

@@ -0,0 +1,23 @@
using FurnitureAssemblyContracts.AdapterContracts.OperationResponses;
using FurnitureAssemblyContracts.BindingModels;
namespace FurnitureAssemblyContracts.AdapterContracts;
public interface IWorkerAdapter
{
WorkerOperationResponse GetList(bool includeDeleted);
WorkerOperationResponse GetPostList(string id, bool includeDeleted);
WorkerOperationResponse GetListByBirthDate(DateTime fromDate, DateTime toDate, bool includeDeleted);
WorkerOperationResponse GetListByEmploymentDate(DateTime fromDate, DateTime toDate, bool includeDeleted);
WorkerOperationResponse GetElement(string data);
WorkerOperationResponse RegisterWorker(WorkerBindingModel workerModel);
WorkerOperationResponse ChangeWorkerInfo(WorkerBindingModel workerModel);
WorkerOperationResponse RemoveWorker(string id);
}

View File

@@ -0,0 +1,19 @@
using FurnitureAssemblyContracts.Infrastructure;
using FurnitureAssemblyContracts.ViewModels;
namespace FurnitureAssemblyContracts.AdapterContracts.OperationResponses;
public class ComponentOperationResponse : OperationResponse
{
public static ComponentOperationResponse OK(List<ComponentViewModel> data) => OK<ComponentOperationResponse, List<ComponentViewModel>>(data);
public static ComponentOperationResponse OK(ComponentViewModel data) => OK<ComponentOperationResponse, ComponentViewModel>(data);
public static ComponentOperationResponse NoContent() => NoContent<ComponentOperationResponse>();
public static ComponentOperationResponse NotFound(string message) => NotFound<ComponentOperationResponse>(message);
public static ComponentOperationResponse BadRequest(string message) => BadRequest<ComponentOperationResponse>(message);
public static ComponentOperationResponse InternalServerError(string message) => InternalServerError<ComponentOperationResponse>(message);
}

View File

@@ -0,0 +1,19 @@
using FurnitureAssemblyContracts.Infrastructure;
using FurnitureAssemblyContracts.ViewModels;
namespace FurnitureAssemblyContracts.AdapterContracts.OperationResponses;
public class FurnitureOperationResponse : OperationResponse
{
public static FurnitureOperationResponse OK(List<FurnitureViewModel> data) => OK<FurnitureOperationResponse, List<FurnitureViewModel>>(data);
public static FurnitureOperationResponse OK(FurnitureViewModel data) => OK<FurnitureOperationResponse, FurnitureViewModel>(data);
public static FurnitureOperationResponse NoContent() => NoContent<FurnitureOperationResponse>();
public static FurnitureOperationResponse NotFound(string message) => NotFound<FurnitureOperationResponse>(message);
public static FurnitureOperationResponse BadRequest(string message) => BadRequest<FurnitureOperationResponse>(message);
public static FurnitureOperationResponse InternalServerError(string message) => InternalServerError<FurnitureOperationResponse>(message);
}

View File

@@ -0,0 +1,25 @@
using FurnitureAssemblyContracts.Infrastructure;
using FurnitureAssemblyContracts.ViewModels;
namespace FurnitureAssemblyContracts.AdapterContracts.OperationResponses;
public class ManifacturingFurnitureOperationResponse : OperationResponse
{
public static ManifacturingFurnitureOperationResponse OK(List<ManifacturingFurnitureViewModel> data) =>
OK<ManifacturingFurnitureOperationResponse, List<ManifacturingFurnitureViewModel>>(data);
public static ManifacturingFurnitureOperationResponse OK(ManifacturingFurnitureViewModel data) =>
OK<ManifacturingFurnitureOperationResponse, ManifacturingFurnitureViewModel>(data);
public static ManifacturingFurnitureOperationResponse NoContent() =>
NoContent<ManifacturingFurnitureOperationResponse>();
public static ManifacturingFurnitureOperationResponse NotFound(string message) =>
NotFound<ManifacturingFurnitureOperationResponse>(message);
public static ManifacturingFurnitureOperationResponse BadRequest(string message) =>
BadRequest<ManifacturingFurnitureOperationResponse>(message);
public static ManifacturingFurnitureOperationResponse InternalServerError(string message) =>
InternalServerError<ManifacturingFurnitureOperationResponse>(message);
}

View File

@@ -0,0 +1,19 @@
using FurnitureAssemblyContracts.Infrastructure;
using FurnitureAssemblyContracts.ViewModels;
namespace FurnitureAssemblyContracts.AdapterContracts.OperationResponses;
public class PostOperationResponse : OperationResponse
{
public static PostOperationResponse OK(List<PostViewModel> data) => OK<PostOperationResponse, List<PostViewModel>>(data);
public static PostOperationResponse OK(PostViewModel data) => OK<PostOperationResponse, PostViewModel>(data);
public static PostOperationResponse NoContent() => NoContent<PostOperationResponse>();
public static PostOperationResponse NotFound(string message) => NotFound<PostOperationResponse>(message);
public static PostOperationResponse BadRequest(string message) => BadRequest<PostOperationResponse>(message);
public static PostOperationResponse InternalServerError(string message) => InternalServerError<PostOperationResponse>(message);
}

View File

@@ -0,0 +1,13 @@
using FurnitureAssemblyContracts.Infrastructure;
using FurnitureAssemblyContracts.ViewModels;
namespace FurnitureAssemblyContracts.AdapterContracts.OperationResponses;
public class SalaryOperationResponse : OperationResponse
{
public static SalaryOperationResponse OK(List<SalaryViewModel> data) => OK<SalaryOperationResponse, List<SalaryViewModel>>(data);
public static SalaryOperationResponse NoContent() => NoContent<SalaryOperationResponse>();
public static SalaryOperationResponse NotFound(string message) => NotFound<SalaryOperationResponse>(message);
public static SalaryOperationResponse BadRequest(string message) => BadRequest<SalaryOperationResponse>(message);
public static SalaryOperationResponse InternalServerError(string message) => InternalServerError<SalaryOperationResponse>(message);
}

View File

@@ -0,0 +1,19 @@
using FurnitureAssemblyContracts.Infrastructure;
using FurnitureAssemblyContracts.ViewModels;
namespace FurnitureAssemblyContracts.AdapterContracts.OperationResponses;
public class SuppliesOperationResponse : OperationResponse
{
public static SuppliesOperationResponse OK(List<SuppliesViewModel> data) => OK<SuppliesOperationResponse, List<SuppliesViewModel>>(data);
public static SuppliesOperationResponse OK(SuppliesViewModel data) => OK<SuppliesOperationResponse, SuppliesViewModel>(data);
public static SuppliesOperationResponse NoContent() => NoContent<SuppliesOperationResponse>();
public static SuppliesOperationResponse NotFound(string message) => NotFound<SuppliesOperationResponse>(message);
public static SuppliesOperationResponse BadRequest(string message) => BadRequest<SuppliesOperationResponse>(message);
public static SuppliesOperationResponse InternalServerError(string message) => InternalServerError<SuppliesOperationResponse>(message);
}

View File

@@ -0,0 +1,19 @@
using FurnitureAssemblyContracts.Infrastructure;
using FurnitureAssemblyContracts.ViewModels;
namespace FurnitureAssemblyContracts.AdapterContracts.OperationResponses;
public class WarehouseOperationResponse : OperationResponse
{
public static WarehouseOperationResponse OK(List<WarehouseViewModel> data) => OK<WarehouseOperationResponse, List<WarehouseViewModel>>(data);
public static WarehouseOperationResponse OK(WarehouseViewModel data) => OK<WarehouseOperationResponse, WarehouseViewModel>(data);
public static WarehouseOperationResponse NoContent() => NoContent<WarehouseOperationResponse>();
public static WarehouseOperationResponse NotFound(string message) => NotFound<WarehouseOperationResponse>(message);
public static WarehouseOperationResponse BadRequest(string message) => BadRequest<WarehouseOperationResponse>(message);
public static WarehouseOperationResponse InternalServerError(string message) => InternalServerError<WarehouseOperationResponse>(message);
}

View File

@@ -0,0 +1,19 @@
using FurnitureAssemblyContracts.Infrastructure;
using FurnitureAssemblyContracts.ViewModels;
namespace FurnitureAssemblyContracts.AdapterContracts.OperationResponses;
public class WorkerOperationResponse : OperationResponse
{
public static WorkerOperationResponse OK(List<WorkerViewModel> data) => OK<WorkerOperationResponse, List<WorkerViewModel>>(data);
public static WorkerOperationResponse OK(WorkerViewModel data) => OK<WorkerOperationResponse, WorkerViewModel>(data);
public static WorkerOperationResponse NoContent() => NoContent<WorkerOperationResponse>();
public static WorkerOperationResponse NotFound(string message) => NotFound<WorkerOperationResponse>(message);
public static WorkerOperationResponse BadRequest(string message) => BadRequest<WorkerOperationResponse>(message);
public static WorkerOperationResponse InternalServerError(string message) => InternalServerError<WorkerOperationResponse>(message);
}

View File

@@ -0,0 +1,11 @@
using FurnitureAssemblyContracts.Enums;
using System.Xml.Linq;
namespace FurnitureAssemblyContracts.BindingModels;
public class ComponentBindingModel
{
public string? Id { get; set; }
public string? Name { get; set; }
public ComponentType? Type { get; set; }
}

View File

@@ -0,0 +1,8 @@
namespace FurnitureAssemblyContracts.BindingModels;
public class ComponentSuppliesBindingModel
{
public string? SuppliesId { get; set; }
public string? ComponentId { get; set; }
public int Count { get; set; }
}

View File

@@ -0,0 +1,8 @@
namespace FurnitureAssemblyContracts.BindingModels;
public class ComponentWarehouseBindingModel
{
public string? WarehouseId { get; set; }
public string? ComponentId { get; set; }
public int Count { get; set; }
}

View File

@@ -0,0 +1,9 @@
namespace FurnitureAssemblyContracts.BindingModels;
public class FurnitureBindingModel
{
public string? Id { get; set; }
public string? Name { get; set; }
public int Weight { get; set; }
public List<FurnitureComponentBindingModel>? Components { get; set; }
}

View File

@@ -0,0 +1,8 @@
namespace FurnitureAssemblyContracts.BindingModels;
public class FurnitureComponentBindingModel
{
public string? FurnitureId { get; set; }
public string? ComponentId { get; set; }
public int Count { get; set; }
}

View File

@@ -0,0 +1,10 @@
namespace FurnitureAssemblyContracts.BindingModels;
public class ManifacturingFurnitureBindingModel
{
public string? Id { get; set; }
public string? FurnitureId { get; set; }
public int Count { get; set; }
public DateTime ProductionDate { get; set; }
public string? WorkerId { get; set; }
}

View File

@@ -0,0 +1,10 @@
namespace FurnitureAssemblyContracts.BindingModels;
public class PostBindingModel
{
public string? Id { get; set; }
public string? PostId => Id;
public string? PostName { get; set; }
public string? PostType { get; set; }
public double Salary { get; set; }
}

View File

@@ -0,0 +1,12 @@
using FurnitureAssemblyContracts.Enums;
namespace FurnitureAssemblyContracts.BindingModels;
public class SuppliesBindingModel
{
public string? Id { get; set; }
public ComponentType? Type { get; set; }
public DateTime ProductuionDate { get; set; }
public int Count { get; set; }
public List<ComponentSuppliesBindingModel>? Components { get; set; }
}

View File

@@ -0,0 +1,11 @@
using FurnitureAssemblyContracts.Enums;
namespace FurnitureAssemblyContracts.BindingModels;
public class WarehouseBindingModel
{
public string? Id { get; set; }
public ComponentType? Type { get; set; }
public int Count { get; set; }
public List<ComponentWarehouseBindingModel>? Components { get; set; }
}

View File

@@ -0,0 +1,10 @@
namespace FurnitureAssemblyContracts.BindingModels;
public class WorkerBindingModel
{
public string? Id { get; set; }
public string? FIO { get; set; }
public string? PostId { get; set; }
public DateTime BirthDate { get; set; }
public DateTime EmploymentDate { get; set; }
}

View File

@@ -4,7 +4,7 @@ namespace FurnitureAssemblyContracts.BusinessLogicsContracts;
public interface IPostBusinessLogicContract
{
List<PostDataModel> GetAllPosts(bool onlyActive);
List<PostDataModel> GetAllPosts();
List<PostDataModel> GetAllDataOfPost(string postId);
PostDataModel GetPostByData(string data);
void InsertPost(PostDataModel postDataModel);

View File

@@ -0,0 +1,11 @@
using FurnitureAssemblyContracts.DataModels;
namespace FurnitureAssemblyContracts.BusinessLogicsContracts;
public interface ISuppliesBusinessLogicContract
{
List<SuppliesDataModel> GetAllComponents();
SuppliesDataModel GetComponentByData(string data);
void InsertComponent(SuppliesDataModel componentDataModel);
void UpdateComponent(SuppliesDataModel componentDataModel);
}

View File

@@ -0,0 +1,12 @@
using FurnitureAssemblyContracts.DataModels;
namespace FurnitureAssemblyContracts.BusinessLogicsContracts;
public interface IWarehouseBusinessLogicContract
{
List<WarehouseDataModel> GetAllComponents();
WarehouseDataModel GetComponentByData(string data);
void InsertComponent(WarehouseDataModel warehouseDataModel);
void UpdateComponent(WarehouseDataModel warehouseDataModel);
void DeleteComponent(string id);
}

View File

@@ -0,0 +1,26 @@
using FurnitureAssemblyContracts.Exceptions;
using FurnitureAssemblyContracts.Extentions;
using FurnitureAssemblyContracts.Infrastructure;
namespace FurnitureAssemblyContracts.DataModels;
public class ComponentSuppliesDataModel(string suppliesId, string componentId, int count) : IValidation
{
public string SuppliesId { get; private set; } = suppliesId;
public string ComponentId { get; private set; } = componentId;
public int Count { get; private set; } = count;
public void Validate()
{
if (SuppliesId.IsEmpty())
throw new ValidationException("Field FurnitureId is empty");
if (!SuppliesId.IsGuid())
throw new ValidationException("The value in the field FurnitureId is not a unique identifier");
if (ComponentId.IsEmpty())
throw new ValidationException("Field ComponentId is empty");
if (!ComponentId.IsGuid())
throw new ValidationException("The value in the field BlandId is not a unique identifier");
if (Count <= 0)
throw new ValidationException("Field Count is less than or equal to 0");
}
}

View File

@@ -0,0 +1,26 @@
using FurnitureAssemblyContracts.Exceptions;
using FurnitureAssemblyContracts.Extentions;
using FurnitureAssemblyContracts.Infrastructure;
namespace FurnitureAssemblyContracts.DataModels;
public class ComponentWarehouseDataModel(string warehouseId, string componentId, int count) : IValidation
{
public string WarehouseId { get; private set; } = warehouseId;
public string ComponentId { get; private set; } = componentId;
public int Count { get; private set; } = count;
public void Validate()
{
if (WarehouseId.IsEmpty())
throw new ValidationException("Field WarehouseId is empty");
if (!WarehouseId.IsGuid())
throw new ValidationException("The value in the field WarehouseId is not a unique identifier");
if (ComponentId.IsEmpty())
throw new ValidationException("Field ComponentId is empty");
if (!ComponentId.IsGuid())
throw new ValidationException("The value in the field ComponentId is not a unique identifier");
if (Count <= 0)
throw new ValidationException("Field Count is less than or equal to 0");
}
}

View File

@@ -4,13 +4,32 @@ using FurnitureAssemblyContracts.Infrastructure;
namespace FurnitureAssemblyContracts.DataModels;
public class ManifacturingFurnitureDataModel(string id, string furnitureId, int count, string workerId) : IValidation
public class ManifacturingFurnitureDataModel : IValidation
{
public string Id { get; private set; } = id;
public string FurnitureId { get; private set; } = furnitureId;
public int Count { get; private set; } = count;
private readonly WorkerDataModel? _worker;
private readonly FurnitureDataModel? _furniture;
public string Id { get; private set; }
public string FurnitureId { get; private set; }
public int Count { get; private set; }
public DateTime ProductuionDate { get; private set; } = DateTime.UtcNow;
public string WorkerId { get; private set; } = workerId;
public string WorkerId { get; private set; }
public string WorkerFIO => _worker?.FIO ?? string.Empty;
public string FurnitureName => _furniture?.Name ?? string.Empty;
public ManifacturingFurnitureDataModel(string id, string furnitureId, int count, string workerId)
{
Id = id;
FurnitureId = furnitureId;
Count = count;
WorkerId = workerId;
}
public ManifacturingFurnitureDataModel(string id, string furnitureId, int count, string workerId, WorkerDataModel worker, FurnitureDataModel furniture)
: this(id, furnitureId, count, workerId)
{
_worker = worker;
_furniture = furniture;
}
public void Validate()
{

View File

@@ -5,14 +5,12 @@ using FurnitureAssemblyContracts.Infrastructure;
namespace FurnitureAssemblyContracts.DataModels;
public class PostDataModel(string postid, string postName, PostType postType, double salary, bool isActual, DateTime changeDate) : IValidation
public class PostDataModel(string postid, string postName, PostType postType, double salary) : IValidation
{
public string Id { get; private set; } = postid;
public string PostName { get; private set; } = postName;
public PostType PostType { get; private set; } = postType;
public double Salary { get; private set; } = salary;
public bool IsActual { get; private set; } = isActual;
public DateTime ChangeDate { get; private set; } = changeDate;
public void Validate()
{

View File

@@ -6,9 +6,16 @@ namespace FurnitureAssemblyContracts.DataModels;
public class SalaryDataModel(string workerId, DateTime salaryDate, double workerSalary) : IValidation
{
private readonly WorkerDataModel? _worker;
public string WorkerId { get; private set; } = workerId;
public DateTime SalaryDate { get; private set; } = salaryDate;
public double Salary { get; private set; } = workerSalary;
public string WorkerFIO => _worker?.FIO ?? string.Empty;
public SalaryDataModel(string workerId, DateTime salaryDate, double workerSalary, WorkerDataModel worker) : this(workerId, salaryDate, workerSalary)
{
_worker = worker;
}
public void Validate()
{

View File

@@ -0,0 +1,29 @@
using FurnitureAssemblyContracts.Enums;
using FurnitureAssemblyContracts.Exceptions;
using FurnitureAssemblyContracts.Extentions;
using FurnitureAssemblyContracts.Infrastructure;
namespace FurnitureAssemblyContracts.DataModels;
public class SuppliesDataModel(string id, ComponentType type, DateTime productuionDate, int count, List<ComponentSuppliesDataModel> components) : IValidation
{
public string Id { get; private set; } = id;
public ComponentType Type { get; private set; } = type;
public DateTime ProductuionDate { get; private set; } = productuionDate;
public int Count { get; private set; } = count;
public List<ComponentSuppliesDataModel> Components { get; private set; } = components;
public void Validate()
{
if (Id.IsEmpty())
throw new ValidationException("Field Id is empty");
if (!Id.IsGuid())
throw new ValidationException("The value in the field Id is not a unique identifier");
if (Type == ComponentType.None)
throw new ValidationException("Field Type is empty");
if (Count <= 0)
throw new ValidationException("Field Count is less than or equal to 0");
if ((Components?.Count ?? 0) == 0)
throw new ValidationException("The component must include supplies");
}
}

View File

@@ -0,0 +1,28 @@
using FurnitureAssemblyContracts.Enums;
using FurnitureAssemblyContracts.Exceptions;
using FurnitureAssemblyContracts.Extentions;
using FurnitureAssemblyContracts.Infrastructure;
namespace FurnitureAssemblyContracts.DataModels;
public class WarehouseDataModel(string id, ComponentType type, int count, List<ComponentWarehouseDataModel> components) : IValidation
{
public string Id { get; private set; } = id;
public ComponentType Type { get; private set; } = type;
public int Count { get; private set; } = count;
public List<ComponentWarehouseDataModel> Components { get; private set; } = components;
public void Validate()
{
if (Id.IsEmpty())
throw new ValidationException("Field Id is empty");
if (!Id.IsGuid())
throw new ValidationException("The value in the field Id is not a unique identifier");
if (Type == ComponentType.None)
throw new ValidationException("Field Type is empty");
if (Count <= 0)
throw new ValidationException("Field Count is less than or equal to 0");
if ((Components?.Count ?? 0) == 0)
throw new ValidationException("The component must include supplies");
}
}

View File

@@ -7,32 +7,56 @@ namespace FurnitureAssemblyContracts.DataModels;
public class WorkerDataModel(string id, string fio, string postId, DateTime birthDate, DateTime employmentDate, bool isDeleted) : IValidation
{
private readonly PostDataModel? _post;
public string Id { get; private set; } = id;
public string FIO { get; private set; } = fio;
public string PostId { get; private set; } = postId;
public DateTime BirthDate { get; private set; } = birthDate;
public DateTime EmploymentDate { get; private set; } = employmentDate;
public bool IsDeleted { get; private set; } = isDeleted;
public string PostName => _post?.PostName ?? string.Empty;
public WorkerDataModel(string id, string fio, string postId, DateTime birthDate, DateTime employmentDate, bool isDeleted, PostDataModel post) : this(id, fio, postId, birthDate, employmentDate, isDeleted)
{
_post = post;
}
public WorkerDataModel(string id, string fio, string postId, DateTime birthDate, DateTime employmentDate) : this(id, fio, postId, birthDate, employmentDate, false) { }
public void Validate()
{
if (Id.IsEmpty())
throw new ValidationException("Field Id is empty");
if (!Id.IsGuid())
throw new ValidationException("The value in the field Id is not a unique identifier");
if (FIO.IsEmpty())
throw new ValidationException("Field FIO is empty");
if (!Regex.IsMatch(FIO, @"^([А-ЯЁ][а-яё]*(-[А-ЯЁ][а-яё]*)?)\s([А-ЯЁ]\.?\s?([А-ЯЁ]\.?\s?)?)?$"))
throw new ValidationException("Field FIO is not a fio");
if (PostId.IsEmpty())
throw new ValidationException("Field PostId is empty");
if (!PostId.IsGuid())
throw new ValidationException("The value in the field PostId is not a unique identifier");
if (BirthDate.Date > DateTime.Now.AddYears(-14).Date)
throw new ValidationException($"Minors cannot be hired (BirthDate = {BirthDate.ToShortDateString()})");
if (EmploymentDate.Date < BirthDate.Date)
throw new ValidationException("The date of employment cannot be less than the date of birth");
if ((EmploymentDate - BirthDate).TotalDays / 365 < 14)
throw new ValidationException($"Minors cannot be hired (EmploymentDate - {EmploymentDate.ToShortDateString()}, BirthDate -{BirthDate.ToShortDateString()})");
if ((EmploymentDate - BirthDate).TotalDays / 365 < 14) // EmploymentDate.Year - BirthDate.Year
throw new ValidationException($"Minors cannot be hired (EmploymentDate - {EmploymentDate.ToShortDateString()}, BirthDate - {BirthDate.ToShortDateString()})");
}
}

View File

@@ -0,0 +1,5 @@
namespace FurnitureAssemblyContracts.Exceptions;
public class InsufficientException(string message) : Exception(message)
{
}

View File

@@ -6,4 +6,10 @@
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Mvc.Abstractions" Version="2.3.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Core" Version="2.3.0" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,38 @@
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Net;
namespace FurnitureAssemblyContracts.Infrastructure;
public class OperationResponse
{
public HttpStatusCode StatusCode { get; set; }
public object? Result { get; set; }
public IActionResult GetResponse(HttpRequest request, HttpResponse response)
{
ArgumentNullException.ThrowIfNull(request);
ArgumentNullException.ThrowIfNull(response);
response.StatusCode = (int)StatusCode;
if (Result is null)
{
return new StatusCodeResult((int)StatusCode);
}
return new ObjectResult(Result);
}
protected static TResult OK<TResult, TData>(TData data) where TResult :
OperationResponse, new() => new() { StatusCode = HttpStatusCode.OK, Result = data };
protected static TResult NoContent<TResult>() where TResult : OperationResponse, new() => new() { StatusCode = HttpStatusCode.NoContent };
protected static TResult BadRequest<TResult>(string? errorMessage = null)
where TResult : OperationResponse, new() => new() { StatusCode = HttpStatusCode.BadRequest, Result = errorMessage };
protected static TResult NotFound<TResult>(string? errorMessage = null)
where TResult : OperationResponse, new() => new() { StatusCode = HttpStatusCode.NotFound, Result = errorMessage };
protected static TResult InternalServerError<TResult>(string? errorMessage = null)
where TResult : OperationResponse, new() => new() { StatusCode = HttpStatusCode.InternalServerError, Result = errorMessage };
}

View File

@@ -4,7 +4,7 @@ namespace FurnitureAssemblyContracts.StoragesContracts;
public interface IPostStorageContract
{
List<PostDataModel> GetList(bool onlyActual = true);
List<PostDataModel> GetList();
List<PostDataModel> GetPostWithHistory(string postId);
PostDataModel? GetElementById(string id);
PostDataModel? GetElementByName(string name);

View File

@@ -0,0 +1,11 @@
using FurnitureAssemblyContracts.DataModels;
namespace FurnitureAssemblyContracts.StoragesContracts;
public interface ISuppliesStorageContract
{
List<SuppliesDataModel> GetList(DateTime? startDate = null);
SuppliesDataModel GetElementById(string id);
void AddElement(SuppliesDataModel suppliesDataModel);
void UpdElement(SuppliesDataModel suppliesDataModel);
}

View File

@@ -0,0 +1,13 @@
using FurnitureAssemblyContracts.DataModels;
namespace FurnitureAssemblyContracts.StoragesContracts;
public interface IWarehouseStorageContract
{
List<WarehouseDataModel> GetList();
WarehouseDataModel GetElementById(string id);
void AddElement(WarehouseDataModel warehouseDataModel);
void UpdElement(WarehouseDataModel warehouseDataModel);
void DelElement(string id);
bool CheckComponents(FurnitureDataModel furnitureDataModel);
}

View File

@@ -0,0 +1,8 @@
namespace FurnitureAssemblyContracts.ViewModels;
public class ComponentSuppliesViewModel
{
public required string SuppliesId { get; set; }
public required string ComponentId { get; set; }
public int Count { get; set; }
}

View File

@@ -0,0 +1,12 @@
using FurnitureAssemblyContracts.Enums;
namespace FurnitureAssemblyContracts.ViewModels;
public class ComponentViewModel
{
public required string Id { get; set; }
public required string Name { get; set; }
public string? PrevName { get; set; }
public string? PrevPrevName { get; set; }
public ComponentType Type { get; set; }
}

View File

@@ -0,0 +1,8 @@
namespace FurnitureAssemblyContracts.ViewModels;
public class ComponentWarehouseViewModel
{
public required string WarehouseId { get; set; }
public required string ComponentId { get; set; }
public int Count { get; set; }
}

View File

@@ -0,0 +1,8 @@
namespace FurnitureAssemblyContracts.ViewModels;
public class FurnitureComponentViewModel
{
public required string FurnitureId { get; set; }
public required string ComponentId { get; set; }
public int Count { get; set; }
}

View File

@@ -0,0 +1,9 @@
namespace FurnitureAssemblyContracts.ViewModels;
public class FurnitureViewModel
{
public required string Id { get; set; }
public required string Name { get; set; }
public int Weight { get; set; }
public List<FurnitureComponentViewModel>? Components { get; set; }
}

View File

@@ -0,0 +1,12 @@
namespace FurnitureAssemblyContracts.ViewModels;
public class ManifacturingFurnitureViewModel
{
public required string Id { get; set; }
public required string FurnitureId { get; set; }
public required int Count { get; set; }
public DateTime ProductionDate { get; set; }
public required string WorkerId { get; set; }
public string? WorkerFIO { get; set; }
public string? FurnitureName { get; set; }
}

View File

@@ -0,0 +1,9 @@
namespace FurnitureAssemblyContracts.ViewModels;
public class PostViewModel
{
public required string Id { get; set; }
public required string PostName { get; set; }
public required string PostType { get; set; }
public double Salary { get; set; }
}

View File

@@ -0,0 +1,9 @@
namespace FurnitureAssemblyContracts.ViewModels;
public class SalaryViewModel
{
public required string WorkerId { get; set; }
public required string WorkerFIO { get; set; }
public DateTime SalaryDate { get; set; }
public double Salary { get; set; }
}

View File

@@ -0,0 +1,12 @@
using FurnitureAssemblyContracts.Enums;
namespace FurnitureAssemblyContracts.ViewModels;
public class SuppliesViewModel
{
public required string Id { get; set; }
public required ComponentType Type { get; set; }
public DateTime ProductuionDate { get; set; }
public int Count { get; set; }
public required List<ComponentSuppliesViewModel> Components { get; set; }
}

View File

@@ -0,0 +1,11 @@
using FurnitureAssemblyContracts.Enums;
namespace FurnitureAssemblyContracts.ViewModels;
public class WarehouseViewModel
{
public required string Id { get; set; }
public required ComponentType Type { get; set; }
public required int Count { get; set; }
public required List<ComponentWarehouseViewModel> Components { get; set; }
}

View File

@@ -0,0 +1,12 @@
namespace FurnitureAssemblyContracts.ViewModels;
public class WorkerViewModel
{
public required string Id { get; set; }
public required string FIO { get; set; }
public required string PostId { get; set; }
public required string PostName { get; set; }
public bool IsDeleted { get; set; }
public DateTime BirthDate { get; set; }
public DateTime EmploymentDate { get; set; }
}

View File

@@ -16,4 +16,10 @@
<ProjectReference Include="..\FurnitureAssemblyContracts\FurnitureAssemblyContracts.csproj" />
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="FurnitureAssemblyTests" />
<InternalVisibleTo Include="FurnitureAssemblyWebApi"/>
<InternalsVisibleTo Include="DynamicProxyGenAssembly2"/>
</ItemGroup>
</Project>

View File

@@ -4,9 +4,16 @@ using Microsoft.EntityFrameworkCore;
namespace FurnitureAssemblyDatebase;
public class FurnitureAssemblyDbContext(IConfigurationDatabase configurationDatabase) : DbContext
public class FurnitureAssemblyDbContext : DbContext
{
private readonly IConfigurationDatabase? _configurationDatabase = configurationDatabase;
private readonly IConfigurationDatabase? _configurationDatabase;
public FurnitureAssemblyDbContext(IConfigurationDatabase configurationDatabase)
{
_configurationDatabase = configurationDatabase;
AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true);
AppContext.SetSwitch("Npgsql.DisableDateTimeInfinityConversions", true);
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
@@ -33,6 +40,10 @@ public class FurnitureAssemblyDbContext(IConfigurationDatabase configurationData
.IsUnique()
.HasFilter($"\"{nameof(Post.IsActual)}\" = TRUE");
modelBuilder.Entity<ComponentSupplies>().HasKey(x => new { x.SuppliesId, x.ComponentId });
modelBuilder.Entity<ComponentWarehouse>().HasKey(x => new { x.WarehouseId, x.ComponentId });
modelBuilder.Entity<FurnitureComponent>().HasKey(x => new { x.FurnitureId, x.ComponentId });
modelBuilder.Entity<FurnitureComponent>()
@@ -49,4 +60,8 @@ public class FurnitureAssemblyDbContext(IConfigurationDatabase configurationData
public DbSet<Furniture> Furnitures { get; set; }
public DbSet<FurnitureComponent> FurnitureComponents { get; set; }
public DbSet<Worker> Workers { get; set; }
public DbSet<Supplies> Supplieses { get; set; }
public DbSet<Warehouse> Warehouses { get; set; }
public DbSet<ComponentSupplies> ComponentSupplieses { get; set; }
public DbSet<ComponentWarehouse> ComponentWarehouses { get; set; }
}

View File

@@ -20,6 +20,8 @@ public class FurnitureStorageContract : IFurnitureStorageContract
{
cfg.CreateMap<Furniture, FurnitureDataModel>();
cfg.CreateMap<FurnitureDataModel, Furniture>();
cfg.CreateMap<FurnitureComponent, FurnitureComponentDataModel>();
cfg.CreateMap<FurnitureComponentDataModel, FurnitureComponent>();
});
_mapper = new Mapper(config);
}

View File

@@ -18,6 +18,8 @@ public class ManifacturingStorageContract : IManifacturingStorageContract
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Worker, WorkerDataModel>();
cfg.CreateMap<Furniture, FurnitureDataModel>();
cfg.CreateMap<ManifacturingFurniture, ManifacturingFurnitureDataModel>();
cfg.CreateMap<ManifacturingFurnitureDataModel, ManifacturingFurniture>();
});
@@ -102,5 +104,5 @@ public class ManifacturingStorageContract : IManifacturingStorageContract
}
}
private ManifacturingFurniture? GetManifacturingById(string id) => _dbContext.Manufacturing.FirstOrDefault(x => x.Id == id);
private ManifacturingFurniture? GetManifacturingById(string id) => _dbContext.Manufacturing.Include(x => x.Worker).Include(x => x.Furniture).FirstOrDefault(x => x.Id == id);
}

View File

@@ -20,7 +20,8 @@ public class PostStorageContract : IPostStorageContract
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Post, PostDataModel>()
.ForMember(x => x.Id, x => x.MapFrom(src => src.PostId));
.ForMember(x => x.Id, x => x.MapFrom(src =>
src.PostId));
cfg.CreateMap<PostDataModel, Post>()
.ForMember(x => x.Id, x => x.Ignore())
.ForMember(x => x.PostId, x => x.MapFrom(src => src.Id))
@@ -30,23 +31,17 @@ public class PostStorageContract : IPostStorageContract
_mapper = new Mapper(config);
}
public List<PostDataModel> GetList(bool onlyActual = true)
public List<PostDataModel> GetList()
{
try
{
var query = _dbContext.Posts.AsQueryable();
if (onlyActual)
{
query = query.Where(x => x.IsActual);
}
return [.. query.Select(x => _mapper.Map<PostDataModel>(x))];
return [.._dbContext.Posts.Select(x => _mapper.Map<PostDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public PostDataModel? GetElementById(string id)
@@ -122,7 +117,8 @@ public class PostStorageContract : IPostStorageContract
var element = GetPostById(postDataModel.Id) ?? throw new ElementNotFoundException(postDataModel.Id);
if (!element.IsActual)
{
throw new ElementDeletedException(postDataModel.Id);
throw new
ElementDeletedException(postDataModel.Id);
}
element.IsActual = false;
_dbContext.SaveChanges();

View File

@@ -3,6 +3,7 @@ using FurnitureAssemblyContracts.DataModels;
using FurnitureAssemblyContracts.Exceptions;
using FurnitureAssemblyContracts.StoragesContracts;
using FurnitureAssemblyDatebase.Models;
using Microsoft.EntityFrameworkCore;
namespace FurnitureAssemblyDatebase.Implementations;
@@ -16,6 +17,7 @@ public class SalaryStorageContract : ISalaryStorageContract
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Worker, WorkerDataModel>();
cfg.CreateMap<Salary, SalaryDataModel>();
cfg.CreateMap<SalaryDataModel, Salary>()
.ForMember(dest => dest.WorkerSalary, opt => opt.MapFrom(src => src.Salary));
@@ -26,7 +28,7 @@ public class SalaryStorageContract : ISalaryStorageContract
{
try
{
var query = _dbContext.Salaries.Where(x => x.SalaryDate >= startDate && x.SalaryDate <= endDate);
var query = _dbContext.Salaries.Include(x => x.Worker).Where(x => x.SalaryDate >= startDate && x.SalaryDate <= endDate);
if (workerId is not null)
{
query = query.Where(x => x.WorkerId == workerId);

View File

@@ -0,0 +1,84 @@
using AutoMapper;
using FurnitureAssemblyContracts.DataModels;
using FurnitureAssemblyContracts.Exceptions;
using FurnitureAssemblyContracts.StoragesContracts;
using FurnitureAssemblyDatebase.Models;
namespace FurnitureAssemblyDatebase.Implementations;
public class SuppliesStorageContract : ISuppliesStorageContract
{
private readonly FurnitureAssemblyDbContext _dbContext;
private readonly Mapper _mapper;
public SuppliesStorageContract(FurnitureAssemblyDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.AddMaps(typeof(Supplies));
});
_mapper = new Mapper(config);
}
public List<SuppliesDataModel> GetList(DateTime? startDate = null)
{
try
{
return [.. _dbContext.Supplieses.Select(x => _mapper.Map<SuppliesDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public SuppliesDataModel GetElementById(string id)
{
try
{
return _mapper.Map<SuppliesDataModel>(GetSuppliesById(id));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void AddElement(SuppliesDataModel suppliesDataModel)
{
try
{
_dbContext.Supplieses.Add(_mapper.Map<Supplies>(suppliesDataModel));
_dbContext.SaveChanges();
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void UpdElement(SuppliesDataModel suppliesDataModel)
{
try
{
var element = GetSuppliesById(suppliesDataModel.Id) ?? throw new ElementNotFoundException(suppliesDataModel.Id);
_dbContext.Supplieses.Update(_mapper.Map(suppliesDataModel, element));
_dbContext.SaveChanges();
}
catch (ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
private Supplies? GetSuppliesById(string id) => _dbContext.Supplieses.FirstOrDefault(x => x.Id == id);
}

View File

@@ -0,0 +1,136 @@
using AutoMapper;
using FurnitureAssemblyContracts.DataModels;
using FurnitureAssemblyContracts.Exceptions;
using FurnitureAssemblyContracts.StoragesContracts;
using FurnitureAssemblyDatebase.Models;
using Microsoft.EntityFrameworkCore;
namespace FurnitureAssemblyDatebase.Implementations;
public class WarehouseStorageContract : IWarehouseStorageContract
{
private readonly FurnitureAssemblyDbContext _dbContext;
private readonly Mapper _mapper;
public WarehouseStorageContract(FurnitureAssemblyDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.AddMaps(typeof(ComponentWarehouse));
cfg.AddMaps(typeof(Warehouse));
});
_mapper = new Mapper(config);
}
public List<WarehouseDataModel> GetList()
{
try
{
return [.. _dbContext.Warehouses.Select(x => _mapper.Map<WarehouseDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public WarehouseDataModel GetElementById(string id)
{
try
{
return _mapper.Map<WarehouseDataModel>(GetWarehouseById(id));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void AddElement(WarehouseDataModel warehouseDataModel)
{
try
{
_dbContext.Warehouses.Add(_mapper.Map<Warehouse>(warehouseDataModel));
_dbContext.SaveChanges();
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void UpdElement(WarehouseDataModel warehouseDataModel)
{
try
{
var element = GetWarehouseById(warehouseDataModel.Id) ?? throw new ElementNotFoundException(warehouseDataModel.Id);
_dbContext.Warehouses.Update(_mapper.Map(warehouseDataModel, element));
_dbContext.SaveChanges();
}
catch (ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void DelElement(string id)
{
try
{
var element = GetWarehouseById(id) ?? throw new ElementNotFoundException(id);
_dbContext.Warehouses.Remove(element);
_dbContext.SaveChanges();
}
catch (ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public bool CheckComponents(FurnitureDataModel furnitureDataModel)
{
using (var transaction = _dbContext.Database.BeginTransaction())
{
foreach (FurnitureComponentDataModel furniture_component in furnitureDataModel.Components)
{
var component = _dbContext.Components.FirstOrDefault(x => x.Id == furniture_component.ComponentId);
var warehouse = _dbContext.Warehouses.FirstOrDefault(x => x.Type == component.Type && x.Count >= furniture_component.Count);
if (warehouse == null)
{
transaction.Rollback();
return false;
}
if (warehouse.Count - furniture_component.Count == 0)
{
DelElement(warehouse.Id);
}
else
{
warehouse.Count -= furniture_component.Count;
}
}
transaction.Commit();
_dbContext.SaveChanges();
return true;
}
}
private Warehouse? GetWarehouseById(string id) => _dbContext.Warehouses.FirstOrDefault(x => x.Id == id);
}

View File

@@ -16,9 +16,11 @@ public class WorkerStorageContract : IWorkerStorageContract
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Post, PostDataModel>()
.ForMember(x => x.Id, x => x.MapFrom(src => src.PostId));
cfg.CreateMap<Worker, WorkerDataModel>();
cfg.CreateMap<WorkerDataModel, Worker>();
});
});
_mapper = new Mapper(config);
}
@@ -43,7 +45,7 @@ public class WorkerStorageContract : IWorkerStorageContract
{
query = query.Where(x => x.EmploymentDate >= fromEmploymentDate && x.EmploymentDate <= toEmploymentDate);
}
return [.. query.Select(x => _mapper.Map<WorkerDataModel>(x))];
return [.. JoinPost(query).Select(x => _mapper.Map<WorkerDataModel>(x))];
}
catch (Exception ex)
{
@@ -69,8 +71,7 @@ public class WorkerStorageContract : IWorkerStorageContract
{
try
{
return
_mapper.Map<WorkerDataModel>(_dbContext.Workers.FirstOrDefault(x => x.FIO == fio));
return _mapper.Map<WorkerDataModel>(AddPost(_dbContext.Workers.FirstOrDefault(x => x.FIO == fio && !x.IsDeleted)));
}
catch (Exception ex)
{
@@ -122,8 +123,7 @@ public class WorkerStorageContract : IWorkerStorageContract
{
try
{
var element = GetWorkerById(id) ?? throw new
ElementNotFoundException(id);
var element = GetWorkerById(id) ?? throw new ElementNotFoundException(id);
element.IsDeleted = true;
_dbContext.SaveChanges();
}
@@ -139,5 +139,12 @@ public class WorkerStorageContract : IWorkerStorageContract
}
}
private Worker? GetWorkerById(string id) => _dbContext.Workers.FirstOrDefault(x => x.Id == id && !x.IsDeleted);
private Worker? GetWorkerById(string id) => AddPost(_dbContext.Workers.FirstOrDefault(x => x.Id == id && !x.IsDeleted));
private IQueryable<Worker> JoinPost(IQueryable<Worker> query)
=> query.GroupJoin(_dbContext.Posts.Where(x => x.IsActual), x => x.PostId, y => y.PostId, (x, y) => new { Worker = x, Post = y })
.SelectMany(xy => xy.Post.DefaultIfEmpty(), (x, y) => x.Worker.AddPost(y));
private Worker? AddPost(Worker? worker)
=> worker?.AddPost(_dbContext.Posts.FirstOrDefault(x => x.PostId == worker.PostId && x.IsActual));
}

View File

@@ -15,4 +15,8 @@ public class Component
public required ComponentType Type { get; set; }
[ForeignKey("ComponentId")]
public List<FurnitureComponent>? FurnitureComponents { get; set; }
[ForeignKey("SuppliesesId")]
public List<ComponentSupplies>? ComponentSupplies { get; set; }
[ForeignKey("WarehousesId")]
public List<ComponentWarehouse>? ComponentWarehouse { get; set; }
}

View File

@@ -0,0 +1,14 @@
using AutoMapper;
using FurnitureAssemblyContracts.DataModels;
namespace FurnitureAssemblyDatebase.Models;
[AutoMap(typeof(ComponentSuppliesDataModel), ReverseMap = true)]
public class ComponentSupplies
{
public required string SuppliesId { get; set; }
public required string ComponentId { get; set; }
public int Count { get; set; }
public Supplies? Supplies { get; set; }
public Component? Components { get; set; }
}

View File

@@ -0,0 +1,14 @@
using AutoMapper;
using FurnitureAssemblyContracts.DataModels;
namespace FurnitureAssemblyDatebase.Models;
[AutoMap(typeof(ComponentWarehouseDataModel), ReverseMap = true)]
public class ComponentWarehouse
{
public required string WarehouseId { get; set; }
public required string ComponentId { get; set; }
public int Count { get; set; }
public Warehouse? Warehouses { get; set; }
public Component? Components { get; set; }
}

View File

@@ -0,0 +1,18 @@
using AutoMapper;
using FurnitureAssemblyContracts.DataModels;
using FurnitureAssemblyContracts.Enums;
using System.ComponentModel.DataAnnotations.Schema;
namespace FurnitureAssemblyDatebase.Models;
[AutoMap(typeof(SuppliesDataModel), ReverseMap = true)]
public class Supplies
{
public required string Id { get; set; }
public required ComponentType Type { get; set; }
public DateTime ProductuionDate { get; set; }
public required int Count { get; set; }
[ForeignKey("SuppliesId")]
public List<ComponentSupplies>? Components { get; set; }
}

View File

@@ -0,0 +1,17 @@
using AutoMapper;
using FurnitureAssemblyContracts.DataModels;
using FurnitureAssemblyContracts.Enums;
using System.ComponentModel.DataAnnotations.Schema;
namespace FurnitureAssemblyDatebase.Models;
[AutoMap(typeof(WarehouseDataModel), ReverseMap = true)]
public class Warehouse
{
public required string Id { get; set; }
public required ComponentType Type { get; set; }
public required int Count { get; set; }
[ForeignKey("WarehouseId")]
public List<ComponentWarehouse>? Components { get; set; }
}

View File

@@ -16,4 +16,11 @@ public class Worker
public List<Salary>? Salaries { get; set; }
[ForeignKey("WorkerId")]
public List<ManifacturingFurniture>? ManifacturingFurniture { get; set; }
[NotMapped]
public Post? Post { get; set; }
public Worker AddPost(Post? post)
{
Post = post;
return this;
}
}

View File

@@ -11,18 +11,21 @@ namespace FurnitureAssemblyTests.BusinessLogicContractsTests;
public class FurnitureBusinessLogicContractTests
{
private IFurnitureBusinessLogicContract _furnitureBusinessLogicContract;
private Mock<IWarehouseStorageContract> _warehouseStorageContract;
private Mock<IFurnitureStorageContract> _furnitureStorageContract;
[OneTimeSetUp]
public void OneTimeSetUp()
{
_furnitureStorageContract = new Mock<IFurnitureStorageContract>();
_furnitureBusinessLogicContract = new FurnitureBusinessLogicContract(_furnitureStorageContract.Object, new Mock<ILogger>().Object);
_warehouseStorageContract = new Mock<IWarehouseStorageContract>();
_furnitureBusinessLogicContract = new FurnitureBusinessLogicContract(_furnitureStorageContract.Object, _warehouseStorageContract.Object, new Mock<ILogger>().Object);
}
[TearDown]
public void TearDown()
{
_warehouseStorageContract.Reset();
_furnitureStorageContract.Reset();
}
@@ -154,6 +157,7 @@ public class FurnitureBusinessLogicContractTests
//Arrange
var flag = false;
var record = new FurnitureDataModel(Guid.NewGuid().ToString(), "name", 10, [new FurnitureComponentDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]);
_warehouseStorageContract.Setup(x => x.CheckComponents(It.IsAny<FurnitureDataModel>())).Returns(true);
_furnitureStorageContract.Setup(x => x.AddElement(It.IsAny<FurnitureDataModel>())).Callback((FurnitureDataModel x) =>
{
flag = x.Id == record.Id && x.Name == record.Name;
@@ -161,6 +165,7 @@ public class FurnitureBusinessLogicContractTests
//Act
_furnitureBusinessLogicContract.InsertFurniture(record);
//Assert
_warehouseStorageContract.Verify(x => x.CheckComponents(It.IsAny<FurnitureDataModel>()), Times.Once);
_furnitureStorageContract.Verify(x => x.AddElement(It.IsAny<FurnitureDataModel>()), Times.Once);
Assert.That(flag);
}
@@ -169,10 +174,12 @@ public class FurnitureBusinessLogicContractTests
public void InsertFurnitures_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_warehouseStorageContract.Setup(x => x.CheckComponents(It.IsAny<FurnitureDataModel>())).Returns(true);
_furnitureStorageContract.Setup(x => x.AddElement(It.IsAny<FurnitureDataModel>())).Throws(new ElementExistsException("Data", "Data"));
//Act&Assert
Assert.That(() => _furnitureBusinessLogicContract.InsertFurniture(new(Guid.NewGuid().ToString(), "name", 10,
[new FurnitureComponentDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<ElementExistsException>());
_warehouseStorageContract.Verify(x => x.CheckComponents(It.IsAny<FurnitureDataModel>()), Times.Once);
_furnitureStorageContract.Verify(x => x.AddElement(It.IsAny<FurnitureDataModel>()), Times.Once);
}
@@ -197,19 +204,34 @@ public class FurnitureBusinessLogicContractTests
public void InsertFurnitures_StorageThrowError_ThrowException_Test()
{
//Arrange
_warehouseStorageContract.Setup(x => x.CheckComponents(It.IsAny<FurnitureDataModel>())).Returns(true);
_furnitureStorageContract.Setup(x => x.AddElement(It.IsAny<FurnitureDataModel>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _furnitureBusinessLogicContract.InsertFurniture(new(Guid.NewGuid().ToString(), "name", 10,
[new FurnitureComponentDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<StorageException>());
_warehouseStorageContract.Verify(x => x.CheckComponents(It.IsAny<FurnitureDataModel>()), Times.Once);
_furnitureStorageContract.Verify(x => x.AddElement(It.IsAny<FurnitureDataModel>()), Times.Once);
}
[Test]
public void InsertFurniture_InsufficientError_ThrowException_Test()
{
//Arrange
_warehouseStorageContract.Setup(x => x.CheckComponents(It.IsAny<FurnitureDataModel>())).Returns(false);
Assert.That(() => _furnitureBusinessLogicContract.InsertFurniture(new FurnitureDataModel(Guid.NewGuid().ToString(), "name", 10,
[new FurnitureComponentDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<InsufficientException>());
//Act&Assert
_warehouseStorageContract.Verify(x => x.CheckComponents(It.IsAny<FurnitureDataModel>()), Times.Once);
_furnitureStorageContract.Verify(x => x.UpdElement(It.IsAny<FurnitureDataModel>()), Times.Never);
}
[Test]
public void UpdateFurnitures_CorrectRecord_Test()
{
//Arrange
var flag = false;
var record = new FurnitureDataModel(Guid.NewGuid().ToString(), "name", 10, [new FurnitureComponentDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]);
_warehouseStorageContract.Setup(x => x.CheckComponents(It.IsAny<FurnitureDataModel>())).Returns(true);
_furnitureStorageContract.Setup(x => x.UpdElement(It.IsAny<FurnitureDataModel>())).Callback((FurnitureDataModel x) =>
{
flag = x.Id == record.Id && x.Name == record.Name;
@@ -217,6 +239,7 @@ public class FurnitureBusinessLogicContractTests
//Act
_furnitureBusinessLogicContract.UpdateFurniture(record);
//Assert
_warehouseStorageContract.Verify(x => x.CheckComponents(It.IsAny<FurnitureDataModel>()), Times.Once);
_furnitureStorageContract.Verify(x => x.UpdElement(It.IsAny<FurnitureDataModel>()), Times.Once);
Assert.That(flag);
}
@@ -225,10 +248,12 @@ public class FurnitureBusinessLogicContractTests
public void UpdateFurnitures_RecordWithIncorrectData_ThrowException_Test()
{
//Arrange
_warehouseStorageContract.Setup(x => x.CheckComponents(It.IsAny<FurnitureDataModel>())).Returns(true);
_furnitureStorageContract.Setup(x => x.UpdElement(It.IsAny<FurnitureDataModel>())).Throws(new ElementNotFoundException(""));
//Act&Assert
Assert.That(() => _furnitureBusinessLogicContract.UpdateFurniture(new(Guid.NewGuid().ToString(), "name", 10,
[new FurnitureComponentDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<ElementNotFoundException>());
_warehouseStorageContract.Verify(x => x.CheckComponents(It.IsAny<FurnitureDataModel>()), Times.Once);
_furnitureStorageContract.Verify(x => x.UpdElement(It.IsAny<FurnitureDataModel>()), Times.Once);
}
@@ -236,10 +261,12 @@ public class FurnitureBusinessLogicContractTests
public void UpdateFurnitures_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_warehouseStorageContract.Setup(x => x.CheckComponents(It.IsAny<FurnitureDataModel>())).Returns(true);
_furnitureStorageContract.Setup(x => x.UpdElement(It.IsAny<FurnitureDataModel>())).Throws(new ElementExistsException("Data", "Data"));
//Act&Assert
Assert.That(() => _furnitureBusinessLogicContract.UpdateFurniture(new(Guid.NewGuid().ToString(), "name", 10,
[new FurnitureComponentDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<ElementExistsException>());
_warehouseStorageContract.Verify(x => x.CheckComponents(It.IsAny<FurnitureDataModel>()), Times.Once);
_furnitureStorageContract.Verify(x => x.UpdElement(It.IsAny<FurnitureDataModel>()), Times.Once);
}
@@ -264,13 +291,27 @@ public class FurnitureBusinessLogicContractTests
public void UpdateFurnitures_StorageThrowError_ThrowException_Test()
{
//Arrange
_warehouseStorageContract.Setup(x => x.CheckComponents(It.IsAny<FurnitureDataModel>())).Returns(true);
_furnitureStorageContract.Setup(x => x.UpdElement(It.IsAny<FurnitureDataModel>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _furnitureBusinessLogicContract.UpdateFurniture(new(Guid.NewGuid().ToString(), "name", 10,
[new FurnitureComponentDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(),5)])), Throws.TypeOf<StorageException>());
_warehouseStorageContract.Verify(x => x.CheckComponents(It.IsAny<FurnitureDataModel>()), Times.Once);
_furnitureStorageContract.Verify(x => x.UpdElement(It.IsAny<FurnitureDataModel>()), Times.Once);
}
[Test]
public void UpdateFurniture_InsufficientError_ThrowException_Test()
{
//Arrange
_warehouseStorageContract.Setup(x => x.CheckComponents(It.IsAny<FurnitureDataModel>())).Returns(false);
//Act&Assert
Assert.That(() => _furnitureBusinessLogicContract.UpdateFurniture(new(Guid.NewGuid().ToString(), "name", 10,
[new FurnitureComponentDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<InsufficientException>());
_warehouseStorageContract.Verify(x => x.CheckComponents(It.IsAny<FurnitureDataModel>()), Times.Once);
_furnitureStorageContract.Verify(x => x.UpdElement(It.IsAny<FurnitureDataModel>()), Times.Never);
}
[Test]
public void DeleteFurnitures_CorrectRecord_Test()
{

View File

@@ -32,61 +32,53 @@ internal class PostBusinessLogicContractTests
//Arrange
var listOriginal = new List<PostDataModel>()
{
new(Guid.NewGuid().ToString(),"name 1", PostType.Builder, 10, true, DateTime.UtcNow),
new(Guid.NewGuid().ToString(), "name 2", PostType.Builder, 10, false, DateTime.UtcNow),
new(Guid.NewGuid().ToString(), "name 3", PostType.Builder, 10, true, DateTime.UtcNow),
new(Guid.NewGuid().ToString(), "name 1", PostType.Builder, 10),
new(Guid.NewGuid().ToString(), "name 2", PostType.Builder, 10),
new(Guid.NewGuid().ToString(), "name 3", PostType.Builder, 10),
};
_postStorageContract.Setup(x => x.GetList(It.IsAny<bool>())).Returns(listOriginal);
_postStorageContract.Setup(x => x.GetList()).Returns(listOriginal);
//Act
var listOnlyActive = _postBusinessLogicContract.GetAllPosts(true);
var listAll = _postBusinessLogicContract.GetAllPosts(false);
var list = _postBusinessLogicContract.GetAllPosts();
//Assert
Assert.Multiple(() =>
{
Assert.That(listOnlyActive, Is.Not.Null);
Assert.That(listAll, Is.Not.Null);
Assert.That(listOnlyActive, Is.EquivalentTo(listOriginal));
Assert.That(listAll, Is.EquivalentTo(listOriginal));
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.EquivalentTo(listOriginal));
});
_postStorageContract.Verify(x => x.GetList(true), Times.Once);
_postStorageContract.Verify(x => x.GetList(false), Times.Once);
_postStorageContract.Verify(x => x.GetList(), Times.Once);
}
[Test]
public void GetAllPosts_ReturnEmptyList_Test()
{
//Arrange
_postStorageContract.Setup(x => x.GetList(It.IsAny<bool>())).Returns([]);
_postStorageContract.Setup(x => x.GetList()).Returns([]);
//Act
var listOnlyActive = _postBusinessLogicContract.GetAllPosts(true);
var listAll = _postBusinessLogicContract.GetAllPosts(false);
var list = _postBusinessLogicContract.GetAllPosts();
//Assert
Assert.Multiple(() =>
{
Assert.That(listOnlyActive, Is.Not.Null);
Assert.That(listAll, Is.Not.Null);
Assert.That(listOnlyActive, Has.Count.EqualTo(0));
Assert.That(listAll, Has.Count.EqualTo(0));
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
});
_postStorageContract.Verify(x => x.GetList(It.IsAny<bool>()), Times.Exactly(2));
}
[Test]
public void GetAllPosts_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.GetAllPosts(It.IsAny<bool>()), Throws.TypeOf<NullListException>());
_postStorageContract.Verify(x => x.GetList(It.IsAny<bool>()), Times.Once);
Assert.That(() => _postBusinessLogicContract.GetAllPosts(), Throws.TypeOf<NullListException>());
_postStorageContract.Verify(x => x.GetList(), Times.Once);
}
[Test]
public void GetAllPosts_StorageThrowError_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x => x.GetList(It.IsAny<bool>())).Throws(new StorageException(new InvalidOperationException()));
_postStorageContract.Setup(x => x.GetList()).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.GetAllPosts(It.IsAny<bool>()), Throws.TypeOf<StorageException>());
_postStorageContract.Verify(x => x.GetList(It.IsAny<bool>()), Times.Once);
Assert.That(() => _postBusinessLogicContract.GetAllPosts(), Throws.TypeOf<StorageException>());
_postStorageContract.Verify(x => x.GetList(), Times.Once);
}
[Test]
@@ -96,8 +88,8 @@ internal class PostBusinessLogicContractTests
var postId = Guid.NewGuid().ToString();
var listOriginal = new List<PostDataModel>()
{
new(postId, "name 1", PostType.Builder, 10, true, DateTime.UtcNow),
new(postId, "name 2", PostType.Builder, 10, false, DateTime.UtcNow)
new(postId, "name 1", PostType.Builder, 10),
new(postId, "name 2", PostType.Builder, 10)
};
_postStorageContract.Setup(x => x.GetPostWithHistory(It.IsAny<string>())).Returns(listOriginal);
//Act
@@ -161,7 +153,7 @@ internal class PostBusinessLogicContractTests
{
//Arrange
var id = Guid.NewGuid().ToString();
var record = new PostDataModel(id, "name", PostType.Builder, 10, true, DateTime.UtcNow);
var record = new PostDataModel(id, "name", PostType.Builder, 10);
_postStorageContract.Setup(x => x.GetElementById(id)).Returns(record);
//Act
var element = _postBusinessLogicContract.GetPostByData(id);
@@ -176,7 +168,7 @@ internal class PostBusinessLogicContractTests
{
//Arrange
var postName = "name";
var record = new PostDataModel(Guid.NewGuid().ToString(), postName, PostType.Builder, 10, true, DateTime.UtcNow);
var record = new PostDataModel(Guid.NewGuid().ToString(), postName, PostType.Builder, 10);
_postStorageContract.Setup(x => x.GetElementByName(postName)).Returns(record);
//Act
var element = _postBusinessLogicContract.GetPostByData(postName);
@@ -232,11 +224,11 @@ internal class PostBusinessLogicContractTests
{
//Arrange
var flag = false;
var record = new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Builder, 10, true, DateTime.UtcNow.AddDays(-1));
var record = new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Builder, 10);
_postStorageContract.Setup(x => x.AddElement(It.IsAny<PostDataModel>()))
.Callback((PostDataModel x) =>
{
flag = x.Id == record.Id && x.PostName == record.PostName && x.PostType == record.PostType && x.Salary == record.Salary && x.ChangeDate == record.ChangeDate;
flag = x.Id == record.Id && x.PostName == record.PostName && x.PostType == record.PostType && x.Salary == record.Salary;
});
//Act
@@ -252,7 +244,7 @@ internal class PostBusinessLogicContractTests
//Arrange
_postStorageContract.Setup(x => x.AddElement(It.IsAny<PostDataModel>())).Throws(new ElementExistsException("Data", "Data"));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.InsertPost(new(Guid.NewGuid().ToString(), "name", PostType.Builder, 10, true, DateTime.UtcNow)), Throws.TypeOf<ElementExistsException>());
Assert.That(() => _postBusinessLogicContract.InsertPost(new(Guid.NewGuid().ToString(), "name", PostType.Builder, 10)), Throws.TypeOf<ElementExistsException>());
_postStorageContract.Verify(x => x.AddElement(It.IsAny<PostDataModel>()), Times.Once);
}
@@ -268,7 +260,7 @@ internal class PostBusinessLogicContractTests
public void InsertPost_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.InsertPost(new PostDataModel("id", "name", PostType.Builder, 10, true, DateTime.UtcNow)), Throws.TypeOf<ValidationException>());
Assert.That(() => _postBusinessLogicContract.InsertPost(new PostDataModel("id", "name", PostType.Builder, 10)), Throws.TypeOf<ValidationException>());
_postStorageContract.Verify(x => x.AddElement(It.IsAny<PostDataModel>()), Times.Never);
}
@@ -278,7 +270,7 @@ internal class PostBusinessLogicContractTests
//Arrange
_postStorageContract.Setup(x => x.AddElement(It.IsAny<PostDataModel>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.InsertPost(new(Guid.NewGuid().ToString(), "name", PostType.Builder, 10, true, DateTime.UtcNow)), Throws.TypeOf<StorageException>());
Assert.That(() => _postBusinessLogicContract.InsertPost(new(Guid.NewGuid().ToString(), "name", PostType.Builder, 10)), Throws.TypeOf<StorageException>());
_postStorageContract.Verify(x => x.AddElement(It.IsAny<PostDataModel>()), Times.Once);
}
@@ -287,10 +279,10 @@ internal class PostBusinessLogicContractTests
{
//Arrange
var flag = false;
var record = new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Builder, 10, true, DateTime.UtcNow.AddDays(-1));
var record = new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Builder, 10);
_postStorageContract.Setup(x => x.UpdElement(It.IsAny<PostDataModel>())).Callback((PostDataModel x) =>
{
flag = x.Id == record.Id && x.PostName == record.PostName && x.PostType == record.PostType && x.Salary == record.Salary && x.ChangeDate == record.ChangeDate;
flag = x.Id == record.Id && x.PostName == record.PostName && x.PostType == record.PostType && x.Salary == record.Salary;
});
//Act
_postBusinessLogicContract.UpdatePost(record);
@@ -305,7 +297,7 @@ internal class PostBusinessLogicContractTests
//Arrange
_postStorageContract.Setup(x => x.UpdElement(It.IsAny<PostDataModel>())).Throws(new ElementNotFoundException(""));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "name", PostType.Builder, 10, true, DateTime.UtcNow)), Throws.TypeOf<ElementNotFoundException>());
Assert.That(() => _postBusinessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "name", PostType.Builder, 10)), Throws.TypeOf<ElementNotFoundException>());
_postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Once);
}
@@ -315,7 +307,7 @@ internal class PostBusinessLogicContractTests
//Arrange
_postStorageContract.Setup(x => x.UpdElement(It.IsAny<PostDataModel>())).Throws(new ElementExistsException("Data", "Data"));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "anme", PostType.Builder, 10, true, DateTime.UtcNow)), Throws.TypeOf<ElementExistsException>());
Assert.That(() => _postBusinessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "anme", PostType.Builder, 10)), Throws.TypeOf<ElementExistsException>());
_postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Once);
}
@@ -331,7 +323,7 @@ internal class PostBusinessLogicContractTests
public void UpdatePost_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.UpdatePost(new PostDataModel("id", "name", PostType.Builder, 10, true, DateTime.UtcNow)), Throws.TypeOf<ValidationException>());
Assert.That(() => _postBusinessLogicContract.UpdatePost(new PostDataModel("id", "name", PostType.Builder, 10)), Throws.TypeOf<ValidationException>());
_postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Never);
}
@@ -341,7 +333,7 @@ internal class PostBusinessLogicContractTests
//Arrange
_postStorageContract.Setup(x => x.UpdElement(It.IsAny<PostDataModel>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "name", PostType.Builder, 10, true, DateTime.UtcNow)), Throws.TypeOf<StorageException>());
Assert.That(() => _postBusinessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "name", PostType.Builder, 10)), Throws.TypeOf<StorageException>());
_postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Once);
}

View File

@@ -190,7 +190,7 @@ internal class SalaryBuisnessLogicContractTests
_manifacturingStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns([new ManifacturingFurnitureDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), saleSum, workerId)]);
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Builder, postSalary, true, DateTime.UtcNow));
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Builder, postSalary));
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Returns([new WorkerDataModel(workerId, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)]);
var sum = 0.0;
@@ -225,7 +225,7 @@ internal class SalaryBuisnessLogicContractTests
new ManifacturingFurnitureDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 10, worker3Id),
new ManifacturingFurnitureDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 10, worker3Id)]);
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Builder, 2000, true, DateTime.UtcNow));
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Builder, 2000));
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Returns(list);
//Act
@@ -243,7 +243,7 @@ internal class SalaryBuisnessLogicContractTests
_manifacturingStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns([]);
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Builder, postSalary, true, DateTime.UtcNow));
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Builder, postSalary));
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Returns([new WorkerDataModel(workerId, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)]);
var sum = 0.0;
@@ -265,7 +265,7 @@ internal class SalaryBuisnessLogicContractTests
//Arrange
var workerId = Guid.NewGuid().ToString();
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Builder, 2000, true, DateTime.UtcNow));
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Builder, 2000));
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Returns([new WorkerDataModel(workerId, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)]);
//Act&Assert
@@ -293,7 +293,7 @@ internal class SalaryBuisnessLogicContractTests
_manifacturingStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns([new ManifacturingFurnitureDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 10, workerId)]);
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Builder, 2000, true, DateTime.UtcNow));
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Builder, 2000));
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow), Throws.TypeOf<NullListException>());
}
@@ -306,7 +306,7 @@ internal class SalaryBuisnessLogicContractTests
_manifacturingStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>()))
.Throws(new StorageException(new InvalidOperationException()));
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Builder, 2000, true, DateTime.UtcNow));
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Builder, 2000));
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Returns([new WorkerDataModel(workerId, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)]);
//Act&Assert
@@ -336,7 +336,7 @@ internal class SalaryBuisnessLogicContractTests
_manifacturingStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns([new ManifacturingFurnitureDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 10, workerId)]);
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Builder, 2000, true, DateTime.UtcNow));
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Builder, 2000));
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Throws(new StorageException(new InvalidOperationException()));
//Act&Assert

View File

@@ -0,0 +1,238 @@
using FurnitureAssemblyBusinessLogic.Implementations;
using FurnitureAssemblyContracts.BusinessLogicsContracts;
using FurnitureAssemblyContracts.DataModels;
using FurnitureAssemblyContracts.Enums;
using FurnitureAssemblyContracts.Exceptions;
using FurnitureAssemblyContracts.StoragesContracts;
using Microsoft.Extensions.Logging;
using Moq;
namespace FurnitureAssemblyTests.BusinessLogicContractsTests;
[TestFixture]
internal class SuppliesBusinessLogicContractTests
{
private SuppliesBusinessLogicContract _suppliesBusinessLogicContract;
private Mock<ISuppliesStorageContract> _suppliesStorageContract;
[OneTimeSetUp]
public void OneTimeSetUp()
{
_suppliesStorageContract = new Mock<ISuppliesStorageContract>();
_suppliesBusinessLogicContract = new SuppliesBusinessLogicContract(_suppliesStorageContract.Object, new Mock<ILogger>().Object);
}
[TearDown]
public void TearDown()
{
_suppliesStorageContract.Reset();
}
[Test]
public void GetAllSupplies_ReturnListOfRecords_Test()
{
// Arrange
var listOriginal = new List<SuppliesDataModel>()
{
new(Guid.NewGuid().ToString(), ComponentType.Panel, DateTime.Now, 1, []),
new(Guid.NewGuid().ToString(), ComponentType.Panel, DateTime.Now, 1, []),
new(Guid.NewGuid().ToString(), ComponentType.Panel, DateTime.Now, 1, []),
};
_suppliesStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>())).Returns(listOriginal);
// Act
var list = _suppliesBusinessLogicContract.GetAllComponents();
// Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.EquivalentTo(listOriginal));
}
[Test]
public void GetAllSupplies_ReturnEmptyList_Test()
{
// Arrange
_suppliesStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>())).Returns([]);
// Act
var list = _suppliesBusinessLogicContract.GetAllComponents();
// Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
_suppliesStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>()), Times.Once);
}
[Test]
public void GetAllSupplies_ReturnNull_ThrowException_Test()
{
// Arrange
_suppliesStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>())).Returns((List<SuppliesDataModel>)null);
// Act & Assert
Assert.That(() => _suppliesBusinessLogicContract.GetAllComponents(), Throws.TypeOf<NullListException>());
_suppliesStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>()), Times.Once);
}
[Test]
public void GetAllSupplies_StorageThrowError_ThrowException_Test()
{
// Arrange
_suppliesStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>())).Throws(new StorageException(new InvalidOperationException()));
// Act & Assert
Assert.That(() => _suppliesBusinessLogicContract.GetAllComponents(), Throws.TypeOf<StorageException>());
_suppliesStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>()), Times.Once);
}
[Test]
public void GetSuppliesByData_GetById_ReturnRecord_Test()
{
// Arrange
var id = Guid.NewGuid().ToString();
var record = new SuppliesDataModel(id, ComponentType.Panel, DateTime.Now, 1, []);
_suppliesStorageContract.Setup(x => x.GetElementById(id)).Returns(record);
// Act
var element = _suppliesBusinessLogicContract.GetComponentByData(id);
// Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.Id, Is.EqualTo(id));
_suppliesStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetComponentsByData_EmptyData_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _suppliesBusinessLogicContract.GetComponentByData(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _suppliesBusinessLogicContract.GetComponentByData(string.Empty), Throws.TypeOf<ArgumentNullException>());
_suppliesStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetSuppliesByData_GetById_NotFoundRecord_ThrowException_Test()
{
// Arrange
_suppliesStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new ElementNotFoundException(""));
// Act & Assert
Assert.That(() => _suppliesBusinessLogicContract.GetComponentByData(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_suppliesStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetSuppliesByData_StorageThrowError_ThrowException_Test()
{
// Arrange
_suppliesStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
// Act & Assert
Assert.That(() => _suppliesBusinessLogicContract.GetComponentByData(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_suppliesStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void InsertSupplies_CorrectRecord_Test()
{
// Arrange
var record = new SuppliesDataModel(Guid.NewGuid().ToString(), ComponentType.Panel, DateTime.Now, 1,
[new ComponentSuppliesDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]);
_suppliesStorageContract.Setup(x => x.AddElement(It.IsAny<SuppliesDataModel>()));
// Act
_suppliesBusinessLogicContract.InsertComponent(record);
// Assert
_suppliesStorageContract.Verify(x => x.AddElement(It.IsAny<SuppliesDataModel>()), Times.Once);
}
[Test]
public void InsertSupplies_RecordWithExistsData_ThrowException_Test()
{
// Arrange
_suppliesStorageContract.Setup(x => x.AddElement(It.IsAny<SuppliesDataModel>())).Throws(new ElementExistsException("Data", "Data"));
// Act & Assert
Assert.That(() => _suppliesBusinessLogicContract.InsertComponent(new(Guid.NewGuid().ToString(), ComponentType.Panel, DateTime.Now, 1,
[new ComponentSuppliesDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<ElementExistsException>());
_suppliesStorageContract.Verify(x => x.AddElement(It.IsAny<SuppliesDataModel>()), Times.Once);
}
[Test]
public void InsertSupplies_NullRecord_ThrowException_Test()
{
// Act & Assert
Assert.That(() => _suppliesBusinessLogicContract.InsertComponent(null), Throws.TypeOf<ArgumentNullException>());
_suppliesStorageContract.Verify(x => x.AddElement(It.IsAny<SuppliesDataModel>()), Times.Never);
}
[Test]
public void InsertComponents_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _suppliesBusinessLogicContract.InsertComponent(new SuppliesDataModel("id", ComponentType.Panel, DateTime.UtcNow, 1, [])), Throws.TypeOf<ValidationException>());
_suppliesStorageContract.Verify(x => x.AddElement(It.IsAny<SuppliesDataModel>()), Times.Never);
}
[Test]
public void InsertSupplies_StorageThrowError_ThrowException_Test()
{
// Arrange
_suppliesStorageContract.Setup(x => x.AddElement(It.IsAny<SuppliesDataModel>())).Throws(new StorageException(new InvalidOperationException()));
// Act & Assert
Assert.That(() => _suppliesBusinessLogicContract.InsertComponent(new(Guid.NewGuid().ToString(), ComponentType.Panel, DateTime.Now, 1,
[new ComponentSuppliesDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<StorageException>());
_suppliesStorageContract.Verify(x => x.AddElement(It.IsAny<SuppliesDataModel>()), Times.Once);
}
[Test]
public void UpdateSupplies_CorrectRecord_Test()
{
// Arrange
var record = new SuppliesDataModel(Guid.NewGuid().ToString(), ComponentType.Panel, DateTime.Now, 1,
[new ComponentSuppliesDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]);
_suppliesStorageContract.Setup(x => x.UpdElement(It.IsAny<SuppliesDataModel>()));
// Act
_suppliesBusinessLogicContract.UpdateComponent(record);
// Assert
_suppliesStorageContract.Verify(x => x.UpdElement(It.IsAny<SuppliesDataModel>()), Times.Once);
}
[Test]
public void UpdateSupplies_RecordWithIncorrectData_ThrowException_Test()
{
// Arrange
_suppliesStorageContract.Setup(x => x.UpdElement(It.IsAny<SuppliesDataModel>())).Throws(new ElementNotFoundException(""));
// Act & Assert
Assert.That(() => _suppliesBusinessLogicContract.UpdateComponent(new(Guid.NewGuid().ToString(), ComponentType.Panel, DateTime.Now, 1,
[new ComponentSuppliesDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<ElementNotFoundException>());
_suppliesStorageContract.Verify(x => x.UpdElement(It.IsAny<SuppliesDataModel>()), Times.Once);
}
[Test]
public void UpdateSupplies_RecordWithExistsData_ThrowException_Test()
{
// Arrange
_suppliesStorageContract.Setup(x => x.UpdElement(It.IsAny<SuppliesDataModel>())).Throws(new ElementExistsException("Data", "Data"));
// Act & Assert
Assert.That(() => _suppliesBusinessLogicContract.UpdateComponent(new(Guid.NewGuid().ToString(), ComponentType.Panel, DateTime.Now, 1,
[new ComponentSuppliesDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<ElementExistsException>());
_suppliesStorageContract.Verify(x => x.UpdElement(It.IsAny<SuppliesDataModel>()), Times.Once);
}
[Test]
public void UpdateSupplies_NullRecord_ThrowException_Test()
{
// Act & Assert
Assert.That(() => _suppliesBusinessLogicContract.UpdateComponent(null), Throws.TypeOf<ArgumentNullException>());
_suppliesStorageContract.Verify(x => x.UpdElement(It.IsAny<SuppliesDataModel>()), Times.Never);
}
[Test]
public void UpdateComponents_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _suppliesBusinessLogicContract.UpdateComponent(new SuppliesDataModel(Guid.NewGuid().ToString(), ComponentType.Panel, DateTime.Now, 1, [])), Throws.TypeOf<ValidationException>());
_suppliesStorageContract.Verify(x => x.UpdElement(It.IsAny<SuppliesDataModel>()), Times.Never);
}
[Test]
public void UpdateSupplies_StorageThrowError_ThrowException_Test()
{
// Arrange
_suppliesStorageContract.Setup(x => x.UpdElement(It.IsAny<SuppliesDataModel>())).Throws(new StorageException(new InvalidOperationException()));
// Act & Assert
Assert.That(() => _suppliesBusinessLogicContract.UpdateComponent(new(Guid.NewGuid().ToString(), ComponentType.Panel, DateTime.Now, 1,
[new ComponentSuppliesDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<StorageException>());
_suppliesStorageContract.Verify(x => x.UpdElement(It.IsAny<SuppliesDataModel>()), Times.Once);
}
}

View File

@@ -0,0 +1,291 @@
using FurnitureAssemblyBusinessLogic.Implementations;
using FurnitureAssemblyContracts.BusinessLogicsContracts;
using FurnitureAssemblyContracts.DataModels;
using FurnitureAssemblyContracts.Enums;
using FurnitureAssemblyContracts.Exceptions;
using FurnitureAssemblyContracts.StoragesContracts;
using Microsoft.Extensions.Logging;
using Moq;
namespace FurnitureAssemblyTests.BusinessLogicContractsTests;
[TestFixture]
internal class WarehouseBusinessLogicContractTests
{
private IWarehouseBusinessLogicContract _warehouseBusinessLogicContract;
private Mock<IWarehouseStorageContract> _warehouseStorageContract;
[OneTimeSetUp]
public void OneTimeSetUp()
{
_warehouseStorageContract = new Mock<IWarehouseStorageContract>();
_warehouseBusinessLogicContract = new WarehouseBusinessLogicContract(_warehouseStorageContract.Object, new Mock<ILogger>().Object);
}
[TearDown]
public void TearDown()
{
_warehouseStorageContract.Reset();
}
public void GetAllSupplies_ReturnListOfRecords_Test()
{
// Arrange
var listOriginal = new List<WarehouseDataModel>()
{
new(Guid.NewGuid().ToString(), ComponentType.Panel, 1, []),
new(Guid.NewGuid().ToString(), ComponentType.Panel, 1, []),
new(Guid.NewGuid().ToString(), ComponentType.Panel, 1, []),
};
_warehouseStorageContract.Setup(x => x.GetList()).Returns(listOriginal);
// Act
var list = _warehouseBusinessLogicContract.GetAllComponents();
// Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.EquivalentTo(listOriginal));
}
[Test]
public void GetAllSupplies_ReturnEmptyList_Test()
{
// Arrange
_warehouseStorageContract.Setup(x => x.GetList()).Returns([]);
// Act
var list = _warehouseBusinessLogicContract.GetAllComponents();
// Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
_warehouseStorageContract.Verify(x => x.GetList(), Times.Once);
}
[Test]
public void GetAllSupplies_ReturnNull_ThrowException_Test()
{
// Arrange
_warehouseStorageContract.Setup(x => x.GetList()).Returns((List<WarehouseDataModel>)null);
// Act & Assert
Assert.That(() => _warehouseBusinessLogicContract.GetAllComponents(), Throws.TypeOf<NullListException>());
_warehouseStorageContract.Verify(x => x.GetList(), Times.Once);
}
[Test]
public void GetAllSupplies_StorageThrowError_ThrowException_Test()
{
// Arrange
_warehouseStorageContract.Setup(x => x.GetList()).Throws(new StorageException(new InvalidOperationException()));
// Act & Assert
Assert.That(() => _warehouseBusinessLogicContract.GetAllComponents(), Throws.TypeOf<StorageException>());
_warehouseStorageContract.Verify(x => x.GetList(), Times.Once);
}
[Test]
public void GetSuppliesByData_GetById_ReturnRecord_Test()
{
// Arrange
var id = Guid.NewGuid().ToString();
var record = new WarehouseDataModel(id, ComponentType.Panel, 1, []);
_warehouseStorageContract.Setup(x => x.GetElementById(id)).Returns(record);
// Act
var element = _warehouseBusinessLogicContract.GetComponentByData(id);
// Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.Id, Is.EqualTo(id));
_warehouseStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetComponentsByData_EmptyData_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _warehouseBusinessLogicContract.GetComponentByData(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _warehouseBusinessLogicContract.GetComponentByData(string.Empty), Throws.TypeOf<ArgumentNullException>());
_warehouseStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetSuppliesByData_GetById_NotFoundRecord_ThrowException_Test()
{
// Arrange
_warehouseStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new ElementNotFoundException(""));
// Act & Assert
Assert.That(() => _warehouseBusinessLogicContract.GetComponentByData(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_warehouseStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetSuppliesByData_StorageThrowError_ThrowException_Test()
{
// Arrange
_warehouseStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
// Act & Assert
Assert.That(() => _warehouseBusinessLogicContract.GetComponentByData(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_warehouseStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void InsertSupplies_CorrectRecord_Test()
{
// Arrange
var record = new WarehouseDataModel(Guid.NewGuid().ToString(), ComponentType.Panel, 1,
[new ComponentWarehouseDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]);
_warehouseStorageContract.Setup(x => x.AddElement(It.IsAny<WarehouseDataModel>()));
// Act
_warehouseBusinessLogicContract.InsertComponent(record);
// Assert
_warehouseStorageContract.Verify(x => x.AddElement(It.IsAny<WarehouseDataModel>()), Times.Once);
}
[Test]
public void InsertSupplies_RecordWithExistsData_ThrowException_Test()
{
// Arrange
_warehouseStorageContract.Setup(x => x.AddElement(It.IsAny<WarehouseDataModel>())).Throws(new ElementExistsException("Data", "Data"));
// Act & Assert
Assert.That(() => _warehouseBusinessLogicContract.InsertComponent(new(Guid.NewGuid().ToString(), ComponentType.Panel, 1,
[new ComponentWarehouseDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<ElementExistsException>());
_warehouseStorageContract.Verify(x => x.AddElement(It.IsAny<WarehouseDataModel>()), Times.Once);
}
[Test]
public void InsertSupplies_NullRecord_ThrowException_Test()
{
// Act & Assert
Assert.That(() => _warehouseBusinessLogicContract.InsertComponent(null), Throws.TypeOf<ArgumentNullException>());
_warehouseStorageContract.Verify(x => x.AddElement(It.IsAny<WarehouseDataModel>()), Times.Never);
}
[Test]
public void InsertComponents_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _warehouseBusinessLogicContract.InsertComponent(new WarehouseDataModel("id", ComponentType.Panel, 1, [])), Throws.TypeOf<ValidationException>());
_warehouseStorageContract.Verify(x => x.AddElement(It.IsAny<WarehouseDataModel>()), Times.Never);
}
[Test]
public void InsertSupplies_StorageThrowError_ThrowException_Test()
{
// Arrange
_warehouseStorageContract.Setup(x => x.AddElement(It.IsAny<WarehouseDataModel>())).Throws(new StorageException(new InvalidOperationException()));
// Act & Assert
Assert.That(() => _warehouseBusinessLogicContract.InsertComponent(new(Guid.NewGuid().ToString(), ComponentType.Panel, 1,
[new ComponentWarehouseDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<StorageException>());
_warehouseStorageContract.Verify(x => x.AddElement(It.IsAny<WarehouseDataModel>()), Times.Once);
}
[Test]
public void UpdateSupplies_CorrectRecord_Test()
{
// Arrange
var record = new WarehouseDataModel(Guid.NewGuid().ToString(), ComponentType.Panel, 1,
[new ComponentWarehouseDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]);
_warehouseStorageContract.Setup(x => x.UpdElement(It.IsAny<WarehouseDataModel>()));
// Act
_warehouseBusinessLogicContract.UpdateComponent(record);
// Assert
_warehouseStorageContract.Verify(x => x.UpdElement(It.IsAny<WarehouseDataModel>()), Times.Once);
}
[Test]
public void UpdateSupplies_RecordWithIncorrectData_ThrowException_Test()
{
// Arrange
_warehouseStorageContract.Setup(x => x.UpdElement(It.IsAny<WarehouseDataModel>())).Throws(new ElementNotFoundException(""));
// Act & Assert
Assert.That(() => _warehouseBusinessLogicContract.UpdateComponent(new(Guid.NewGuid().ToString(), ComponentType.Panel, 1,
[new ComponentWarehouseDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<ElementNotFoundException>());
_warehouseStorageContract.Verify(x => x.UpdElement(It.IsAny<WarehouseDataModel>()), Times.Once);
}
[Test]
public void UpdateSupplies_RecordWithExistsData_ThrowException_Test()
{
// Arrange
_warehouseStorageContract.Setup(x => x.UpdElement(It.IsAny<WarehouseDataModel>())).Throws(new ElementExistsException("Data", "Data"));
// Act & Assert
Assert.That(() => _warehouseBusinessLogicContract.UpdateComponent(new(Guid.NewGuid().ToString(), ComponentType.Panel, 1,
[new ComponentWarehouseDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<ElementExistsException>());
_warehouseStorageContract.Verify(x => x.UpdElement(It.IsAny<WarehouseDataModel>()), Times.Once);
}
[Test]
public void UpdateSupplies_NullRecord_ThrowException_Test()
{
// Act & Assert
Assert.That(() => _warehouseBusinessLogicContract.UpdateComponent(null), Throws.TypeOf<ArgumentNullException>());
_warehouseStorageContract.Verify(x => x.UpdElement(It.IsAny<WarehouseDataModel>()), Times.Never);
}
[Test]
public void UpdateComponents_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _warehouseBusinessLogicContract.UpdateComponent(new WarehouseDataModel(Guid.NewGuid().ToString(), ComponentType.Panel, 1, [])), Throws.TypeOf<ValidationException>());
_warehouseStorageContract.Verify(x => x.UpdElement(It.IsAny<WarehouseDataModel>()), Times.Never);
}
[Test]
public void UpdateSupplies_StorageThrowError_ThrowException_Test()
{
// Arrange
_warehouseStorageContract.Setup(x => x.UpdElement(It.IsAny<WarehouseDataModel>())).Throws(new StorageException(new InvalidOperationException()));
// Act & Assert
Assert.That(() => _warehouseBusinessLogicContract.UpdateComponent(new(Guid.NewGuid().ToString(), ComponentType.Panel, 1,
[new ComponentWarehouseDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<StorageException>());
_warehouseStorageContract.Verify(x => x.UpdElement(It.IsAny<WarehouseDataModel>()), Times.Once);
}
[Test]
public void DeleteComponents_CorrectRecord_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
var flag = false;
_warehouseStorageContract.Setup(x => x.DelElement(It.Is((string x) => x == id))).Callback(() => { flag = true; });
//Act
_warehouseBusinessLogicContract.DeleteComponent(id);
//Assert
_warehouseStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once); Assert.That(flag);
}
[Test]
public void DeleteComponents_RecordWithIncorrectId_ThrowException_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
_warehouseStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new ElementNotFoundException(id));
//Act&Assert
Assert.That(() => _warehouseBusinessLogicContract.DeleteComponent(Guid.NewGuid().ToString()),
Throws.TypeOf<ElementNotFoundException>());
_warehouseStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
}
[Test]
public void DeleteComponents_IdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _warehouseBusinessLogicContract.DeleteComponent(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _warehouseBusinessLogicContract.DeleteComponent(string.Empty), Throws.TypeOf<ArgumentNullException>());
_warehouseStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Never);
}
[Test]
public void DeleteComponents_IdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _warehouseBusinessLogicContract.DeleteComponent("id"),
Throws.TypeOf<ValidationException>());
_warehouseStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Never);
}
[Test]
public void DeleteComponents_StorageThrowError_ThrowException_Test()
{
//Arrange
_warehouseStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _warehouseBusinessLogicContract.DeleteComponent(Guid.NewGuid().ToString()),
Throws.TypeOf<StorageException>());
_warehouseStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
}
}

View File

@@ -29,7 +29,7 @@ internal class ComponentDataModelTests
{
var component = CreateDataModel(Guid.NewGuid().ToString(), null, ComponentType.Box);
Assert.That(() => component.Validate(), Throws.TypeOf<ValidationException>());
component = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, ComponentType.Box);
component = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, ComponentType.Box);
Assert.That(() => component.Validate(), Throws.TypeOf<ValidationException>());
}
@@ -40,6 +40,7 @@ internal class ComponentDataModelTests
Assert.That(() => component.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void AllFieldsIsCorrectTest()
{

View File

@@ -0,0 +1,70 @@
using FurnitureAssemblyContracts.DataModels;
using FurnitureAssemblyContracts.Exceptions;
namespace FurnitureAssemblyTests.DataModelsTests;
[TestFixture]
internal class ComponentSuppliesDataModelTests
{
[Test]
public void SuppliesIdIsNullOrEmptyTest()
{
var model = CreateDataModel(null, Guid.NewGuid().ToString(), 1);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
model = CreateDataModel(string.Empty, Guid.NewGuid().ToString(), 1);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void SuppliesIdIsNotGuidTest()
{
var model = CreateDataModel("id", Guid.NewGuid().ToString(), 1);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void ComponentIdIsNullOrEmptyTest()
{
var model = CreateDataModel(Guid.NewGuid().ToString(), null, 1);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
model = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, 1);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void ComponentIdIsNotGuidTest()
{
var model = CreateDataModel(Guid.NewGuid().ToString(), "id", 1);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void CountIsLessOrZeroTest()
{
var model = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 0);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
model = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), -1);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void AllFieldsIsCorrectTest()
{
var suppliesId = Guid.NewGuid().ToString();
var componentId = Guid.NewGuid().ToString();
var count = 1;
var model = CreateDataModel(suppliesId, componentId, count);
Assert.That(() => model.Validate(), Throws.Nothing);
Assert.Multiple(() =>
{
Assert.That(model.SuppliesId, Is.EqualTo(suppliesId));
Assert.That(model.ComponentId, Is.EqualTo(componentId));
Assert.That(model.Count, Is.EqualTo(count));
});
}
private static ComponentSuppliesDataModel CreateDataModel(string? suppliesId, string? componentId, int count)
=> new(suppliesId, componentId, count);
}

View File

@@ -0,0 +1,70 @@
using FurnitureAssemblyContracts.DataModels;
using FurnitureAssemblyContracts.Exceptions;
namespace FurnitureAssemblyTests.DataModelsTests;
[TestFixture]
internal class ComponentWarehouseDataModelTests
{
[Test]
public void WarehouseIdIsNullOrEmptyTest()
{
var model = CreateDataModel(null, Guid.NewGuid().ToString(), 1);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
model = CreateDataModel(string.Empty, Guid.NewGuid().ToString(), 1);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void WarehouseIdIsNotGuidTest()
{
var model = CreateDataModel("id", Guid.NewGuid().ToString(), 1);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void ComponentIdIsNullOrEmptyTest()
{
var model = CreateDataModel(Guid.NewGuid().ToString(), null, 1);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
model = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, 1);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void ComponentIdIsNotGuidTest()
{
var model = CreateDataModel(Guid.NewGuid().ToString(), "id", 1);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void CountIsLessOrZeroTest()
{
var model = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 0);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
model = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), -1);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void AllFieldsIsCorrectTest()
{
var warehouseId = Guid.NewGuid().ToString();
var componentId = Guid.NewGuid().ToString();
var count = 1;
var model = CreateDataModel(componentId, componentId, count);
Assert.That(() => model.Validate(), Throws.Nothing);
Assert.Multiple(() =>
{
Assert.That(model.WarehouseId, Is.EqualTo(componentId));
Assert.That(model.ComponentId, Is.EqualTo(componentId));
Assert.That(model.Count, Is.EqualTo(count));
});
}
private static ComponentWarehouseDataModel CreateDataModel(string? warehouseId, string? componentId, int count)
=> new(warehouseId, componentId, count);
}

View File

@@ -10,43 +10,43 @@ internal class PostDataModelTests
[Test]
public void IdIsNullOrEmptyTest()
{
var model = CreateDataModel(null, "name", PostType.Builder, 100, true, DateTime.Now);
var model = CreateDataModel(null, "name", PostType.Builder, 100);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
model = CreateDataModel(string.Empty, "name", PostType.Builder, 100, true, DateTime.Now);
model = CreateDataModel(string.Empty, "name", PostType.Builder, 100);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void IdIsNotGuidTest()
{
var model = CreateDataModel("id", "name", PostType.Builder, 100, true, DateTime.Now);
var model = CreateDataModel("id", "name", PostType.Builder, 100);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void PostNameIsNullOrEmptyTest()
{
var model = CreateDataModel(Guid.NewGuid().ToString(), null, PostType.Builder, 100, true, DateTime.Now);
var model = CreateDataModel(Guid.NewGuid().ToString(), null, PostType.Builder, 100);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
model = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, PostType.Builder, 100, true, DateTime.Now);
model = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, PostType.Builder, 100);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void PostTypeIsNoneTest()
{
var model = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.None, 100, true, DateTime.Now);
var model = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.None, 100);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void SalaryIsZeroNegativeTest()
{
var model = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.Builder, 0, true, DateTime.Now);
var model = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.Builder, 0);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
model = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.Builder, -1, true, DateTime.Now);
model = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.Builder, -1);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
}
@@ -59,7 +59,7 @@ internal class PostDataModelTests
var salary = 100.50;
var isActual = true;
var changeDate = DateTime.Now;
var model = CreateDataModel(id, postName, postType, salary, isActual, changeDate);
var model = CreateDataModel(id, postName, postType, salary);
Assert.That(() => model.Validate(), Throws.Nothing);
Assert.Multiple(() =>
@@ -68,11 +68,9 @@ internal class PostDataModelTests
Assert.That(model.PostName, Is.EqualTo(postName));
Assert.That(model.PostType, Is.EqualTo(postType));
Assert.That(model.Salary, Is.EqualTo(salary));
Assert.That(model.IsActual, Is.EqualTo(isActual));
Assert.That(model.ChangeDate, Is.EqualTo(changeDate));
});
}
private static PostDataModel CreateDataModel(string? id, string? postName, PostType postType, double salary, bool isActual, DateTime changeDate)
=> new(id, postName, postType, salary, isActual, changeDate);
private static PostDataModel CreateDataModel(string? id, string? postName, PostType postType, double salary)
=> new(id, postName, postType, salary);
}

View File

@@ -0,0 +1,77 @@
using FurnitureAssemblyContracts.DataModels;
using FurnitureAssemblyContracts.Enums;
using FurnitureAssemblyContracts.Exceptions;
namespace FurnitureAssemblyTests.DataModelsTests;
[TestFixture]
public class SuppliesDataModelTest
{
[Test]
public void IdIsNullOrEmptyTest()
{
var model = CreateDataModel(null, ComponentType.Handle, DateTime.Now, 1, CreateSuppliesDataModel());
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
model = CreateDataModel(string.Empty, ComponentType.Handle, DateTime.Now, 1, CreateSuppliesDataModel());
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void IdIsNotGuidTest()
{
var model = CreateDataModel("id", ComponentType.Handle, DateTime.Now, 1, CreateSuppliesDataModel());
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void TypeIsNoneTest()
{
var model = CreateDataModel(Guid.NewGuid().ToString(), ComponentType.None, DateTime.Now, 1, CreateSuppliesDataModel());
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void CountIsLessOrZeroTest()
{
var model = CreateDataModel(Guid.NewGuid().ToString(), ComponentType.None, DateTime.Now, 0, CreateSuppliesDataModel());
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
model = CreateDataModel(Guid.NewGuid().ToString(), ComponentType.None, DateTime.Now, -1, CreateSuppliesDataModel());
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void SuppliesIsEmptyOrNullTest()
{
var model = CreateDataModel(Guid.NewGuid().ToString(), ComponentType.None, DateTime.Now, 0, []);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
model = CreateDataModel(Guid.NewGuid().ToString(), ComponentType.None, DateTime.Now, 0, null);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void AllFieldsIsCorrectTest()
{
var id = Guid.NewGuid().ToString();
var type = ComponentType.Handle;
var date = DateTime.Now;
var count = 1;
var supplies = CreateSuppliesDataModel();
var model = CreateDataModel(id, type, date, count, supplies);
Assert.DoesNotThrow(() => model.Validate());
Assert.Multiple(() =>
{
Assert.That(model.Id, Is.EqualTo(id));
Assert.That(model.Type, Is.EqualTo(type));
Assert.That(model.ProductuionDate, Is.EqualTo(date));
Assert.That(model.Count, Is.EqualTo(count));
Assert.That(model.Components, Is.EqualTo(supplies));
});
}
private static SuppliesDataModel CreateDataModel(string? id, ComponentType type, DateTime date, int count, List<ComponentSuppliesDataModel> supplies)
=> new(id, type, date, count, supplies);
private static List<ComponentSuppliesDataModel> CreateSuppliesDataModel()
=> [new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 1)];
}

View File

@@ -0,0 +1,75 @@
using FurnitureAssemblyContracts.DataModels;
using FurnitureAssemblyContracts.Enums;
using FurnitureAssemblyContracts.Exceptions;
namespace FurnitureAssemblyTests.DataModelsTests;
[TestFixture]
internal class WorkhouseDataModelTests
{
[Test]
public void IdIsNullOrEmptyTest()
{
var model = CreateDataModel(null, ComponentType.Handle, 1, CreateWarehouseDataModel());
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
model = CreateDataModel(string.Empty, ComponentType.Handle, 1, CreateWarehouseDataModel());
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void IdIsNotGuidTest()
{
var model = CreateDataModel("id", ComponentType.Handle, 1, CreateWarehouseDataModel());
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void TypeIsNoneTest()
{
var model = CreateDataModel(Guid.NewGuid().ToString(), ComponentType.None, 1, CreateWarehouseDataModel());
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void CountIsLessOrZeroTest()
{
var model = CreateDataModel(Guid.NewGuid().ToString(), ComponentType.None, 0, CreateWarehouseDataModel());
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
model = CreateDataModel(Guid.NewGuid().ToString(), ComponentType.None, -1, CreateWarehouseDataModel());
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void WorkhouseIsEmptyOrNullTest()
{
var model = CreateDataModel(Guid.NewGuid().ToString(), ComponentType.None, 0, []);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
model = CreateDataModel(Guid.NewGuid().ToString(), ComponentType.None, 0, null);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void AllFieldsIsCorrectTest()
{
var id = Guid.NewGuid().ToString();
var type = ComponentType.Handle;
var count = 1;
var warehouse = CreateWarehouseDataModel();
var model = CreateDataModel(id, type, count, warehouse);
Assert.DoesNotThrow(() => model.Validate());
Assert.Multiple(() =>
{
Assert.That(model.Id, Is.EqualTo(id));
Assert.That(model.Type, Is.EqualTo(type));
Assert.That(model.Count, Is.EqualTo(count));
Assert.That(model.Components, Is.EqualTo(warehouse));
});
}
private static WarehouseDataModel CreateDataModel(string? id, ComponentType type, int count, List<ComponentWarehouseDataModel> warehouse)
=> new WarehouseDataModel(id, type, count, warehouse);
private static List<ComponentWarehouseDataModel> CreateWarehouseDataModel()
=> [new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 1)];
}

View File

@@ -8,8 +8,17 @@
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<Content Include="appsettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<ExcludeFromSingleFile>true</ExcludeFromSingleFile>
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
</Content>
</ItemGroup>
<ItemGroup>
<PackageReference Include="coverlet.collector" Version="6.0.2" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="9.0.3" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.12.0" />
<PackageReference Include="Moq" Version="4.20.72" />
<PackageReference Include="NUnit" Version="4.2.2" />
@@ -21,6 +30,7 @@
<ProjectReference Include="..\FurnitureAssemblyBusinessLogic\FurnitureAssemblyBusinessLogic.csproj" />
<ProjectReference Include="..\FurnitureAssemblyContracts\FurnitureAssemblyContracts.csproj" />
<ProjectReference Include="..\FurnitureAssemblyDatebase\FurnitureAssemblyDatebase.csproj" />
<ProjectReference Include="..\FurnitureAssemblyWebApi\FurnitureAssemblyWebApi.csproj" />
</ItemGroup>
<ItemGroup>

View File

@@ -0,0 +1,27 @@
using FurnitureAssemblyContracts.Infrastructure;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace FurnitureAssemblyTests.Infrastructure;
internal class CustomWebApplicationFactory<TProgram> : WebApplicationFactory<TProgram>
where TProgram : class
{
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder.ConfigureServices(services =>
{
var databaseConfig = services.SingleOrDefault(x => x.ServiceType == typeof(IConfigurationDatabase));
if (databaseConfig is not null)
services.Remove(databaseConfig);
var loggerFactory = services.SingleOrDefault(x => x.ServiceType == typeof(LoggerFactory));
if (loggerFactory is not null)
services.Remove(loggerFactory);
services.AddSingleton<IConfigurationDatabase, ConfigurationDateBaseTest>();
});
builder.UseEnvironment("Development");
base.ConfigureWebHost(builder);
}
}

View File

@@ -0,0 +1,113 @@
using FurnitureAssemblyContracts.Enums;
using FurnitureAssemblyDatebase;
using FurnitureAssemblyDatebase.Models;
using Microsoft.EntityFrameworkCore;
namespace FurnitureAssemblyTests.Infrastructure;
internal static class FurnitureAssemblyDbContextExtensions
{
public static Post InsertPostToDatabaseAndReturn(this FurnitureAssemblyDbContext dbContext, string? id = null, string postName = "test", PostType postType = PostType.Builder, double salary = 10, bool isActual = true, DateTime? changeDate = null)
{
var post = new Post() { Id = Guid.NewGuid().ToString(), PostId = id ?? Guid.NewGuid().ToString(), PostName = postName, PostType = postType, Salary = salary, IsActual = isActual, ChangeDate = changeDate ?? DateTime.UtcNow };
dbContext.Posts.Add(post);
dbContext.SaveChanges();
return post;
}
public static Worker InsertWorkerToDatabaseAndReturn(this FurnitureAssemblyDbContext dbContext, string? id = null, string fio = "Иванов И.И.", string? postId = null, DateTime? birthDate = null, DateTime? employmentDate = null, bool isDeleted = false)
{
var worker = new Worker() { Id = id ?? Guid.NewGuid().ToString(), FIO = fio, PostId = postId ?? Guid.NewGuid().ToString(), BirthDate = birthDate ?? DateTime.UtcNow.AddYears(-20), EmploymentDate = employmentDate ?? DateTime.UtcNow, IsDeleted = isDeleted };
dbContext.Workers.Add(worker);
dbContext.SaveChanges();
return worker;
}
public static Component InsertComponentToDatabaseAndReturn(this FurnitureAssemblyDbContext dbContext, string? id = null, string name = "test", ComponentType type = ComponentType.Panel, string? prevName = null, string? prevPrevName = null)
{
var component = new Component() { Id = id ?? Guid.NewGuid().ToString(), Name = name, Type = type, PrevName = prevName, PrevPrevName = prevPrevName};
dbContext.Components.Add(component);
dbContext.SaveChanges();
return component;
}
public static Furniture InsertFurnitureToDatabaseAndReturn(this FurnitureAssemblyDbContext dbContext, string? id = null, string? name = "test", int weight = 5, List<(string, int)>? components = null)
{
var furniture = new Furniture() { Id = id ?? Guid.NewGuid().ToString(), Name = name!, Weight = weight, Components = [] };
if (components is not null)
{
foreach (var elem in components)
{
furniture.Components.Add(new FurnitureComponent { FurnitureId = furniture.Id, ComponentId = elem.Item1, Count = elem.Item2 });
}
}
dbContext.Furnitures.Add(furniture);
dbContext.SaveChanges();
return furniture;
}
public static ManifacturingFurniture InsertManifacturingToDatabaseAndReturn(this FurnitureAssemblyDbContext dbContext, string workerId, string furnitureId, string? id = null, int count = 5)
{
var manifacturing = new ManifacturingFurniture() { Id = id ?? Guid.NewGuid().ToString(), WorkerId = workerId, FurnitureId = furnitureId, Count = count, ProductuionDate = DateTime.UtcNow };
dbContext.Manufacturing.Add(manifacturing);
dbContext.SaveChanges();
return manifacturing;
}
public static Salary InsertSalaryToDatabaseAndReturn(this FurnitureAssemblyDbContext dbContext, string workerId, double workerSalary = 1, DateTime? salaryDate = null)
{
var salary = new Salary() { WorkerId = workerId, WorkerSalary = workerSalary, SalaryDate = salaryDate ?? DateTime.UtcNow };
dbContext.Salaries.Add(salary);
dbContext.SaveChanges();
return salary;
}
public static Warehouse InsertWarehouseToDatabaseAndReturn(this FurnitureAssemblyDbContext dbContext, string? id = null, ComponentType type = ComponentType.Panel, int count = 20, List<(string, int)>? components = null)
{
var warehouse = new Warehouse() { Id = id ?? Guid.NewGuid().ToString(), Type = type, Count = count, Components = [] };
if (components is not null)
{
foreach (var elem in components)
{
warehouse.Components.Add(new ComponentWarehouse { WarehouseId = warehouse.Id, ComponentId = elem.Item1, Count = elem.Item2 });
}
}
dbContext.Warehouses.Add(warehouse);
dbContext.SaveChanges();
return warehouse;
}
public static Supplies InsertSuppliesToDatabaseAndReturn(this FurnitureAssemblyDbContext dbContext, string? id = null, ComponentType type = ComponentType.Panel, int count = 20, DateTime? date = null, List<(string, int)>? components = null)
{
var supply = new Supplies() { Id = id ?? Guid.NewGuid().ToString(), Type = type, Count = count, ProductuionDate = date ?? DateTime.UtcNow, Components = [] };
if (components is not null)
{
foreach (var elem in components)
{
supply.Components.Add(new ComponentSupplies { SuppliesId = supply.Id, ComponentId = elem.Item1, Count = elem.Item2 });
}
}
dbContext.Supplieses.Add(supply);
dbContext.SaveChanges();
return supply;
}
public static Post? GetPostFromDatabaseByPostId(this FurnitureAssemblyDbContext dbContext, string id) => dbContext.Posts.FirstOrDefault(x => x.PostId == id && x.IsActual);
public static Post[] GetPostsFromDatabaseByPostId(this FurnitureAssemblyDbContext dbContext, string id) => [.. dbContext.Posts.Where(x => x.PostId == id).OrderByDescending(x => x.ChangeDate)];
public static Worker? GetWorkerFromDatabaseById(this FurnitureAssemblyDbContext dbContext, string id) => dbContext.Workers.FirstOrDefault(x => x.Id == id);
public static Component? GetComponentFromDatabaseById(this FurnitureAssemblyDbContext dbContext, string id) => dbContext.Components.FirstOrDefault(x => x.Id == id);
public static Furniture? GetFurnitureFromDatabaseById(this FurnitureAssemblyDbContext dbContext, string id) => dbContext.Furnitures.Include(x => x.Components).FirstOrDefault(x => x.Id == id);
public static ManifacturingFurniture? GetManifacturingFromDatabaseById(this FurnitureAssemblyDbContext dbContext, string id) => dbContext.Manufacturing.FirstOrDefault(x => x.Id == id);
public static Salary[] GetSalariesFromDatabaseByWorkerId(this FurnitureAssemblyDbContext dbContext, string id) => [.. dbContext.Salaries.Where(x => x.WorkerId == id)];
public static Warehouse? GetWarehouseFromDatabaseById(this FurnitureAssemblyDbContext dbContext, string id) => dbContext.Warehouses.Include(x => x.Components).FirstOrDefault(x => x.Id == id);
public static Supplies? GetSuppliesFromDatabaseById(this FurnitureAssemblyDbContext dbContext, string id) => dbContext.Supplieses.Include(x => x.Components).FirstOrDefault(x => x.Id == id);
public static void RemovePostsFromDatabase(this FurnitureAssemblyDbContext dbContext) => dbContext.ExecuteSqlRaw("TRUNCATE \"Posts\" CASCADE;");
public static void RemoveWorkersFromDatabase(this FurnitureAssemblyDbContext dbContext) => dbContext.ExecuteSqlRaw("TRUNCATE \"Workers\" CASCADE;");
public static void RemoveComponentsFromDatabase(this FurnitureAssemblyDbContext dbContext) => dbContext.ExecuteSqlRaw("TRUNCATE \"Components\" CASCADE;");
public static void RemoveFurnituresFromDatabase(this FurnitureAssemblyDbContext dbContext) => dbContext.ExecuteSqlRaw("TRUNCATE \"Furnitures\" CASCADE;");
public static void RemoveManifacturingFromDatabase(this FurnitureAssemblyDbContext dbContext) => dbContext.ExecuteSqlRaw("TRUNCATE \"Manufacturing\" CASCADE;");
public static void RemoveSalariesFromDatabase(this FurnitureAssemblyDbContext dbContext) => dbContext.ExecuteSqlRaw("TRUNCATE \"Salaries\" CASCADE;");
public static void RemoveWarehousesFromDatabase(this FurnitureAssemblyDbContext dbContext) => dbContext.ExecuteSqlRaw("TRUNCATE \"Warehouses\" CASCADE;");
public static void RemoveSuppliesFromDatabase(this FurnitureAssemblyDbContext dbContext) => dbContext.ExecuteSqlRaw("TRUNCATE \"Supplieses\" CASCADE;");
private static void ExecuteSqlRaw(this FurnitureAssemblyDbContext dbContext, string command) => dbContext.Database.ExecuteSqlRaw(command);
}

View File

@@ -1,9 +1,9 @@
using Castle.Components.DictionaryAdapter.Xml;
using FurnitureAssemblyContracts.DataModels;
using FurnitureAssemblyContracts.DataModels;
using FurnitureAssemblyContracts.Enums;
using FurnitureAssemblyContracts.Exceptions;
using FurnitureAssemblyDatebase.Implementations;
using FurnitureAssemblyDatebase.Models;
using FurnitureAssemblyTests.Infrastructure;
using Microsoft.EntityFrameworkCore;
namespace FurnitureAssemblyTests.StorageContractTests;
@@ -23,15 +23,14 @@ internal class ComponentStorageContractTests : BaseStorageContractTest
public void TearDown()
{
FurnitureAssemblyDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Components\" CASCADE; ");
//FurnitureAssemblyDbContext.Database.ExecuteSqlRaw("TRUNCATE\"Manufacturers\" CASCADE;");
}
[Test]
public void Try_GetList_WhenHaveRecords_Test()
{
var component = InsertComponentToDatabaseAndReturn(Guid.NewGuid().ToString(), "Component 1");
InsertComponentToDatabaseAndReturn(Guid.NewGuid().ToString(), "Component 2");
InsertComponentToDatabaseAndReturn(Guid.NewGuid().ToString(), "Component 3");
var component = FurnitureAssemblyDbContext.InsertComponentToDatabaseAndReturn(Guid.NewGuid().ToString(), "Component 1");
FurnitureAssemblyDbContext.InsertComponentToDatabaseAndReturn(Guid.NewGuid().ToString(), "Component 2");
FurnitureAssemblyDbContext.InsertComponentToDatabaseAndReturn(name: "Component 3");
var list = _componentStorageContract.GetList();
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(3));
@@ -49,35 +48,35 @@ internal class ComponentStorageContractTests : BaseStorageContractTest
[Test]
public void Try_GetElementById_WhenHaveRecord_Test()
{
var component = InsertComponentToDatabaseAndReturn(Guid.NewGuid().ToString());
var component = FurnitureAssemblyDbContext.InsertComponentToDatabaseAndReturn();
AssertElement(_componentStorageContract.GetElementById(component.Id), component);
}
[Test]
public void Try_GetElementById_WhenNoRecord_Test()
{
InsertComponentToDatabaseAndReturn(Guid.NewGuid().ToString());
FurnitureAssemblyDbContext.InsertComponentToDatabaseAndReturn();
Assert.That(() => _componentStorageContract.GetElementById(Guid.NewGuid().ToString()), Is.Null);
}
[Test]
public void Try_GetElementByName_WhenHaveRecord_Test()
{
var component = InsertComponentToDatabaseAndReturn(Guid.NewGuid().ToString(), "Unique Name");
var component = FurnitureAssemblyDbContext.InsertComponentToDatabaseAndReturn();
AssertElement(_componentStorageContract.GetElementByName(component.Name), component);
}
[Test]
public void Try_GetElementByName_WhenNoRecord_Test()
{
InsertComponentToDatabaseAndReturn(Guid.NewGuid().ToString());
FurnitureAssemblyDbContext.InsertComponentToDatabaseAndReturn();
Assert.That(() => _componentStorageContract.GetElementByName("Non-existent Name"), Is.Null);
}
[Test]
public void Try_GetElementByOldName_WhenHaveRecord_Test()
{
var component = InsertComponentToDatabaseAndReturn(Guid.NewGuid().ToString(), "Current Name", ComponentType.Panel, "Previous Name", "Old Name");
var component = FurnitureAssemblyDbContext.InsertComponentToDatabaseAndReturn(name: "Current Name", prevName: "Previous Name", prevPrevName: "Old Name");
AssertElement(_componentStorageContract.GetElementByOldName(component.PrevName!), component);
AssertElement(_componentStorageContract.GetElementByOldName(component.PrevPrevName!), component);
}
@@ -85,7 +84,7 @@ internal class ComponentStorageContractTests : BaseStorageContractTest
[Test]
public void Try_GetElementByOldName_WhenNoRecord_Test()
{
InsertComponentToDatabaseAndReturn(Guid.NewGuid().ToString());
FurnitureAssemblyDbContext.InsertComponentToDatabaseAndReturn();
Assert.That(() => _componentStorageContract.GetElementByOldName("Non-existent Old Name"), Is.Null);
}
@@ -94,14 +93,14 @@ internal class ComponentStorageContractTests : BaseStorageContractTest
{
var component = CreateModel(Guid.NewGuid().ToString(), "New Component");
_componentStorageContract.AddElement(component);
AssertElement(GetComponentFromDatabase(component.Id), component);
AssertElement(FurnitureAssemblyDbContext.GetComponentFromDatabaseById(component.Id), component);
}
[Test]
public void Try_AddElement_WhenHaveRecordWithSameId_Test()
{
var component = CreateModel(Guid.NewGuid().ToString(), "Unique Name");
InsertComponentToDatabaseAndReturn(component.Id);
FurnitureAssemblyDbContext.InsertComponentToDatabaseAndReturn(component.Id);
Assert.That(() => _componentStorageContract.AddElement(component), Throws.TypeOf<ElementExistsException>());
}
@@ -109,7 +108,7 @@ internal class ComponentStorageContractTests : BaseStorageContractTest
public void Try_AddElement_WhenHaveRecordWithSameName_Test()
{
var component = CreateModel(Guid.NewGuid().ToString(), "Duplicate Name");
InsertComponentToDatabaseAndReturn(Guid.NewGuid().ToString(), component.Name);
FurnitureAssemblyDbContext.InsertComponentToDatabaseAndReturn(Guid.NewGuid().ToString(), component.Name);
Assert.That(() => _componentStorageContract.AddElement(component), Throws.TypeOf<ElementExistsException>());
}
@@ -117,9 +116,9 @@ internal class ComponentStorageContractTests : BaseStorageContractTest
public void Try_UpdElement_Test()
{
var component = CreateModel(Guid.NewGuid().ToString(), "Old Name", ComponentType.Panel, "Previous Name", "Old Name");
InsertComponentToDatabaseAndReturn(component.Id, name: component.Name!, type: component.Type!, prevName: component.PrevName!, prevPrevName: component.PrevPrevName!);
FurnitureAssemblyDbContext.InsertComponentToDatabaseAndReturn(component.Id, name: component.Name!, type: component.Type!, prevName: component.PrevName!, prevPrevName: component.PrevPrevName!);
_componentStorageContract.UpdElement(component);
AssertElement(GetComponentFromDatabase(component.Id), component);
AssertElement(FurnitureAssemblyDbContext.GetComponentFromDatabaseById(component.Id), component);
}
@@ -127,9 +126,9 @@ internal class ComponentStorageContractTests : BaseStorageContractTest
public void Try_UpdElement_WhenNoChangeName_Test()
{
var component = CreateModel(Guid.NewGuid().ToString(), "Same Name", ComponentType.Panel, "Previous Name", "Old Name");
InsertComponentToDatabaseAndReturn(component.Id, component.Name, component.Type, component.PrevName, component.PrevPrevName);
FurnitureAssemblyDbContext.InsertComponentToDatabaseAndReturn(component.Id, component.Name, component.Type, component.PrevName, component.PrevPrevName);
_componentStorageContract.UpdElement(component);
AssertElement(GetComponentFromDatabase(component.Id), component);
AssertElement(FurnitureAssemblyDbContext.GetComponentFromDatabaseById(component.Id), component);
}
[Test]
@@ -142,17 +141,17 @@ internal class ComponentStorageContractTests : BaseStorageContractTest
public void Try_UpdElement_WhenHaveRecordWithSameName_Test()
{
var component = CreateModel(Guid.NewGuid().ToString(), "Duplicate Name");
InsertComponentToDatabaseAndReturn(component.Id, "Old Name");
InsertComponentToDatabaseAndReturn(Guid.NewGuid().ToString(), component.Name);
FurnitureAssemblyDbContext.InsertComponentToDatabaseAndReturn(component.Id, "Old Name");
FurnitureAssemblyDbContext.InsertComponentToDatabaseAndReturn(name: component.Name);
Assert.That(() => _componentStorageContract.UpdElement(component), Throws.TypeOf<ElementExistsException>());
}
[Test]
public void Try_DelElement_Test()
{
var component = InsertComponentToDatabaseAndReturn(Guid.NewGuid().ToString());
var component = FurnitureAssemblyDbContext.InsertComponentToDatabaseAndReturn();
_componentStorageContract.DelElement(component.Id);
var element = GetComponentFromDatabase(component.Id);
var element = FurnitureAssemblyDbContext.GetComponentFromDatabaseById(component.Id);
Assert.That(element, Is.Null);
}
@@ -162,14 +161,6 @@ internal class ComponentStorageContractTests : BaseStorageContractTest
Assert.That(() => _componentStorageContract.DelElement(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
}
private Component InsertComponentToDatabaseAndReturn(string id, string name = "test", ComponentType type = ComponentType.Panel, string prevName = "prevname", string prevPrevName = "prevprevname")
{
var component = new Component { Id = id, Name = name, Type = type, PrevName = prevName, PrevPrevName = prevPrevName };
FurnitureAssemblyDbContext.Components.Add(component);
FurnitureAssemblyDbContext.SaveChanges();
return component;
}
private static void AssertElement(ComponentDataModel? actual, Component expected)
{
Assert.That(actual, Is.Not.Null);
@@ -186,8 +177,6 @@ internal class ComponentStorageContractTests : BaseStorageContractTest
private static ComponentDataModel CreateModel(string id, string name = "test", ComponentType type = ComponentType.Panel, string prevName = "prevname", string prevPrevName = "prevprevname")
=> new(id, name, type, prevName, prevPrevName);
private Component? GetComponentFromDatabase(string id) => FurnitureAssemblyDbContext.Components.FirstOrDefault(x => x.Id == id);
private static void AssertElement(Component? actual, ComponentDataModel expected)
{
Assert.That(actual, Is.Not.Null);

View File

@@ -2,7 +2,7 @@
using FurnitureAssemblyContracts.Exceptions;
using FurnitureAssemblyDatebase;
using FurnitureAssemblyDatebase.Models;
using Microsoft.EntityFrameworkCore;
using FurnitureAssemblyTests.Infrastructure;
namespace FurnitureAssemblyTests.StorageContractTests;
@@ -20,15 +20,15 @@ internal class FurnitureStorageContractTests : BaseStorageContractTest
[TearDown]
public void TearDown()
{
FurnitureAssemblyDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Furnitures\" CASCADE;");
FurnitureAssemblyDbContext.RemoveFurnituresFromDatabase();
}
[Test]
public void Try_GetList_WhenHaveRecords_Test()
{
var furniture = InsertFurnitureToDatabaseAndReturn(Guid.NewGuid().ToString(), "Furniture 1");
InsertFurnitureToDatabaseAndReturn(Guid.NewGuid().ToString(), "Furniture 2");
InsertFurnitureToDatabaseAndReturn(Guid.NewGuid().ToString(), "Furniture 3");
var furniture = FurnitureAssemblyDbContext.InsertFurnitureToDatabaseAndReturn(name: "Furniture 1");
FurnitureAssemblyDbContext.InsertFurnitureToDatabaseAndReturn(name: "Furniture 2");
FurnitureAssemblyDbContext.InsertFurnitureToDatabaseAndReturn(name: "Furniture 3");
var list = _furnitureStorageContract.GetList();
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(3));
@@ -46,29 +46,29 @@ internal class FurnitureStorageContractTests : BaseStorageContractTest
[Test]
public void Try_GetElementById_WhenHaveRecord_Test()
{
var furniture = InsertFurnitureToDatabaseAndReturn(Guid.NewGuid().ToString());
var furniture = FurnitureAssemblyDbContext.InsertFurnitureToDatabaseAndReturn();
AssertElement(_furnitureStorageContract.GetElementById(furniture.Id), furniture);
}
[Test]
public void Try_GetElementById_WhenNoRecord_Test()
{
InsertFurnitureToDatabaseAndReturn(Guid.NewGuid().ToString());
Assert.That(() => _furnitureStorageContract.GetElementById(Guid.NewGuid().ToString()), Is.Null);
FurnitureAssemblyDbContext.InsertFurnitureToDatabaseAndReturn();
Assert.That(() => FurnitureAssemblyDbContext.GetFurnitureFromDatabaseById(Guid.NewGuid().ToString()), Is.Null);
}
[Test]
public void Try_GetElementByName_WhenHaveRecord_Test()
{
var furniture = InsertFurnitureToDatabaseAndReturn(Guid.NewGuid().ToString(), "Unique Name");
var furniture = FurnitureAssemblyDbContext.InsertFurnitureToDatabaseAndReturn(name: "Unique Name");
AssertElement(_furnitureStorageContract.GetElementByName(furniture.Name), furniture);
}
[Test]
public void Try_GetElementByName_WhenNoRecord_Test()
{
InsertFurnitureToDatabaseAndReturn(Guid.NewGuid().ToString());
Assert.That(() => _furnitureStorageContract.GetElementByName("Non-existent Name"), Is.Null);
FurnitureAssemblyDbContext.InsertFurnitureToDatabaseAndReturn();
Assert.That(() => FurnitureAssemblyDbContext.GetFurnitureFromDatabaseById("Non-existent Name"), Is.Null);
}
[Test]
@@ -76,14 +76,14 @@ internal class FurnitureStorageContractTests : BaseStorageContractTest
{
var furniture = CreateModel(Guid.NewGuid().ToString(), "New Furniture");
_furnitureStorageContract.AddElement(furniture);
AssertElement(GetFurnitureFromDatabase(furniture.Id), furniture);
AssertElement(FurnitureAssemblyDbContext.GetFurnitureFromDatabaseById(furniture.Id), furniture);
}
[Test]
public void Try_AddElement_WhenHaveRecordWithSameId_Test()
{
var furniture = CreateModel(Guid.NewGuid().ToString(), "Unique Name");
InsertFurnitureToDatabaseAndReturn(furniture.Id);
FurnitureAssemblyDbContext.InsertFurnitureToDatabaseAndReturn(furniture.Id);
Assert.That(() => _furnitureStorageContract.AddElement(furniture), Throws.TypeOf<ElementExistsException>());
}
@@ -91,7 +91,7 @@ internal class FurnitureStorageContractTests : BaseStorageContractTest
public void Try_AddElement_WhenHaveRecordWithSameName_Test()
{
var furniture = CreateModel(Guid.NewGuid().ToString(), "Duplicate Name");
InsertFurnitureToDatabaseAndReturn(Guid.NewGuid().ToString(), furniture.Name);
FurnitureAssemblyDbContext.InsertFurnitureToDatabaseAndReturn(Guid.NewGuid().ToString(), furniture.Name);
Assert.That(() => _furnitureStorageContract.AddElement(furniture), Throws.TypeOf<ElementExistsException>());
}
@@ -99,18 +99,18 @@ internal class FurnitureStorageContractTests : BaseStorageContractTest
public void Try_UpdElement_Test()
{
var furniture = CreateModel(Guid.NewGuid().ToString(), "Old Name");
InsertFurnitureToDatabaseAndReturn(furniture.Id, name: furniture.Name!);
FurnitureAssemblyDbContext.InsertFurnitureToDatabaseAndReturn(furniture.Id, name: furniture.Name!);
_furnitureStorageContract.UpdElement(furniture);
AssertElement(GetFurnitureFromDatabase(furniture.Id), furniture);
AssertElement(FurnitureAssemblyDbContext.GetFurnitureFromDatabaseById(furniture.Id), furniture);
}
[Test]
public void Try_UpdElement_WhenNoChangeName_Test()
{
var furniture = CreateModel(Guid.NewGuid().ToString(), "Same Name");
InsertFurnitureToDatabaseAndReturn(furniture.Id, furniture.Name);
FurnitureAssemblyDbContext.InsertFurnitureToDatabaseAndReturn(furniture.Id, furniture.Name);
_furnitureStorageContract.UpdElement(furniture);
AssertElement(GetFurnitureFromDatabase(furniture.Id), furniture);
AssertElement(FurnitureAssemblyDbContext.GetFurnitureFromDatabaseById(furniture.Id), furniture);
}
[Test]
@@ -123,17 +123,17 @@ internal class FurnitureStorageContractTests : BaseStorageContractTest
public void Try_UpdElement_WhenHaveRecordWithSameName_Test()
{
var furniture = CreateModel(Guid.NewGuid().ToString(), "Duplicate Name");
InsertFurnitureToDatabaseAndReturn(furniture.Id, "Old Name");
InsertFurnitureToDatabaseAndReturn(Guid.NewGuid().ToString(), furniture.Name);
FurnitureAssemblyDbContext.InsertFurnitureToDatabaseAndReturn(furniture.Id, "Old Name");
FurnitureAssemblyDbContext.InsertFurnitureToDatabaseAndReturn(Guid.NewGuid().ToString(), furniture.Name);
Assert.That(() => _furnitureStorageContract.UpdElement(furniture), Throws.TypeOf<ElementExistsException>());
}
[Test]
public void Try_DelElement_Test()
{
var furniture = InsertFurnitureToDatabaseAndReturn(Guid.NewGuid().ToString());
var furniture = FurnitureAssemblyDbContext.InsertFurnitureToDatabaseAndReturn(Guid.NewGuid().ToString());
_furnitureStorageContract.DelElement(furniture.Id);
var element = GetFurnitureFromDatabase(furniture.Id);
var element = FurnitureAssemblyDbContext.GetFurnitureFromDatabaseById(furniture.Id);
Assert.That(element, Is.Null);
}
@@ -143,14 +143,6 @@ internal class FurnitureStorageContractTests : BaseStorageContractTest
Assert.That(() => _furnitureStorageContract.DelElement(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
}
private Furniture InsertFurnitureToDatabaseAndReturn(string id, string name = "test")
{
var furniture = new Furniture { Id = id, Name = name };
FurnitureAssemblyDbContext.Furnitures.Add(furniture);
FurnitureAssemblyDbContext.SaveChanges();
return furniture;
}
private static void AssertElement(FurnitureDataModel? actual, Furniture expected)
{
Assert.That(actual, Is.Not.Null);
@@ -164,8 +156,6 @@ internal class FurnitureStorageContractTests : BaseStorageContractTest
private static FurnitureDataModel CreateModel(string id, string name = "test", int weight = 0)
=> new(id, name, weight, []);
private Furniture? GetFurnitureFromDatabase(string id) => FurnitureAssemblyDbContext.Furnitures.FirstOrDefault(x => x.Id == id);
private static void AssertElement(Furniture? actual, FurnitureDataModel expected)
{
Assert.That(actual, Is.Not.Null);

View File

@@ -2,6 +2,7 @@
using FurnitureAssemblyContracts.Exceptions;
using FurnitureAssemblyDatebase.Implementations;
using FurnitureAssemblyDatebase.Models;
using FurnitureAssemblyTests.Infrastructure;
using Microsoft.EntityFrameworkCore;
namespace FurnitureAssemblyTests.StorageContractTests;
@@ -17,24 +18,24 @@ internal class ManifacturingStorageContractTests : BaseStorageContractTest
public void SetUp()
{
_manifacturingStorageContract = new ManifacturingStorageContract(FurnitureAssemblyDbContext);
_worker = InsertWorkerToDatabaseAndReturn();
_furniture = InsertFurnitureToDatabaseAndReturn();
_worker = FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn();
_furniture = FurnitureAssemblyDbContext.InsertFurnitureToDatabaseAndReturn();
}
[TearDown]
public void TearDown()
{
FurnitureAssemblyDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Furnitures\" CASCADE;");
FurnitureAssemblyDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Manufacturing\" CASCADE;");
FurnitureAssemblyDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Workers\" CASCADE;");
FurnitureAssemblyDbContext.RemoveComponentsFromDatabase();
FurnitureAssemblyDbContext.RemoveFurnituresFromDatabase();
FurnitureAssemblyDbContext.RemoveWorkersFromDatabase();
}
[Test]
public void Try_GetList_WhenHaveRecords_Test()
{
var manufacturing = InsertManufacturingToDatabaseAndReturn(Guid.NewGuid().ToString(), _furniture.Id, 5, _worker.Id);
InsertManufacturingToDatabaseAndReturn(Guid.NewGuid().ToString(), _furniture.Id, 5, _worker.Id);
InsertManufacturingToDatabaseAndReturn(Guid.NewGuid().ToString(), _furniture.Id, 5, _worker.Id);
var manufacturing = FurnitureAssemblyDbContext.InsertManifacturingToDatabaseAndReturn(_worker.Id, _furniture.Id);
FurnitureAssemblyDbContext.InsertManifacturingToDatabaseAndReturn(_worker.Id, _furniture.Id);
FurnitureAssemblyDbContext.InsertManifacturingToDatabaseAndReturn(_worker.Id, _furniture.Id);
var list = _manifacturingStorageContract.GetList();
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(3));
@@ -52,10 +53,9 @@ internal class ManifacturingStorageContractTests : BaseStorageContractTest
[Test]
public void Try_GetList_ByWorker_Test()
{
var worker = InsertWorkerToDatabaseAndReturn("Other worker");
InsertManufacturingToDatabaseAndReturn(Guid.NewGuid().ToString(), _furniture.Id, 5, _worker.Id);
InsertManufacturingToDatabaseAndReturn(Guid.NewGuid().ToString(), _furniture.Id, 5, _worker.Id);
InsertManufacturingToDatabaseAndReturn(Guid.NewGuid().ToString(), _furniture.Id, 5, worker.Id);
var worker = FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(fio: "Other worker");
FurnitureAssemblyDbContext.InsertManifacturingToDatabaseAndReturn(_worker.Id, _furniture.Id);
FurnitureAssemblyDbContext.InsertManifacturingToDatabaseAndReturn(_worker.Id, _furniture.Id);
var list = _manifacturingStorageContract.GetList(workerId: _worker.Id);
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(2));
@@ -65,10 +65,10 @@ internal class ManifacturingStorageContractTests : BaseStorageContractTest
[Test]
public void Try_GetList_ByFurniture_Test()
{
var furniture = InsertFurnitureToDatabaseAndReturn("Other furniture");
InsertManufacturingToDatabaseAndReturn(Guid.NewGuid().ToString(), _furniture.Id, 5, _worker.Id);
InsertManufacturingToDatabaseAndReturn(Guid.NewGuid().ToString(), _furniture.Id, 5, _worker.Id);
InsertManufacturingToDatabaseAndReturn(Guid.NewGuid().ToString(), furniture.Id, 5, _worker.Id);
var furniture = FurnitureAssemblyDbContext.InsertFurnitureToDatabaseAndReturn(name: "Other furniture");
FurnitureAssemblyDbContext.InsertManifacturingToDatabaseAndReturn(_worker.Id, _furniture.Id);
FurnitureAssemblyDbContext.InsertManifacturingToDatabaseAndReturn(_worker.Id, _furniture.Id);
FurnitureAssemblyDbContext.InsertManifacturingToDatabaseAndReturn(_worker.Id, furniture.Id);
var list = _manifacturingStorageContract.GetList(furnitureId: _furniture.Id);
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(2));
@@ -78,14 +78,14 @@ internal class ManifacturingStorageContractTests : BaseStorageContractTest
[Test]
public void Try_GetElementById_WhenHaveRecord_Test()
{
var manufacturing = InsertManufacturingToDatabaseAndReturn(Guid.NewGuid().ToString(), _furniture.Id, 5, _worker.Id);
var manufacturing = FurnitureAssemblyDbContext.InsertManifacturingToDatabaseAndReturn(_worker.Id, _furniture.Id);
AssertElement(_manifacturingStorageContract.GetElementById(manufacturing.Id), manufacturing);
}
[Test]
public void Try_GetElementById_WhenNoRecord_Test()
{
InsertManufacturingToDatabaseAndReturn(Guid.NewGuid().ToString(), _furniture.Id, 5, _worker.Id);
FurnitureAssemblyDbContext.InsertManifacturingToDatabaseAndReturn(_worker.Id, _furniture.Id);
Assert.That(() => _manifacturingStorageContract.GetElementById(Guid.NewGuid().ToString()), Is.Null);
}
@@ -94,14 +94,14 @@ internal class ManifacturingStorageContractTests : BaseStorageContractTest
{
var manufacturing = CreateModel(Guid.NewGuid().ToString(), _furniture.Id, 5, _worker.Id);
_manifacturingStorageContract.AddElement(manufacturing);
AssertElement(GetManufacturingFromDatabaseById(manufacturing.Id), manufacturing);
AssertElement(FurnitureAssemblyDbContext.GetManifacturingFromDatabaseById(manufacturing.Id), manufacturing);
}
[Test]
public void Try_AddElement_WhenHaveRecordWithSameId_Test()
{
var manufacturing = CreateModel(Guid.NewGuid().ToString(), _furniture.Id, 5, _worker.Id);
InsertManufacturingToDatabaseAndReturn(manufacturing.Id, _furniture.Id, 5, _worker.Id);
FurnitureAssemblyDbContext.InsertManifacturingToDatabaseAndReturn(_worker.Id, _furniture.Id, id: manufacturing.Id);
Assert.That(() => _manifacturingStorageContract.AddElement(manufacturing), Throws.TypeOf<StorageException>());
}
@@ -109,9 +109,9 @@ internal class ManifacturingStorageContractTests : BaseStorageContractTest
public void Try_UpdElement_Test()
{
var manufacturing = CreateModel(Guid.NewGuid().ToString(), _furniture.Id, 5, _worker.Id);
InsertManufacturingToDatabaseAndReturn(manufacturing.Id, _furniture.Id, 5, _worker.Id);
FurnitureAssemblyDbContext.InsertManifacturingToDatabaseAndReturn(_worker.Id, _furniture.Id, id: manufacturing.Id);
_manifacturingStorageContract.UpdElement(manufacturing);
AssertElement(GetManufacturingFromDatabaseById(manufacturing.Id), manufacturing);
AssertElement(FurnitureAssemblyDbContext.GetManifacturingFromDatabaseById(manufacturing.Id), manufacturing);
}
[Test]
@@ -120,30 +120,6 @@ internal class ManifacturingStorageContractTests : BaseStorageContractTest
Assert.That(() => _manifacturingStorageContract.UpdElement(CreateModel(Guid.NewGuid().ToString(), _furniture.Id, 5, _worker.Id)), Throws.TypeOf<ElementNotFoundException>());
}
private Worker InsertWorkerToDatabaseAndReturn(string workerFIO = "fio")
{
var worker = new Worker() { Id = Guid.NewGuid().ToString(), PostId = Guid.NewGuid().ToString(), FIO = workerFIO, IsDeleted = false };
FurnitureAssemblyDbContext.Workers.Add(worker);
FurnitureAssemblyDbContext.SaveChanges();
return worker;
}
private Furniture InsertFurnitureToDatabaseAndReturn(string furnitureName = "furniture", int weight = 5)
{
var furniture = new Furniture() { Id = Guid.NewGuid().ToString(), Name = furnitureName, Weight = weight };
FurnitureAssemblyDbContext.Furnitures.Add(furniture);
FurnitureAssemblyDbContext.SaveChanges();
return furniture;
}
private ManifacturingFurniture InsertManufacturingToDatabaseAndReturn(string id, string furnitureId, int count, string workerId)
{
var manufacturing = new ManifacturingFurniture() { Id = id, FurnitureId = furnitureId, Count = count, WorkerId = workerId };
FurnitureAssemblyDbContext.Manufacturing.Add(manufacturing);
FurnitureAssemblyDbContext.SaveChanges();
return manufacturing;
}
private static void AssertElement(ManifacturingFurnitureDataModel? actual, ManifacturingFurniture expected)
{
Assert.That(actual, Is.Not.Null);
@@ -161,9 +137,6 @@ internal class ManifacturingStorageContractTests : BaseStorageContractTest
return new(id, furnitureId, count, workerId);
}
private ManifacturingFurniture? GetManufacturingFromDatabaseById(string id) =>
FurnitureAssemblyDbContext.Manufacturing.FirstOrDefault(x => x.Id == id);
private static void AssertElement(ManifacturingFurniture? actual, ManifacturingFurnitureDataModel expected)
{
Assert.That(actual, Is.Not.Null);

View File

@@ -3,7 +3,7 @@ using FurnitureAssemblyContracts.Enums;
using FurnitureAssemblyContracts.Exceptions;
using FurnitureAssemblyDatebase.Implementations;
using FurnitureAssemblyDatebase.Models;
using Microsoft.EntityFrameworkCore;
using FurnitureAssemblyTests.Infrastructure;
namespace FurnitureAssemblyTests.StorageContractTests;
@@ -21,16 +21,15 @@ internal class PostStorageContractTests : BaseStorageContractTest
[TearDown]
public void TearDown()
{
FurnitureAssemblyDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Posts\"CASCADE; ");
FurnitureAssemblyDbContext.RemovePostsFromDatabase();
}
[Test]
public void Try_GetList_WhenHaveRecords_Test()
{
var post = InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(),
"name 1");
InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 2");
InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 3");
var post = FurnitureAssemblyDbContext.InsertPostToDatabaseAndReturn(postName: "name 1");
FurnitureAssemblyDbContext.InsertPostToDatabaseAndReturn(postName: "name 2");
FurnitureAssemblyDbContext.InsertPostToDatabaseAndReturn(postName: "name 3");
var list = _postStorageContract.GetList();
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(3));
@@ -45,44 +44,13 @@ internal class PostStorageContractTests : BaseStorageContractTest
Assert.That(list, Is.Empty);
}
[Test]
public void Try_GetList_OnlyActual_Test()
{
InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 1", isActual: true);
InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 2", isActual: true);
InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 3", isActual: false);
var list = _postStorageContract.GetList(onlyActual: true);
Assert.That(list, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(list, Has.Count.EqualTo(2));
Assert.That(!list.Any(x => !x.IsActual));
});
}
[Test]
public void Try_GetList_IncludeNoActual_Test()
{
InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 1", isActual: true);
InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 2", isActual: true);
InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 3", isActual: false);
var list = _postStorageContract.GetList(onlyActual: false);
Assert.That(list, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(list, Has.Count.EqualTo(3));
Assert.That(list.Count(x => x.IsActual), Is.EqualTo(2));
Assert.That(list.Count(x => !x.IsActual), Is.EqualTo(1));
});
}
[Test]
public void Try_GetPostWithHistory_WhenHaveRecords_Test()
{
var postId = Guid.NewGuid().ToString();
InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 1", isActual: true);
InsertPostToDatabaseAndReturn(postId, "name 2", isActual: true);
InsertPostToDatabaseAndReturn(postId, "name 2", isActual: false);
FurnitureAssemblyDbContext.InsertPostToDatabaseAndReturn(postName: "name 1", isActual: true);
FurnitureAssemblyDbContext.InsertPostToDatabaseAndReturn(postId, "name 2", isActual: true);
FurnitureAssemblyDbContext.InsertPostToDatabaseAndReturn(postId, "name 2", isActual: false);
var list = _postStorageContract.GetPostWithHistory(postId);
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(2));
@@ -92,9 +60,9 @@ internal class PostStorageContractTests : BaseStorageContractTest
public void Try_GetPostWithHistory_WhenNoRecords_Test()
{
var postId = Guid.NewGuid().ToString();
InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 1", isActual: true);
InsertPostToDatabaseAndReturn(postId, "name 2", isActual: true);
InsertPostToDatabaseAndReturn(postId, "name 2", isActual: false);
FurnitureAssemblyDbContext.InsertPostToDatabaseAndReturn(postName: "name 1", isActual: true);
FurnitureAssemblyDbContext.InsertPostToDatabaseAndReturn(postId, "name 2", isActual: true);
FurnitureAssemblyDbContext.InsertPostToDatabaseAndReturn(postId, "name 2", isActual: false);
var list = _postStorageContract.GetPostWithHistory(Guid.NewGuid().ToString());
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
@@ -103,148 +71,118 @@ internal class PostStorageContractTests : BaseStorageContractTest
[Test]
public void Try_GetElementById_WhenHaveRecord_Test()
{
var post = InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString());
var post = FurnitureAssemblyDbContext.InsertPostToDatabaseAndReturn();
AssertElement(_postStorageContract.GetElementById(post.PostId), post);
}
[Test]
public void Try_GetElementById_WhenNoRecord_Test()
{
InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString());
FurnitureAssemblyDbContext.InsertPostToDatabaseAndReturn();
Assert.That(() => _postStorageContract.GetElementById(Guid.NewGuid().ToString()), Is.Null);
}
[Test]
public void Try_GetElementById_WhenRecordHasDeleted_Test()
public void Try_GetElementById_WhenRecordWasDeleted_Test()
{
var post = InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), isActual: false);
var post = FurnitureAssemblyDbContext.InsertPostToDatabaseAndReturn(isActual: false);
Assert.That(() => _postStorageContract.GetElementById(post.PostId), Is.Null);
}
[Test]
public void Try_GetElementById_WhenTrySearchById_Test()
{
var post = InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString());
var post = FurnitureAssemblyDbContext.InsertPostToDatabaseAndReturn();
Assert.That(() => _postStorageContract.GetElementById(post.Id), Is.Null);
}
[Test]
public void Try_GetElementByName_WhenHaveRecord_Test()
{
var post = InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString());
AssertElement(_postStorageContract.GetElementByName(post.PostName),
post);
var post = FurnitureAssemblyDbContext.InsertPostToDatabaseAndReturn();
AssertElement(_postStorageContract.GetElementByName(post.PostName), post);
}
[Test]
public void Try_GetElementByName_WhenNoRecord_Test()
{
InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString());
FurnitureAssemblyDbContext.InsertPostToDatabaseAndReturn();
Assert.That(() => _postStorageContract.GetElementByName("name"), Is.Null);
}
[Test]
public void Try_GetElementByName_WhenRecordHasDeleted_Test()
public void Try_GetElementByName_WhenRecordWasDeleted_Test()
{
var post = InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), isActual: false);
var post = FurnitureAssemblyDbContext.InsertPostToDatabaseAndReturn(isActual: false);
Assert.That(() => _postStorageContract.GetElementById(post.PostName), Is.Null);
}
[Test]
public void Try_AddElement_Test()
{
var post = CreateModel(Guid.NewGuid().ToString(), isActual: true);
var post = CreateModel(Guid.NewGuid().ToString());
_postStorageContract.AddElement(post);
AssertElement(GetPostFromDatabaseByPostId(post.Id), post);
}
[Test]
public void Try_AddElement_WhenActualIsFalse_Test()
{
var post = CreateModel(Guid.NewGuid().ToString(), isActual: false);
Assert.That(() => _postStorageContract.AddElement(post),
Throws.Nothing);
AssertElement(GetPostFromDatabaseByPostId(post.Id),
CreateModel(post.Id, isActual: true));
AssertElement(FurnitureAssemblyDbContext.GetPostFromDatabaseByPostId(post.Id), post);
}
[Test]
public void Try_AddElement_WhenHaveRecordWithSameName_Test()
{
var post = CreateModel(Guid.NewGuid().ToString(), "name unique", isActual: true);
InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), postName: post.PostName, isActual: true);
Assert.That(() => _postStorageContract.AddElement(post),
Throws.TypeOf<ElementExistsException>());
var post = CreateModel(Guid.NewGuid().ToString(), "name unique");
FurnitureAssemblyDbContext.InsertPostToDatabaseAndReturn(postName: post.PostName, isActual: true);
Assert.That(() => _postStorageContract.AddElement(post), Throws.TypeOf<ElementExistsException>());
}
[Test]
public void
Try_AddElement_WhenHaveRecordWithSamePostIdAndActualIsTrue_Test()
public void Try_AddElement_WhenHaveRecordWithSamePostId_Test()
{
var post = CreateModel(Guid.NewGuid().ToString(), isActual: true);
InsertPostToDatabaseAndReturn(post.Id, isActual: true);
Assert.That(() => _postStorageContract.AddElement(post),
Throws.TypeOf<ElementExistsException>());
var post = CreateModel(Guid.NewGuid().ToString());
FurnitureAssemblyDbContext.InsertPostToDatabaseAndReturn(post.Id, isActual: true);
Assert.That(() => _postStorageContract.AddElement(post), Throws.TypeOf<ElementExistsException>());
}
[Test]
public void Try_UpdElement_Test()
{
var post = CreateModel(Guid.NewGuid().ToString());
InsertPostToDatabaseAndReturn(post.Id, isActual: true);
FurnitureAssemblyDbContext.InsertPostToDatabaseAndReturn(post.Id, isActual: true);
_postStorageContract.UpdElement(post);
var posts = FurnitureAssemblyDbContext.Posts.Where(x => x.PostId == post.Id).OrderByDescending(x => x.ChangeDate);
Assert.That(posts.Count(), Is.EqualTo(2));
AssertElement(posts.First(), CreateModel(post.Id, isActual: true));
AssertElement(posts.Last(), CreateModel(post.Id, isActual: false));
}
[Test]
public void Try_UpdElement_WhenActualIsFalse_Test()
{
var post = CreateModel(Guid.NewGuid().ToString(), isActual: false);
InsertPostToDatabaseAndReturn(post.Id, isActual: true);
_postStorageContract.UpdElement(post);
AssertElement(GetPostFromDatabaseByPostId(post.Id),
CreateModel(post.Id, isActual: true));
var posts = FurnitureAssemblyDbContext.GetPostsFromDatabaseByPostId(post.Id);
Assert.That(posts, Is.Not.Null);
Assert.That(posts, Has.Length.EqualTo(2));
AssertElement(posts[0], CreateModel(post.Id));
AssertElement(posts[^1], CreateModel(post.Id));
}
[Test]
public void Try_UpdElement_WhenNoRecordWithThisId_Test()
{
Assert.That(() => _postStorageContract.UpdElement(CreateModel(Guid.NewGuid().ToString())),
Throws.TypeOf<ElementNotFoundException>());
Assert.That(() => _postStorageContract.UpdElement(CreateModel(Guid.NewGuid().ToString())), Throws.TypeOf<ElementNotFoundException>());
}
[Test]
public void Try_UpdElement_WhenHaveRecordWithSameName_Test()
{
var post = CreateModel(Guid.NewGuid().ToString(), "New Name");
InsertPostToDatabaseAndReturn(post.Id, postName: "name");
InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), postName: post.PostName);
Assert.That(() => _postStorageContract.UpdElement(post),
Throws.TypeOf<ElementExistsException>());
FurnitureAssemblyDbContext.InsertPostToDatabaseAndReturn(post.Id, postName: "name");
FurnitureAssemblyDbContext.InsertPostToDatabaseAndReturn(postName: post.PostName);
Assert.That(() => _postStorageContract.UpdElement(post), Throws.TypeOf<ElementExistsException>());
}
[Test]
public void Try_UpdElement_WhenRecordWasDeleted_Test()
{
var post = CreateModel(Guid.NewGuid().ToString());
InsertPostToDatabaseAndReturn(post.Id, isActual: false);
FurnitureAssemblyDbContext.InsertPostToDatabaseAndReturn(post.Id, isActual: false);
Assert.That(() => _postStorageContract.UpdElement(post), Throws.TypeOf<ElementDeletedException>());
}
[Test]
public void Try_DelElement_Test()
{
var post = InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), isActual: true);
var post = FurnitureAssemblyDbContext.InsertPostToDatabaseAndReturn(isActual: true);
_postStorageContract.DelElement(post.PostId);
var element = GetPostFromDatabaseByPostId(post.PostId);
Assert.Multiple(() =>
{
Assert.That(element, Is.Not.Null);
Assert.That(!element!.IsActual);
});
Assert.That(FurnitureAssemblyDbContext.GetPostFromDatabaseByPostId(post.PostId), Is.Null);
}
[Test]
@@ -256,16 +194,16 @@ internal class PostStorageContractTests : BaseStorageContractTest
[Test]
public void Try_DelElement_WhenRecordWasDeleted_Test()
{
var post = InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), isActual: false);
var post = FurnitureAssemblyDbContext.InsertPostToDatabaseAndReturn(isActual: false);
Assert.That(() => _postStorageContract.DelElement(post.PostId), Throws.TypeOf<ElementDeletedException>());
}
[Test]
public void Try_ResElement_Test()
{
var post = InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), isActual: false);
var post = FurnitureAssemblyDbContext.InsertPostToDatabaseAndReturn(isActual: false);
_postStorageContract.ResElement(post.PostId);
var element = GetPostFromDatabaseByPostId(post.PostId);
var element = FurnitureAssemblyDbContext.GetPostFromDatabaseByPostId(post.PostId);
Assert.Multiple(() =>
{
Assert.That(element, Is.Not.Null);
@@ -276,51 +214,30 @@ internal class PostStorageContractTests : BaseStorageContractTest
[Test]
public void Try_ResElement_WhenNoRecordWithThisId_Test()
{
Assert.That(() => _postStorageContract.ResElement(Guid.NewGuid().ToString()),
Throws.TypeOf<ElementNotFoundException>());
Assert.That(() => _postStorageContract.ResElement(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
}
[Test]
public void Try_ResElement_WhenRecordNotWasDeleted_Test()
{
var post = InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), isActual: true);
var post = FurnitureAssemblyDbContext.InsertPostToDatabaseAndReturn(isActual: true);
Assert.That(() => _postStorageContract.ResElement(post.PostId), Throws.Nothing);
}
private Post InsertPostToDatabaseAndReturn(string id, string postName = "test", PostType postType = PostType.Builder, double salary = 10, bool isActual = true, DateTime? changeDate = null)
{
var post = new Post()
{
Id = Guid.NewGuid().ToString(),
PostId = id,
PostName = postName,
PostType = postType,
Salary = salary,
IsActual = isActual,
ChangeDate = changeDate ?? DateTime.UtcNow
};
FurnitureAssemblyDbContext.Posts.Add(post);
FurnitureAssemblyDbContext.SaveChanges();
return post;
}
private static void AssertElement(PostDataModel? actual, Post expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.Id, Is.EqualTo(expected.PostId));
Assert.That(actual.PostName, Is.EqualTo(expected.PostName)); Assert.That(actual.PostType, Is.EqualTo(expected.PostType));
Assert.That(actual.PostName, Is.EqualTo(expected.PostName));
Assert.That(actual.PostType, Is.EqualTo(expected.PostType));
Assert.That(actual.Salary, Is.EqualTo(expected.Salary));
Assert.That(actual.IsActual, Is.EqualTo(expected.IsActual));
});
}
private static PostDataModel CreateModel(string postId, string postName = "test", PostType postType = PostType.Builder, double salary = 10, bool isActual = false, DateTime? changeDate = null)
=> new(postId, postName, postType, salary, isActual, changeDate ?? DateTime.UtcNow);
private Post? GetPostFromDatabaseByPostId(string id) => FurnitureAssemblyDbContext.Posts
.Where(x => x.PostId == id).OrderByDescending(x => x.ChangeDate).FirstOrDefault();
private static PostDataModel CreateModel(string postId, string postName = "test", PostType postType = PostType.Builder, double salary = 10)
=> new(postId, postName, postType, salary);
private static void AssertElement(Post? actual, PostDataModel expected)
{
@@ -331,7 +248,6 @@ internal class PostStorageContractTests : BaseStorageContractTest
Assert.That(actual.PostName, Is.EqualTo(expected.PostName));
Assert.That(actual.PostType, Is.EqualTo(expected.PostType));
Assert.That(actual.Salary, Is.EqualTo(expected.Salary));
Assert.That(actual.IsActual, Is.EqualTo(expected.IsActual));
});
}
}

View File

@@ -2,7 +2,7 @@
using FurnitureAssemblyDatebase;
using FurnitureAssemblyDatebase.Implementations;
using FurnitureAssemblyDatebase.Models;
using Microsoft.EntityFrameworkCore;
using FurnitureAssemblyTests.Infrastructure;
namespace FurnitureAssemblyTests.StorageContractTests;
@@ -16,26 +16,26 @@ internal class SalaryStorageContractTests : BaseStorageContractTest
public void SetUp()
{
_salaryStorageContract = new SalaryStorageContract(FurnitureAssemblyDbContext);
_worker = InsertWorkerToDatabaseAndReturn();
_worker = FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn();
}
[TearDown]
public void TearDown()
{
FurnitureAssemblyDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Salaries\"CASCADE; ");
FurnitureAssemblyDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Workers\"CASCADE; ");
FurnitureAssemblyDbContext.RemoveWorkersFromDatabase();
FurnitureAssemblyDbContext.RemoveSalariesFromDatabase();
}
[Test]
public void Try_GetList_WhenHaveRecords_Test()
{
var salary = InsertSalaryToDatabaseAndReturn(_worker.Id, workerSalary: 100);
InsertSalaryToDatabaseAndReturn(_worker.Id);
InsertSalaryToDatabaseAndReturn(_worker.Id);
var salary = FurnitureAssemblyDbContext.InsertSalaryToDatabaseAndReturn(_worker.Id, workerSalary: 100);
FurnitureAssemblyDbContext.InsertSalaryToDatabaseAndReturn(_worker.Id);
FurnitureAssemblyDbContext.InsertSalaryToDatabaseAndReturn(_worker.Id);
var list = _salaryStorageContract.GetList(DateTime.UtcNow.AddDays(-10), DateTime.UtcNow.AddDays(10));
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(3));
AssertElement(list.First(), salary);
AssertElement(list.Single(x => x.Salary == salary.WorkerSalary), salary);
}
[Test]
@@ -49,12 +49,12 @@ internal class SalaryStorageContractTests : BaseStorageContractTest
[Test]
public void Try_GetList_OnlyInDatePeriod_Test()
{
InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate: DateTime.UtcNow.AddDays(-2));
InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate: DateTime.UtcNow.AddDays(-1).AddMinutes(-5));
InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate: DateTime.UtcNow.AddDays(-1).AddMinutes(5));
InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate: DateTime.UtcNow.AddDays(1).AddMinutes(-5));
InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate: DateTime.UtcNow.AddDays(1).AddMinutes(5));
InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate: DateTime.UtcNow.AddDays(-2));
FurnitureAssemblyDbContext.InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate: DateTime.UtcNow.AddDays(-2));
FurnitureAssemblyDbContext.InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate: DateTime.UtcNow.AddDays(-1).AddMinutes(-5));
FurnitureAssemblyDbContext.InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate: DateTime.UtcNow.AddDays(-1).AddMinutes(5));
FurnitureAssemblyDbContext.InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate: DateTime.UtcNow.AddDays(1).AddMinutes(-5));
FurnitureAssemblyDbContext.InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate: DateTime.UtcNow.AddDays(1).AddMinutes(5));
FurnitureAssemblyDbContext.InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate: DateTime.UtcNow.AddDays(-2));
var list = _salaryStorageContract.GetList(DateTime.UtcNow.AddDays(-1), DateTime.UtcNow.AddDays(1));
Assert.That(list, Is.Not.Null);
Assert.Multiple(() =>
@@ -66,10 +66,10 @@ internal class SalaryStorageContractTests : BaseStorageContractTest
[Test]
public void Try_GetList_ByWorker_Test()
{
var worker = InsertWorkerToDatabaseAndReturn("name 2");
InsertSalaryToDatabaseAndReturn(_worker.Id);
InsertSalaryToDatabaseAndReturn(_worker.Id);
InsertSalaryToDatabaseAndReturn(worker.Id);
var worker = FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn();
FurnitureAssemblyDbContext.InsertSalaryToDatabaseAndReturn(_worker.Id);
FurnitureAssemblyDbContext.InsertSalaryToDatabaseAndReturn(_worker.Id);
FurnitureAssemblyDbContext.InsertSalaryToDatabaseAndReturn(worker.Id);
var list = _salaryStorageContract.GetList(DateTime.UtcNow.AddDays(-
1), DateTime.UtcNow.AddDays(1), _worker.Id);
Assert.That(list, Is.Not.Null);
@@ -84,17 +84,17 @@ internal class SalaryStorageContractTests : BaseStorageContractTest
public void Try_GetList_ByWorkerOnlyInDatePeriod_Test()
{
var worker = InsertWorkerToDatabaseAndReturn("name 2");
InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate:
FurnitureAssemblyDbContext.InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate:
DateTime.UtcNow.AddDays(-2));
InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate:
FurnitureAssemblyDbContext.InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate:
DateTime.UtcNow.AddDays(-1).AddMinutes(5));
InsertSalaryToDatabaseAndReturn(worker.Id, salaryDate:
FurnitureAssemblyDbContext.InsertSalaryToDatabaseAndReturn(worker.Id, salaryDate:
DateTime.UtcNow.AddDays(-1).AddMinutes(5));
InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate:
FurnitureAssemblyDbContext.InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate:
DateTime.UtcNow.AddDays(1).AddMinutes(-5));
InsertSalaryToDatabaseAndReturn(worker.Id, salaryDate:
FurnitureAssemblyDbContext.InsertSalaryToDatabaseAndReturn(worker.Id, salaryDate:
DateTime.UtcNow.AddDays(1).AddMinutes(-5));
InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate:
FurnitureAssemblyDbContext.InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate:
DateTime.UtcNow.AddDays(-2));
var list = _salaryStorageContract.GetList(DateTime.UtcNow.AddDays(-
1), DateTime.UtcNow.AddDays(1), _worker.Id);
@@ -111,7 +111,7 @@ internal class SalaryStorageContractTests : BaseStorageContractTest
{
var salary = CreateModel(_worker.Id);
_salaryStorageContract.AddElement(salary);
AssertElement(GetSalaryFromDatabaseByWorkerId(_worker.Id), salary);
AssertElement(FurnitureAssemblyDbContext.GetSalariesFromDatabaseByWorkerId(_worker.Id).FirstOrDefault(), salary);
}
private Worker InsertWorkerToDatabaseAndReturn(string workerFIO = "fio")
@@ -128,20 +128,6 @@ internal class SalaryStorageContractTests : BaseStorageContractTest
return worker;
}
private Salary InsertSalaryToDatabaseAndReturn(string workerId, double
workerSalary = 1, DateTime? salaryDate = null)
{
var salary = new Salary()
{
WorkerId = workerId,
WorkerSalary = workerSalary,
SalaryDate = salaryDate ?? DateTime.UtcNow
};
FurnitureAssemblyDbContext.Salaries.Add(salary);
FurnitureAssemblyDbContext.SaveChanges();
return salary;
}
private static void AssertElement(SalaryDataModel? actual, Salary expected)
{
Assert.That(actual, Is.Not.Null);
@@ -154,8 +140,6 @@ internal class SalaryStorageContractTests : BaseStorageContractTest
private static SalaryDataModel CreateModel(string workerId, double workerSalary = 1, DateTime? salaryDate = null)
=> new(workerId, salaryDate ?? DateTime.UtcNow, workerSalary);
private Salary? GetSalaryFromDatabaseByWorkerId(string id) => FurnitureAssemblyDbContext.Salaries.FirstOrDefault(x => x.WorkerId == id);
private static void AssertElement(Salary? actual, SalaryDataModel expected)
{
Assert.That(actual, Is.Not.Null);

View File

@@ -0,0 +1,187 @@
using FurnitureAssemblyContracts.DataModels;
using FurnitureAssemblyContracts.Exceptions;
using FurnitureAssemblyDatebase.Implementations;
using FurnitureAssemblyDatebase.Models;
using FurnitureAssemblyDatebase;
using Microsoft.EntityFrameworkCore;
using FurnitureAssemblyContracts.Enums;
namespace FurnitureAssemblyTests.StorageContractTests;
[TestFixture]
internal class SuppliesStorageContractTests : BaseStorageContractTest
{
private SuppliesStorageContract _suppliesStorageContract;
private Component _component;
[SetUp]
public void SetUp()
{
_suppliesStorageContract = new SuppliesStorageContract(FurnitureAssemblyDbContext);
_component = InsertComponentToDatabaseAndReturn();
}
[TearDown]
public void TearDown()
{
FurnitureAssemblyDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Supplieses\" CASCADE;");
FurnitureAssemblyDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Components\" CASCADE;");
}
[Test]
public void Try_GetList_WhenHaveRecords_Test()
{
var supply = InsertSupplyToDatabaseAndReturn(Guid.NewGuid().ToString(), ComponentType.Handle, 5);
InsertSupplyToDatabaseAndReturn(Guid.NewGuid().ToString(), ComponentType.Handle, 5);
InsertSupplyToDatabaseAndReturn(Guid.NewGuid().ToString(), ComponentType.Handle, 5);
var list = _suppliesStorageContract.GetList();
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(3));
AssertElement(list.First(), supply);
}
[Test]
public void Try_GetList_WhenNoRecords_Test()
{
var list = _suppliesStorageContract.GetList();
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.Empty);
}
[Test]
public void Try_GetElementById_WhenHaveRecord_Test()
{
var supply = InsertSupplyToDatabaseAndReturn(Guid.NewGuid().ToString(), ComponentType.Handle, 5);
AssertElement(_suppliesStorageContract.GetElementById(supply.Id), supply);
}
[Test]
public void Try_GetElementById_WhenNoRecord_Test()
{
Assert.That(() => _suppliesStorageContract.GetElementById(Guid.NewGuid().ToString()), Is.Null);
}
[Test]
public void Try_AddElement_Test()
{
var supply = CreateModel(Guid.NewGuid().ToString(), ComponentType.Handle, 5, [_component.Id]);
_suppliesStorageContract.AddElement(supply);
AssertElement(GetSupplyFromDatabaseById(supply.Id), supply);
}
[Test]
public void Try_AddElement_WhenHaveRecordWithSameId_Test()
{
var supply = CreateModel(Guid.NewGuid().ToString(), ComponentType.Handle, 5, [_component.Id]);
InsertSupplyToDatabaseAndReturn(supply.Id, ComponentType.Handle, 5, [(_component.Id, 3)]);
Assert.That(() => _suppliesStorageContract.AddElement(supply), Throws.TypeOf<StorageException>());
}
[Test]
public void Try_UpdElement_Test()
{
var supply = CreateModel(Guid.NewGuid().ToString(), ComponentType.Handle, 5, [_component.Id]);
InsertSupplyToDatabaseAndReturn(supply.Id, ComponentType.Legs, 5, null);
_suppliesStorageContract.UpdElement(supply);
AssertElement(GetSupplyFromDatabaseById(supply.Id), supply);
}
[Test]
public void Try_UpdElement_WhenNoRecordWithThisId_Test()
{
Assert.That(() => _suppliesStorageContract.UpdElement(CreateModel(Guid.NewGuid().ToString(), ComponentType.Handle, 5, [_component.Id])), Throws.TypeOf<ElementNotFoundException>());
}
private Component InsertComponentToDatabaseAndReturn()
{
var component = new Component { Id = Guid.NewGuid().ToString(), Name = "Test Component", Type = ComponentType.Panel };
FurnitureAssemblyDbContext.Components.Add(component);
FurnitureAssemblyDbContext.SaveChanges();
return component;
}
private Supplies InsertSupplyToDatabaseAndReturn(string id, ComponentType type, int count, List<(string, int)>? components = null)
{
var supply = new Supplies { Id = id, Type = type, ProductuionDate = DateTime.UtcNow, Count = count, Components = [] };
if (components is not null)
{
foreach (var elem in components)
{
supply.Components.Add(new ComponentSupplies { SuppliesId = supply.Id, ComponentId = elem.Item1, Count = elem.Item2 });
}
}
FurnitureAssemblyDbContext.Supplieses.Add(supply);
FurnitureAssemblyDbContext.SaveChanges();
return supply;
}
private static void AssertElement(SuppliesDataModel? actual, Supplies expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.Id, Is.EqualTo(expected.Id));
Assert.That(actual.Type, Is.EqualTo(expected.Type));
Assert.That(actual.ProductuionDate, Is.EqualTo(expected.ProductuionDate));
Assert.That(actual.Count, Is.EqualTo(expected.Count));
});
if (expected.Components is not null)
{
Assert.That(actual.Components, Is.Not.Null);
Assert.That(actual.Components, Has.Count.EqualTo(expected.Components.Count));
for (int i = 0; i < actual.Components.Count; ++i)
{
Assert.Multiple(() =>
{
Assert.That(actual.Components[i].ComponentId, Is.EqualTo(expected.Components[i].ComponentId));
Assert.That(actual.Components[i].Count, Is.EqualTo(expected.Components[i].Count));
});
}
}
else
{
Assert.That(actual.Components, Is.Null);
}
}
private static void AssertElement(Supplies? actual, SuppliesDataModel expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.Id, Is.EqualTo(expected.Id));
Assert.That(actual.Type, Is.EqualTo(expected.Type));
Assert.That(actual.ProductuionDate, Is.EqualTo(expected.ProductuionDate));
Assert.That(actual.Count, Is.EqualTo(expected.Count));
});
if (expected.Components is not null)
{
Assert.That(actual.Components, Is.Not.Null);
Assert.That(actual.Components, Has.Count.EqualTo(expected.Components.Count));
for (int i = 0; i < actual.Components.Count; ++i)
{
Assert.Multiple(() =>
{
Assert.That(actual.Components[i].ComponentId, Is.EqualTo(expected.Components[i].ComponentId));
Assert.That(actual.Components[i].Count, Is.EqualTo(expected.Components[i].Count));
});
}
}
else
{
Assert.That(actual.Components, Is.Null);
}
}
private static SuppliesDataModel CreateModel(string id, ComponentType type, int count, List<string> componentsIds)
{
var components = componentsIds.Select(x => new ComponentSuppliesDataModel(id, x, 1)).ToList();
return new(id, type, DateTime.UtcNow, count, components);
}
private Supplies? GetSupplyFromDatabaseById(string id)
{
return FurnitureAssemblyDbContext.Supplieses.FirstOrDefault(x => x.Id == id);
}
}

View File

@@ -0,0 +1,209 @@
using FurnitureAssemblyContracts.DataModels;
using FurnitureAssemblyContracts.Enums;
using FurnitureAssemblyContracts.Exceptions;
using FurnitureAssemblyDatebase.Implementations;
using FurnitureAssemblyDatebase.Models;
using Microsoft.EntityFrameworkCore;
namespace FurnitureAssemblyTests.StorageContractTests;
internal class WarehouseStorageContractTests : BaseStorageContractTest
{
private WarehouseStorageContract _warehouseStorageContract;
private Component _component;
[SetUp]
public void SetUp()
{
_warehouseStorageContract = new WarehouseStorageContract(FurnitureAssemblyDbContext);
_component = InsertComponentToDatabaseAndReturn(Guid.NewGuid().ToString(), "name", ComponentType.Panel);
}
[TearDown]
public void TearDown()
{
FurnitureAssemblyDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Warehouses\" CASCADE;");
FurnitureAssemblyDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Components\" CASCADE;");
}
[Test]
public void Try_GetList_WhenHaveRecords_Test()
{
var warehouse = InsertWarehouseToDatabaseAndReturn(Guid.NewGuid().ToString(), ComponentType.Handle, 5);
InsertWarehouseToDatabaseAndReturn(Guid.NewGuid().ToString(), ComponentType.Handle, 5);
InsertWarehouseToDatabaseAndReturn(Guid.NewGuid().ToString(), ComponentType.Handle, 5);
var list = _warehouseStorageContract.GetList();
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(3));
AssertElement(list.First(), warehouse);
}
[Test]
public void Try_GetList_WhenNoRecords_Test()
{
var list = _warehouseStorageContract.GetList();
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.Empty);
}
[Test]
public void Try_GetElementById_WhenHaveRecord_Test()
{
var warehouse = InsertWarehouseToDatabaseAndReturn(Guid.NewGuid().ToString(), ComponentType.Handle, 5);
var result = _warehouseStorageContract.GetElementById(warehouse.Id);
AssertElement(result, warehouse);
}
[Test]
public void Try_GetElementById_WhenNoRecord_Test()
{
Assert.That(() => _warehouseStorageContract.GetElementById(Guid.NewGuid().ToString()), Is.Null);
}
[Test]
public void Try_AddElement_WhenValidData_Test()
{
var warehouse = CreateModel(Guid.NewGuid().ToString(), ComponentType.Handle, 5, [_component.Id]);
_warehouseStorageContract.AddElement(warehouse);
var result = GetWarehouseFromDatabaseById(warehouse.Id);
AssertElement(result, warehouse);
}
[Test]
public void Try_AddElement_WhenHaveRecordWithSameId_Test()
{
var warehouse = CreateModel(Guid.NewGuid().ToString(), ComponentType.Handle, 5, [_component.Id]);
InsertWarehouseToDatabaseAndReturn(warehouse.Id, ComponentType.Handle, 5, [(_component.Id, 3)]);
Assert.That(() => _warehouseStorageContract.AddElement(warehouse), Throws.TypeOf<StorageException>());
}
[Test]
public void Try_AddElement_WhenNoHaveComponent_Test()
{
var warehouse = CreateModel(Guid.NewGuid().ToString(), ComponentType.Handle, 0, [_component.Id]);
InsertWarehouseToDatabaseAndReturn(warehouse.Id, ComponentType.Handle, 5, [(_component.Id, 3)]);
Assert.That(() => _warehouseStorageContract.AddElement(warehouse), Throws.TypeOf<StorageException>());
}
[Test]
public void Try_UpdElement_WhenValidData_Test()
{
var warehouse = CreateModel(Guid.NewGuid().ToString(), ComponentType.Handle, 5, [_component.Id]);
InsertWarehouseToDatabaseAndReturn(warehouse.Id, ComponentType.Legs, 10, null);
_warehouseStorageContract.UpdElement(warehouse);
var result = GetWarehouseFromDatabaseById(warehouse.Id);
AssertElement(result, warehouse);
}
[Test]
public void Try_UpdElement_WhenNoRecordWithThisId_Test()
{
var warehouse = CreateModel(Guid.NewGuid().ToString(), ComponentType.Handle, 5, [_component.Id]);
Assert.That(() => _warehouseStorageContract.UpdElement(warehouse), Throws.TypeOf<ElementNotFoundException>());
}
[Test]
public void Try_DelElement_WhenRecordExists_Test()
{
var warehouse = InsertWarehouseToDatabaseAndReturn(Guid.NewGuid().ToString(), ComponentType.Handle, 5);
_warehouseStorageContract.DelElement(warehouse.Id);
var result = GetWarehouseFromDatabaseById(warehouse.Id);
Assert.That(result, Is.Null);
}
[Test]
public void Try_DelElement_WhenRecordDoesNotExist_ThrowsElementNotFoundException()
{
Assert.That(() => _warehouseStorageContract.DelElement(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
}
private Component InsertComponentToDatabaseAndReturn(string id, string name, ComponentType type)
{
var component = new Component { Id = id, Name = name, Type = type };
FurnitureAssemblyDbContext.Components.Add(component);
FurnitureAssemblyDbContext.SaveChanges();
return component;
}
private Warehouse InsertWarehouseToDatabaseAndReturn(string id, ComponentType type, int count, List<(string, int)>? components = null)
{
var warehouse = new Warehouse { Id = id, Type = type, Count = count, Components = [] };
if (components is not null)
{
foreach (var elem in components)
{
warehouse.Components.Add(new ComponentWarehouse { WarehouseId = warehouse.Id, ComponentId = elem.Item1, Count = elem.Item2 });
}
}
FurnitureAssemblyDbContext.Warehouses.Add(warehouse);
FurnitureAssemblyDbContext.SaveChanges();
return warehouse;
}
private static void AssertElement(WarehouseDataModel? actual, Warehouse expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.Id, Is.EqualTo(expected.Id));
Assert.That(actual.Type, Is.EqualTo(expected.Type));
Assert.That(actual.Count, Is.EqualTo(expected.Count));
});
if (expected.Components is not null)
{
Assert.That(actual.Components, Is.Not.Null);
Assert.That(actual.Components, Has.Count.EqualTo(expected.Components.Count));
for (int i = 0; i < actual.Components.Count; ++i)
{
Assert.Multiple(() =>
{
Assert.That(actual.Components[i].ComponentId, Is.EqualTo(expected.Components[i].ComponentId));
Assert.That(actual.Components[i].Count, Is.EqualTo(expected.Components[i].Count));
});
}
}
else
{
Assert.That(actual.Components, Is.Null);
}
}
private static void AssertElement(Warehouse? actual, WarehouseDataModel expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.Id, Is.EqualTo(expected.Id));
Assert.That(actual.Type, Is.EqualTo(expected.Type));
Assert.That(actual.Count, Is.EqualTo(expected.Count));
});
if (expected.Components is not null)
{
Assert.That(actual.Components, Is.Not.Null);
Assert.That(actual.Components, Has.Count.EqualTo(expected.Components.Count));
for (int i = 0; i < actual.Components.Count; ++i)
{
Assert.Multiple(() =>
{
Assert.That(actual.Components[i].ComponentId, Is.EqualTo(expected.Components[i].ComponentId));
Assert.That(actual.Components[i].Count, Is.EqualTo(expected.Components[i].Count));
});
}
}
else
{
Assert.That(actual.Components, Is.Null);
}
}
private static WarehouseDataModel CreateModel(string id, ComponentType type, int count, List<string> componentsIds)
{
var components = componentsIds.Select(x => new ComponentWarehouseDataModel(id, x, 1)).ToList();
return new(id, type, count, components);
}
private Warehouse? GetWarehouseFromDatabaseById(string id)
{
return FurnitureAssemblyDbContext.Warehouses.FirstOrDefault(x => x.Id == id);
}
}

View File

@@ -2,6 +2,7 @@
using FurnitureAssemblyContracts.Exceptions;
using FurnitureAssemblyDatebase.Implementations;
using FurnitureAssemblyDatebase.Models;
using FurnitureAssemblyTests.Infrastructure;
using Microsoft.EntityFrameworkCore;
namespace FurnitureAssemblyTests.StorageContractTests;
@@ -20,19 +21,19 @@ internal class WorkerStorageContractTests : BaseStorageContractTest
[TearDown]
public void TearDown()
{
FurnitureAssemblyDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Workers\"CASCADE; ");
FurnitureAssemblyDbContext.RemoveWorkersFromDatabase();
}
[Test]
public void Try_GetList_WhenHaveRecords_Test()
{
var worker = InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 1");
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 2");
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 3");
var worker = FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 1");
FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 2");
FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 3");
var list = _workerStorageContract.GetList();
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(3));
AssertElement(list.First(), worker);
AssertElement(list.First(x => x.FIO == worker.FIO), worker);
}
[Test]
@@ -47,11 +48,9 @@ internal class WorkerStorageContractTests : BaseStorageContractTest
public void Try_GetList_ByPostId_Test()
{
var postId = Guid.NewGuid().ToString();
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 1",
postId);
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 2",
postId);
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 3");
FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 1", postId: postId);
FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 2", postId: postId);
FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 3");
var list = _workerStorageContract.GetList(postId: postId);
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(2));
@@ -61,14 +60,10 @@ internal class WorkerStorageContractTests : BaseStorageContractTest
[Test]
public void Try_GetList_ByBirthDate_Test()
{
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 1",
birthDate: DateTime.UtcNow.AddYears(-25));
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 2",
birthDate: DateTime.UtcNow.AddYears(-21));
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 3",
birthDate: DateTime.UtcNow.AddYears(-20));
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 4",
birthDate: DateTime.UtcNow.AddYears(-19));
FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 1", birthDate: DateTime.UtcNow.AddYears(-25));
FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 2", birthDate: DateTime.UtcNow.AddYears(-21));
FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 3", birthDate: DateTime.UtcNow.AddYears(-20));
FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 4", birthDate: DateTime.UtcNow.AddYears(-19));
var list = _workerStorageContract.GetList(fromBirthDate: DateTime.UtcNow.AddYears(-21).AddMinutes(-1), toBirthDate: DateTime.UtcNow.AddYears(-20).AddMinutes(1));
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(2));
@@ -77,14 +72,10 @@ internal class WorkerStorageContractTests : BaseStorageContractTest
[Test]
public void Try_GetList_ByEmploymentDate_Test()
{
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 1",
employmentDate: DateTime.UtcNow.AddDays(-2));
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 2",
employmentDate: DateTime.UtcNow.AddDays(-1));
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 3",
employmentDate: DateTime.UtcNow.AddDays(1));
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 4",
employmentDate: DateTime.UtcNow.AddDays(2));
FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 1", employmentDate: DateTime.UtcNow.AddDays(-2));
FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 2", employmentDate: DateTime.UtcNow.AddDays(-1));
FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 3", employmentDate: DateTime.UtcNow.AddDays(1));
FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 4", employmentDate: DateTime.UtcNow.AddDays(2));
var list = _workerStorageContract.GetList(fromEmploymentDate: DateTime.UtcNow.AddDays(-1).AddMinutes(-1), toEmploymentDate: DateTime.UtcNow.AddDays(1).AddMinutes(1));
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(2));
@@ -94,13 +85,11 @@ internal class WorkerStorageContractTests : BaseStorageContractTest
public void Try_GetList_ByAllParameters_Test()
{
var postId = Guid.NewGuid().ToString();
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 1", postId, birthDate: DateTime.UtcNow.AddYears(-25), employmentDate: DateTime.UtcNow.AddDays(-2));
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 2", postId, birthDate: DateTime.UtcNow.AddYears(-22), employmentDate: DateTime.UtcNow.AddDays(-1));
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 3", postId, birthDate: DateTime.UtcNow.AddYears(-21), employmentDate: DateTime.UtcNow.AddDays(-1));
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 4", birthDate: DateTime.UtcNow.AddYears(-20), employmentDate: DateTime.UtcNow.AddDays(1));
var list = _workerStorageContract.GetList(postId: postId, fromBirthDate: DateTime.UtcNow.AddYears(-21).AddMinutes(-1),
toBirthDate: DateTime.UtcNow.AddYears(-20).AddMinutes(1), fromEmploymentDate: DateTime.UtcNow.AddDays(-1).AddMinutes(-1),
toEmploymentDate: DateTime.UtcNow.AddDays(1).AddMinutes(1));
FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 1", postId: postId, birthDate: DateTime.UtcNow.AddYears(-25), employmentDate: DateTime.UtcNow.AddDays(-2));
FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 2", postId: postId, birthDate: DateTime.UtcNow.AddYears(-22), employmentDate: DateTime.UtcNow.AddDays(-1));
FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 3", postId: postId, birthDate: DateTime.UtcNow.AddYears(-21), employmentDate: DateTime.UtcNow.AddDays(-1));
FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 4", birthDate: DateTime.UtcNow.AddYears(-20), employmentDate: DateTime.UtcNow.AddDays(1));
var list = _workerStorageContract.GetList(postId: postId, fromBirthDate: DateTime.UtcNow.AddYears(-21).AddMinutes(-1), toBirthDate: DateTime.UtcNow.AddYears(-20).AddMinutes(1), fromEmploymentDate: DateTime.UtcNow.AddDays(-1).AddMinutes(-1), toEmploymentDate: DateTime.UtcNow.AddDays(1).AddMinutes(1));
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(1));
}
@@ -108,7 +97,7 @@ internal class WorkerStorageContractTests : BaseStorageContractTest
[Test]
public void Try_GetElementById_WhenHaveRecord_Test()
{
var worker = InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString());
var worker = FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn();
AssertElement(_workerStorageContract.GetElementById(worker.Id), worker);
}
@@ -121,7 +110,7 @@ internal class WorkerStorageContractTests : BaseStorageContractTest
[Test]
public void Try_GetElementByFIO_WhenHaveRecord_Test()
{
var worker = InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString());
var worker = FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn();
AssertElement(_workerStorageContract.GetElementByFIO(worker.FIO), worker);
}
@@ -136,14 +125,14 @@ internal class WorkerStorageContractTests : BaseStorageContractTest
{
var worker = CreateModel(Guid.NewGuid().ToString());
_workerStorageContract.AddElement(worker);
AssertElement(GetWorkerFromDatabase(worker.Id), worker);
AssertElement(FurnitureAssemblyDbContext.GetWorkerFromDatabaseById(worker.Id), worker);
}
[Test]
public void Try_AddElement_WhenHaveRecordWithSameId_Test()
{
var worker = CreateModel(Guid.NewGuid().ToString());
InsertWorkerToDatabaseAndReturn(worker.Id);
FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(worker.Id);
Assert.That(() => _workerStorageContract.AddElement(worker), Throws.TypeOf<ElementExistsException>());
}
@@ -151,33 +140,31 @@ internal class WorkerStorageContractTests : BaseStorageContractTest
public void Try_UpdElement_Test()
{
var worker = CreateModel(Guid.NewGuid().ToString(), "New Fio");
InsertWorkerToDatabaseAndReturn(worker.Id);
FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(worker.Id);
_workerStorageContract.UpdElement(worker);
AssertElement(GetWorkerFromDatabase(worker.Id), worker);
AssertElement(FurnitureAssemblyDbContext.GetWorkerFromDatabaseById(worker.Id), worker);
}
[Test]
public void Try_UpdElement_WhenNoRecordWithThisId_Test()
{
Assert.That(() => _workerStorageContract.UpdElement(CreateModel(Guid.NewGuid().ToString())),
Throws.TypeOf<ElementNotFoundException>());
Assert.That(() => _workerStorageContract.UpdElement(CreateModel(Guid.NewGuid().ToString())), Throws.TypeOf<ElementNotFoundException>());
}
[Test]
public void Try_UpdElement_WhenNoRecordWasDeleted_Test()
{
var worker = CreateModel(Guid.NewGuid().ToString());
InsertWorkerToDatabaseAndReturn(worker.Id, isDeleted: true);
Assert.That(() => _workerStorageContract.UpdElement(worker),
Throws.TypeOf<ElementNotFoundException>());
FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(worker.Id, isDeleted: true);
Assert.That(() => _workerStorageContract.UpdElement(worker), Throws.TypeOf<ElementNotFoundException>());
}
[Test]
public void Try_DelElement_Test()
{
var worker = InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString());
var worker = FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString());
_workerStorageContract.DelElement(worker.Id);
var element = GetWorkerFromDatabase(worker.Id);
var element = FurnitureAssemblyDbContext.GetWorkerFromDatabaseById(worker.Id);
Assert.That(element, Is.Not.Null);
Assert.That(element.IsDeleted);
}
@@ -185,33 +172,17 @@ internal class WorkerStorageContractTests : BaseStorageContractTest
[Test]
public void Try_DelElement_WhenNoRecordWithThisId_Test()
{
Assert.That(() => _workerStorageContract.DelElement(Guid.NewGuid().ToString()),
Throws.TypeOf<ElementNotFoundException>());
Assert.That(() => _workerStorageContract.DelElement(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
}
[Test]
public void Try_DelElement_WhenNoRecordWasDeleted_Test()
{
var worker = CreateModel(Guid.NewGuid().ToString());
InsertWorkerToDatabaseAndReturn(worker.Id, isDeleted: true);
FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(worker.Id, isDeleted: true);
Assert.That(() => _workerStorageContract.DelElement(worker.Id), Throws.TypeOf<ElementNotFoundException>());
}
private Worker InsertWorkerToDatabaseAndReturn(string id, string fio = "test", string? postId = null, DateTime? birthDate = null, DateTime? employmentDate = null, bool isDeleted = false)
{
var worker = new Worker()
{
Id = id,
FIO = fio,
PostId = postId ?? Guid.NewGuid().ToString(),
BirthDate = birthDate ?? DateTime.UtcNow.AddYears(-20),
EmploymentDate = employmentDate ?? DateTime.UtcNow,
IsDeleted = isDeleted
};
FurnitureAssemblyDbContext.Workers.Add(worker);
FurnitureAssemblyDbContext.SaveChanges();
return worker;
}
private static void AssertElement(WorkerDataModel? actual, Worker expected)
{
Assert.That(actual, Is.Not.Null);
@@ -221,16 +192,14 @@ internal class WorkerStorageContractTests : BaseStorageContractTest
Assert.That(actual.PostId, Is.EqualTo(expected.PostId));
Assert.That(actual.FIO, Is.EqualTo(expected.FIO));
Assert.That(actual.BirthDate, Is.EqualTo(expected.BirthDate));
Assert.That(actual.EmploymentDate,
Is.EqualTo(expected.EmploymentDate));
Assert.That(actual.EmploymentDate, Is.EqualTo(expected.EmploymentDate));
Assert.That(actual.IsDeleted, Is.EqualTo(expected.IsDeleted));
});
}
private static WorkerDataModel CreateModel(string id, string fio = "fio", string? postId = null, DateTime? birthDate = null, DateTime? employmentDate = null, bool isDeleted = false) =>
new(id, fio, postId ?? Guid.NewGuid().ToString(), birthDate ?? DateTime.UtcNow.AddYears(-20), employmentDate ?? DateTime.UtcNow, isDeleted);
private Worker? GetWorkerFromDatabase(string id) => FurnitureAssemblyDbContext.Workers.FirstOrDefault(x => x.Id == id);
private static void AssertElement(Worker? actual, WorkerDataModel expected)
{
Assert.That(actual, Is.Not.Null);
@@ -240,7 +209,7 @@ internal class WorkerStorageContractTests : BaseStorageContractTest
Assert.That(actual.PostId, Is.EqualTo(expected.PostId));
Assert.That(actual.FIO, Is.EqualTo(expected.FIO));
Assert.That(actual.BirthDate, Is.EqualTo(expected.BirthDate));
Assert.That(actual.EmploymentDate,Is.EqualTo(expected.EmploymentDate));
Assert.That(actual.EmploymentDate, Is.EqualTo(expected.EmploymentDate));
Assert.That(actual.IsDeleted, Is.EqualTo(expected.IsDeleted));
});
}

View File

@@ -0,0 +1,290 @@
using AutoMapper;
using FurnitureAssemblyContracts.BindingModels;
using FurnitureAssemblyContracts.BusinessLogicsContracts;
using FurnitureAssemblyContracts.DataModels;
using FurnitureAssemblyContracts.Enums;
using FurnitureAssemblyContracts.Exceptions;
using FurnitureAssemblyContracts.ViewModels;
using FurnitureAssemblyWebApi.Adapters;
using Microsoft.Extensions.Logging;
using Moq;
using System.Net;
namespace FurnitureAssemblyTests.WebApiAdapterTests;
[TestFixture]
internal class SuppliesAdapterTests
{
private Mock<ISuppliesBusinessLogicContract> _suppliesBusinessLogicContract;
private SuppliesAdapter _adapter;
private Mock<ILogger<SuppliesAdapter>> _logger;
private IMapper _mapper;
[OneTimeSetUp]
public void OneTimeSetUp()
{
_suppliesBusinessLogicContract = new Mock<ISuppliesBusinessLogicContract>();
_logger = new Mock<ILogger<SuppliesAdapter>>();
_adapter = new SuppliesAdapter(_suppliesBusinessLogicContract.Object, _logger.Object);
}
[Test]
public void GetAllComponents_WhenSuppliesExist_ReturnOk()
{
// Arrange
var supplies = new List<SuppliesDataModel>
{
new SuppliesDataModel(Guid.NewGuid().ToString(), ComponentType.Panel, DateTime.Now, 5, []),
new SuppliesDataModel(Guid.NewGuid().ToString(), ComponentType.Panel, DateTime.Now.AddDays(1), 10, [])
};
_suppliesBusinessLogicContract.Setup(x => x.GetAllComponents()).Returns(supplies);
// Act
var result = _adapter.GetAllComponents();
var list = (List<SuppliesViewModel>)result.Result!;
// Assert
Assert.That(result.StatusCode, Is.EqualTo(HttpStatusCode.OK));
Assert.That(list.Count, Is.EqualTo(2));
}
[Test]
public void GetAllComponents_WhenListNull_ReturnNotFound()
{
// Arrange
_suppliesBusinessLogicContract.Setup(x => x.GetAllComponents()).Throws(new NullListException());
// Act
var result = _adapter.GetAllComponents();
// Assert
Assert.That(result.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
}
[Test]
public void GetAllComponents_WhenStorageException_ReturnsInternalServerError()
{
// Arrange
_suppliesBusinessLogicContract.Setup(x => x.GetAllComponents()).Throws(new StorageException(new InvalidOperationException()));
// Act
var result = _adapter.GetAllComponents();
// Assert
Assert.That(result.StatusCode, Is.EqualTo(HttpStatusCode.InternalServerError));
}
[Test]
public void GetComponentByData_WhenSupplies_ReturnOK()
{
var supply = new SuppliesDataModel(Guid.NewGuid().ToString(), ComponentType.Panel, DateTime.Now, 5, []);
// Arrange
_suppliesBusinessLogicContract.Setup(x => x.GetComponentByData(supply.Id)).Returns(supply);
// Act
var result = _adapter.GetComponentByData(supply.Id);
Assert.That(result.StatusCode, Is.EqualTo(HttpStatusCode.OK));
var resultData = (SuppliesViewModel)result.Result!;
Assert.That(resultData.Id!, Is.EqualTo(supply.Id));
}
[Test]
public void GetComponentByData_WhenComponentNotFound_ReturnsNotFound()
{
// Arrange
var data = "test";
_suppliesBusinessLogicContract.Setup(x => x.GetComponentByData(data)).Throws(new ElementNotFoundException(""));
// Act
var result = _adapter.GetComponentByData(data);
// Assert
Assert.That(result.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
}
[Test]
public void GetComponentByData_WhenStorageException_ReturnInternalServerError()
{
// Arrange
var data = "test";
_suppliesBusinessLogicContract.Setup(x => x.GetComponentByData(data)).Throws(new StorageException(new InvalidOperationException()));
// Act
var result = _adapter.GetComponentByData(data);
// Assert
Assert.That(result.StatusCode, Is.EqualTo(HttpStatusCode.InternalServerError));
}
[Test]
public void InsertComponent_WhenValidData_ReturnsNoContent()
{
// Arrange
var supply = new SuppliesBindingModel
{
Id = Guid.NewGuid().ToString(),
Type = ComponentType.Panel,
ProductuionDate = DateTime.Now,
Count = 5,
Components = [new ComponentSuppliesBindingModel { ComponentId = Guid.NewGuid().ToString(), SuppliesId = Guid.NewGuid().ToString(), Count = 5 }]
};
_suppliesBusinessLogicContract.Setup(x => x.InsertComponent(It.IsAny<SuppliesDataModel>()));
// Act
var result = _adapter.InsertComponent(supply);
// Assert
Assert.That(result.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
}
[Test]
public void InsertComponent_WhenDataIsNull_ReturnsBadRequest()
{
// Arrange
_suppliesBusinessLogicContract.Setup(x => x.InsertComponent(null)).Throws(new ArgumentNullException());
// Act
var result = _adapter.InsertComponent(null);
// Assert
Assert.That(result.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}
[Test]
public void InsertComponent_WhenValidationError_ReturnBadRequest()
{
// Arrange
var supply = new SuppliesBindingModel
{
Id = Guid.NewGuid().ToString(),
Type = ComponentType.None,
ProductuionDate = DateTime.Now,
Count = 5,
Components = []
};
// Act
var result = _adapter.InsertComponent(supply);
// Assert
Assert.That(result.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}
[Test]
public void InsertComponent_WhenElementExistException_ReturnBadRequest()
{
// Arrange
var supply1 = new SuppliesBindingModel
{
Id = Guid.NewGuid().ToString(),
Type = ComponentType.None,
ProductuionDate = DateTime.Now,
Count = 5,
Components = []
};
_suppliesBusinessLogicContract.Setup(x => x.InsertComponent(It.IsAny<SuppliesDataModel>())).Throws(new ElementExistsException("Data", "Data"));
// Act
var result = _adapter.InsertComponent(supply1);
// Assert
Assert.That(result.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}
[Test]
public void InsertComponent_WhenStorageException_ReturnBadRequest()
{
// Arrange
var supply = new SuppliesBindingModel
{
Id = Guid.NewGuid().ToString(), Type = ComponentType.Panel, ProductuionDate = DateTime.Now, Count = 5,
Components = new List<ComponentSuppliesBindingModel>()
};
_suppliesBusinessLogicContract.Setup(x => x.InsertComponent(It.IsAny<SuppliesDataModel>())).Throws(new StorageException(new InvalidOperationException()));
// Act
var result = _adapter.InsertComponent(supply);
// Assert
Assert.That(result.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}
[Test]
public void UpdateComponent_WhenValidData_ReturnsNoContent()
{
// Arrange
var supply = new SuppliesBindingModel { Id = Guid.NewGuid().ToString() };
_suppliesBusinessLogicContract.Setup(x => x.UpdateComponent(It.IsAny<SuppliesDataModel>()));
// Act
var result = _adapter.UpdateComponent(supply);
// Assert
Assert.That(result.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
}
[Test]
public void UpdateComponent_WhenDataIsNull_ReturnsBadRequest()
{
// Arrange
var component = new SuppliesBindingModel { Id = Guid.NewGuid().ToString() };
_suppliesBusinessLogicContract.Setup(x => x.UpdateComponent(It.IsAny<SuppliesDataModel>())).Throws(new ElementNotFoundException(""));
// Act
var result = _adapter.UpdateComponent(component);
// Assert
Assert.That(result.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}
[Test]
public void UpdateComponent_WhenValidationError_ReturnBadRequest()
{
// Arrange
var supply = new SuppliesBindingModel
{
Id = Guid.NewGuid().ToString(),
Type = ComponentType.None,
ProductuionDate = DateTime.Now,
Count = 5,
Components = []
};
_suppliesBusinessLogicContract.Setup(x => x.UpdateComponent(It.IsAny<SuppliesDataModel>())).Throws(new ValidationException(""));
// Act
var result = _adapter.UpdateComponent(supply);
// Assert
Assert.That(result.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}
[Test]
public void UpdateComponent_WhenElementNotFoundException_ReturnBadRequest()
{
// Arrange
var supply = new SuppliesBindingModel
{
Id = Guid.NewGuid().ToString(),
Type = ComponentType.None,
ProductuionDate = DateTime.Now,
Count = 5,
Components = []
};
_suppliesBusinessLogicContract.Setup(x => x.UpdateComponent(It.IsAny<SuppliesDataModel>())).Throws(new ElementNotFoundException(""));
// Act
var result = _adapter.UpdateComponent(supply);
// Assert
Assert.That(result.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}
[Test]
public void UpdateComponent_WhenElementExistException_ReturnBadRequest()
{
// Arrange
var supply1 = new SuppliesBindingModel
{
Id = Guid.NewGuid().ToString(),
Type = ComponentType.None,
ProductuionDate = DateTime.Now,
Count = 5,
Components = []
};
_suppliesBusinessLogicContract.Setup(x => x.UpdateComponent(It.IsAny<SuppliesDataModel>())).Throws(new ElementExistsException("Data", "Data"));
// Act
var result = _adapter.UpdateComponent(supply1);
Assert.That(result.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}
[Test]
public void UpdateComponent_WhenStorageException_ReturnBadRequest()
{
// Arrange
var supply = new SuppliesBindingModel
{
Id = Guid.NewGuid().ToString(),
Type = ComponentType.Panel,
ProductuionDate = DateTime.Now,
Count = 5,
Components = new List<ComponentSuppliesBindingModel>()
};
_suppliesBusinessLogicContract.Setup(x => x.UpdateComponent(It.IsAny<SuppliesDataModel>())).Throws(new StorageException(new InvalidOperationException()));
// Act
var result = _adapter.UpdateComponent(supply);
// Assert
Assert.That(result.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}
}

View File

@@ -0,0 +1,69 @@
using FurnitureAssemblyDatebase;
using FurnitureAssemblyTests.Infrastructure;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
using System.Text;
using System.Text.Json;
namespace FurnitureAssemblyTests.WebApiControllerTests;
internal class BaseWebApiControllerTest
{
private WebApplicationFactory<Program> _webApplication;
protected HttpClient HttpClient { get; private set; }
protected FurnitureAssemblyDbContext FurnitureAssemblyDbContext { get; private set; }
protected static readonly JsonSerializerOptions JsonSerializerOptions = new() { PropertyNameCaseInsensitive = true };
[OneTimeSetUp]
public void OneTimeSetUp()
{
_webApplication = new CustomWebApplicationFactory<Program>();
HttpClient = _webApplication
.WithWebHostBuilder(builder =>
{
builder.ConfigureTestServices(services =>
{
using var loggerFactory = new LoggerFactory();
loggerFactory.AddSerilog(new LoggerConfiguration()
.ReadFrom.Configuration(new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build())
.CreateLogger());
services.AddSingleton(loggerFactory);
});
})
.CreateClient();
var request = HttpClient.GetAsync("/login/user").GetAwaiter().GetResult();
var data = request.Content.ReadAsStringAsync().GetAwaiter().GetResult();
HttpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {data}");
FurnitureAssemblyDbContext = _webApplication.Services.GetRequiredService<FurnitureAssemblyDbContext>();
FurnitureAssemblyDbContext.Database.EnsureDeleted();
FurnitureAssemblyDbContext.Database.EnsureCreated();
}
[OneTimeTearDown]
public void OneTimeTearDown()
{
FurnitureAssemblyDbContext?.Database.EnsureDeleted();
FurnitureAssemblyDbContext?.Dispose();
HttpClient?.Dispose();
_webApplication?.Dispose();
}
protected static async Task<T?> GetModelFromResponseAsync<T>(HttpResponseMessage response) =>
JsonSerializer.Deserialize<T>(await response.Content.ReadAsStringAsync(), JsonSerializerOptions);
protected static StringContent MakeContent(object model) =>
new(JsonSerializer.Serialize(model), Encoding.UTF8, "application/json");
}

Some files were not shown because too many files have changed in this diff Show More