22 Commits

Author SHA1 Message Date
dca7a5752d Реализация Salary 2025-04-24 09:18:01 +04:00
bb6387e6eb Всё работает 2025-04-23 21:06:15 +04:00
a5dbe17292 WebApi 2025-04-08 20:00:32 +04:00
beef5c0232 Правка DataModels 2025-04-08 19:30:51 +04:00
09a0c6759c ViewModel, Adapter, OperationResponse 2025-04-08 19:02:27 +04:00
d992d6e280 Исправления 2025-03-13 11:20:23 +04:00
9ef676657b Тесты контрактов хранилища 2025-03-13 09:44:27 +04:00
9be7a2c78b Мелкие правки 2025-03-13 09:43:09 +04:00
6667a1103b Реализация контрактов хранилища 2025-03-12 18:26:45 +04:00
3a43e7ae89 DbContext 2025-03-12 17:15:26 +04:00
f3559dcddb Проект и модели 2025-03-12 16:54:16 +04:00
1eeb4014f5 Reapply "Реализация бизнесс логики"
This reverts commit 4b6ec2b79d.
2025-03-11 18:03:33 +04:00
4b6ec2b79d Revert "Реализация бизнесс логики"
This reverts commit f92aa70f71.
2025-03-11 17:37:33 +04:00
f92aa70f71 Реализация бизнесс логики 2025-03-11 17:17:30 +04:00
d63585404b Изменения 2 2025-03-11 17:16:24 +04:00
0cdd3c07ef Исправления из-за обновления условий 2025-03-11 16:55:06 +04:00
1ac006185a Тесты бизнесс логики 2025-03-11 15:52:16 +04:00
b43e799cd6 Контракты бизнесс логики 2025-03-11 15:51:59 +04:00
a9557fed86 Исправление названий 2025-03-11 15:50:23 +04:00
bedb4987a3 Исправления 2025-02-26 15:43:39 +04:00
fe53c2a542 Заготовки реализаций 2025-02-26 15:35:44 +04:00
21b006b0fa Контракты 2025-02-26 14:25:15 +04:00
147 changed files with 13346 additions and 84 deletions

View File

@@ -0,0 +1,56 @@
using TheBlacksmithVakulaContract.BusinessLogicsContracts;
using TheBlacksmithVakulaContract.DataModels;
using TheBlacksmithVakulaContract.StoragesContracts;
using Microsoft.Extensions.Logging;
using System.Text.Json;
using TheBlacksmithVakulaContract.Exceptions;
using TheBlacksmithVakulaContract.Extensions;
namespace TheBlacksmithVakulaBusinessLogic.Implementations
{
internal class BilletBusinessLogicContract(IBilletStorageContract billetStorageContract, ILogger logger) :
IBilletBusinessLogicContract
{
private readonly IBilletStorageContract _billetStorageContract = billetStorageContract;
private readonly ILogger _logger = logger;
public List<BilletDataModel> GetAllBillets()
{
_logger.LogInformation("GetAllBillets");
return _billetStorageContract.GetList() ?? throw new NullListException();
}
public BilletDataModel GetBilletByData(string data)
{
_logger.LogInformation("Get element by data: {data}", data);
if (data.IsEmpty()) throw new ArgumentNullException(nameof(data));
if (data.IsGuid()) return _billetStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data);
return _billetStorageContract.GetElementByName(data) ?? _billetStorageContract.GetElementByOldName(data) ??
throw new ElementNotFoundException(data);
}
public void InsertBillet(BilletDataModel billetDataModel)
{
_logger.LogInformation("New data: {json}", JsonSerializer.Serialize(billetDataModel));
ArgumentNullException.ThrowIfNull(billetDataModel);
billetDataModel.Validate();
_billetStorageContract.AddElement(billetDataModel);
}
public void UpdateBillet(BilletDataModel billetDataModel)
{
_logger.LogInformation("Update data: {json}", JsonSerializer.Serialize(billetDataModel));
ArgumentNullException.ThrowIfNull(billetDataModel);
billetDataModel.Validate();
_billetStorageContract.UpdElement(billetDataModel);
}
public void DeleteBillet(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");
_billetStorageContract.DelElement(id);
}
}
}

View File

@@ -0,0 +1,79 @@
using Microsoft.Extensions.Logging;
using System.Text.Json;
using TheBlacksmithVakulaContract.BusinessLogicsContracts;
using TheBlacksmithVakulaContract.DataModels;
using TheBlacksmithVakulaContract.Exceptions;
using TheBlacksmithVakulaContract.Extensions;
using TheBlacksmithVakulaContract.StoragesContracts;
namespace TheBlacksmithVakulaBusinessLogic.Implementations
{
internal class BlacksmithBusinessLogicContract(IBlacksmithStorageContract blacksmithStorageContract, ILogger logger) :
IBlacksmithBusinessLogicContract
{
private readonly IBlacksmithStorageContract _blacksmithStorageContract = blacksmithStorageContract;
private readonly ILogger _logger = logger;
public List<BlacksmithDataModel> GetAllBlacksmith(bool onlyActive = true)
{
_logger.LogInformation("GetAllBlacksmiths params: {onlyActive}", onlyActive);
return _blacksmithStorageContract.GetList(onlyActive) ?? throw new NullListException();
}
public List<BlacksmithDataModel> GetAllBlacksmithByRank(string rankId, bool onlyActive = true)
{
_logger.LogInformation("GetAllBlacksmiths params: {rankId}, {onlyActive},", rankId, onlyActive);
if (rankId.IsEmpty()) throw new ArgumentNullException(nameof(rankId));
if (!rankId.IsGuid()) throw new ValidationException("The value in the field rankId is not a unique identifier.");
return _blacksmithStorageContract.GetList(onlyActive, rankId) ?? throw new NullListException();
}
public List<BlacksmithDataModel> GetAllBlacksmithByBirthDate(DateTime fromDate, DateTime toDate, bool onlyActive = true)
{
_logger.LogInformation("GetAllBlacksmiths params: {onlyActive}, {fromDate}, {toDate}", onlyActive, fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate)) throw new IncorrectDatesException(fromDate, toDate);
return _blacksmithStorageContract.GetList(onlyActive, fromBirthDate: fromDate, toBirthDate: toDate) ??
throw new NullListException();
}
public List<BlacksmithDataModel> GetAllBlacksmithByEmploymentDate(DateTime fromDate, DateTime toDate, bool onlyActive = true)
{
_logger.LogInformation("GetAllBlacksmiths params: {onlyActive}, {fromDate}, {toDate}", onlyActive, fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate)) throw new IncorrectDatesException(fromDate, toDate);
return _blacksmithStorageContract.GetList(onlyActive, fromEmploymentDate: fromDate, toEmploymentDate: toDate) ??
throw new NullListException();
}
public BlacksmithDataModel GetBlacksmithByData(string data)
{
_logger.LogInformation("Get element by data: {data}", data);
if (data.IsEmpty()) throw new ArgumentNullException(nameof(data));
if (data.IsGuid()) return _blacksmithStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data);
return _blacksmithStorageContract.GetElementByFIO(data) ?? throw new ElementNotFoundException(data);
}
public void InsertBlacksmith(BlacksmithDataModel blacksmithDataModel)
{
_logger.LogInformation("New data: {json}", JsonSerializer.Serialize(blacksmithDataModel));
ArgumentNullException.ThrowIfNull(blacksmithDataModel);
blacksmithDataModel.Validate();
_blacksmithStorageContract.AddElement(blacksmithDataModel);
}
public void UpdateBlacksmith(BlacksmithDataModel blacksmithDataModel)
{
_logger.LogInformation("Update data: {json}", JsonSerializer.Serialize(blacksmithDataModel));
ArgumentNullException.ThrowIfNull(blacksmithDataModel);
blacksmithDataModel.Validate();
_blacksmithStorageContract.UpdElement(blacksmithDataModel);
}
public void DeleteBlacksmith(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");
_blacksmithStorageContract.DelElement(id);
}
}
}

View File

@@ -0,0 +1,65 @@
using Microsoft.Extensions.Logging;
using System.Text.Json;
using System.Text.RegularExpressions;
using TheBlacksmithVakulaContract.BusinessLogicsContracts;
using TheBlacksmithVakulaContract.DataModels;
using TheBlacksmithVakulaContract.Exceptions;
using TheBlacksmithVakulaContract.Extensions;
using TheBlacksmithVakulaContract.StoragesContracts;
namespace TheBlacksmithVakulaBusinessLogic.Implementations
{
internal class BuyerBusinessLogicContract(IBuyerStorageContract buyerStorageContract, ILogger logger) : IBuyerBusinessLogicContract
{
private readonly ILogger _logger = logger;
private readonly IBuyerStorageContract _buyerStorageContract = buyerStorageContract;
public List<BuyerDataModel> GetAllBuyers()
{
_logger.LogInformation("GetAllBuyers");
return _buyerStorageContract.GetList() ?? throw new NullListException();
}
public BuyerDataModel GetBuyerByData(string data)
{
_logger.LogInformation("Get element by data: {data}", data);
if (data.IsEmpty())
{
throw new ArgumentNullException(nameof(data));
}
if (data.IsGuid())
{
return _buyerStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data);
}
if (Regex.IsMatch(data, @"^((8|\+7)[\- ]?)?(\(?\d{3}\)?[\- ]?)?[\d\-]{7,10}$"))
{
return _buyerStorageContract.GetElementByPhoneNumber(data) ?? throw new ElementNotFoundException(data);
}
return _buyerStorageContract.GetElementByFIO(data) ?? throw new ElementNotFoundException(data);
}
public void InsertBuyer(BuyerDataModel model)
{
_logger.LogInformation("New data: {json}", JsonSerializer.Serialize(model));
ArgumentNullException.ThrowIfNull(model);
model.Validate();
_buyerStorageContract.AddElement(model);
}
public void UpdateBuyer(BuyerDataModel model)
{
_logger.LogInformation("Update data: {json}", JsonSerializer.Serialize(model));
ArgumentNullException.ThrowIfNull(model);
model.Validate();
_buyerStorageContract.UpdElement(model);
}
public void DeleteBuyer(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");
_buyerStorageContract.DelElement(id);
}
}
}

View File

@@ -0,0 +1,75 @@
using Microsoft.Extensions.Logging;
using System.Text.Json;
using TheBlacksmithVakulaContract.BusinessLogicsContracts;
using TheBlacksmithVakulaContract.DataModels;
using TheBlacksmithVakulaContract.Exceptions;
using TheBlacksmithVakulaContract.Extensions;
using TheBlacksmithVakulaContract.StoragesContracts;
namespace TheBlacksmithVakulaBusinessLogic.Implementations
{
internal class OrderBusinessLogicContract(IOrderStorageContract orderStorageContract, ILogger logger) :
IOrderBusinessLogicContract
{
private readonly IOrderStorageContract _orderStorageContract = orderStorageContract;
private readonly ILogger _logger = logger;
public List<OrderDataModel> GetAllOrderByPeriod(DateTime fromDate, DateTime toDate)
{
_logger.LogInformation("GetAllOrders params: {fromDate}, {toDate}", fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate)) throw new IncorrectDatesException(fromDate, toDate);
return _orderStorageContract.GetList(fromDate, toDate) ?? throw new NullListException();
}
public List<OrderDataModel> GetAllOrderByBlacksmithByPeriod(string blacksmithId, DateTime fromDate, DateTime toDate)
{
_logger.LogInformation("GetAllOrders params: {blacksmithId}, {fromDate}, { toDate}", blacksmithId, fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate)) throw new IncorrectDatesException(fromDate, toDate);
if (blacksmithId.IsEmpty()) throw new ArgumentNullException(nameof(blacksmithId));
if (!blacksmithId.IsGuid()) throw new ValidationException("The value in the field blacksmithId is not a unique identifier.");
return _orderStorageContract.GetList(fromDate, toDate, blacksmithId: blacksmithId) ?? throw new NullListException();
}
public List<OrderDataModel> GetAllOrderByBuyerByPeriod(string buyerId, DateTime fromDate, DateTime toDate)
{
_logger.LogInformation("GetAllOrders params: {buyerId}, {fromDate}, {toDate}", buyerId, fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate)) throw new IncorrectDatesException(fromDate, toDate);
if (buyerId.IsEmpty()) throw new ArgumentNullException(nameof(buyerId));
if (!buyerId.IsGuid()) throw new ValidationException("The value in the field buyerId is not a unique identifier.");
return _orderStorageContract.GetList(fromDate, toDate, buyerId: buyerId) ?? throw new NullListException();
}
public List<OrderDataModel> GetAllOrderByProductByPeriod(string productId, DateTime fromDate, DateTime toDate)
{
_logger.LogInformation("GetAllOrders params: {productId}, {fromDate}, {toDate}", productId, fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate)) throw new IncorrectDatesException(fromDate, toDate);
if (productId.IsEmpty()) throw new ArgumentNullException(nameof(productId));
if (!productId.IsGuid()) throw new ValidationException("The value in the field productId is not a unique identifier.");
return _orderStorageContract.GetList(fromDate, toDate, productId: productId) ?? throw new NullListException();
}
public OrderDataModel GetOrderByData(string data)
{
_logger.LogInformation("Get element by data: {data}", data);
if (data.IsEmpty()) throw new ArgumentNullException(nameof(data));
if (!data.IsGuid()) throw new ValidationException("Id is not a unique identifier");
return _orderStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data);
}
public void InsertOrder(OrderDataModel orderDataModel)
{
_logger.LogInformation("New data: {json}", JsonSerializer.Serialize(orderDataModel));
ArgumentNullException.ThrowIfNull(orderDataModel);
orderDataModel.Validate();
_orderStorageContract.AddElement(orderDataModel);
}
public void CancelOrder(string id)
{
_logger.LogInformation("Cancel by id: {id}", id);
if (id.IsEmpty()) throw new ArgumentNullException(nameof(id));
if (!id.IsGuid()) throw new ValidationException("Id is not a unique identifier");
_orderStorageContract.DelElement(id);
}
}
}

View File

@@ -0,0 +1,71 @@
using Microsoft.Extensions.Logging;
using System.Text.Json;
using TheBlacksmithVakulaContract.BusinessLogicsContracts;
using TheBlacksmithVakulaContract.DataModels;
using TheBlacksmithVakulaContract.Exceptions;
using TheBlacksmithVakulaContract.Extensions;
using TheBlacksmithVakulaContract.StoragesContracts;
namespace TheBlacksmithVakulaBusinessLogic.Implementations
{
internal class ProductBusinessLogicContract(IProductStorageContract productStorageContract, ILogger logger) :
IProductBusinessLogicContract
{
private readonly IProductStorageContract _productStorageContract = productStorageContract;
private readonly ILogger _logger = logger;
public List<ProductDataModel> GetAllProducts(bool onlyActive)
{
_logger.LogInformation("GetAllProducts params: {onlyActive}", onlyActive);
return _productStorageContract.GetList(onlyActive) ?? throw new NullListException();
}
public List<ProductDataModel> GetAllProductsByBillet(string billetId, bool onlyActive = true)
{
if (billetId.IsEmpty()) throw new ArgumentNullException(nameof(billetId));
if (!billetId.IsGuid()) throw new ValidationException("The value in the field billetId is not a unique identifier.");
_logger.LogInformation("GetAllProducts params: {billetId}, { onlyActive}", billetId, onlyActive);
return _productStorageContract.GetList(onlyActive, billetId) ?? throw new NullListException();
}
public List<ProductHistoryDataModel> GetProductHistoryByProduct(string productId)
{
_logger.LogInformation("GetProductHistoryByProduct for {productId}", productId);
if (productId.IsEmpty()) throw new ArgumentNullException(nameof(productId));
if (!productId.IsGuid()) throw new ValidationException("The value in the field productId is not a unique identifier.");
return _productStorageContract.GetHistoryByProductId(productId) ?? throw new NullListException();
}
public ProductDataModel GetProductByData(string data)
{
_logger.LogInformation("Get element by data: {data}", data);
if (data.IsEmpty()) throw new ArgumentNullException(nameof(data));
if (data.IsGuid()) return _productStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data);
return _productStorageContract.GetElementByName(data) ?? throw new ElementNotFoundException(data);
}
public void InsertProduct(ProductDataModel productDataModel)
{
_logger.LogInformation("New data: {json}", JsonSerializer.Serialize(productDataModel));
ArgumentNullException.ThrowIfNull(productDataModel);
productDataModel.Validate();
_productStorageContract.AddElement(productDataModel);
}
public void UpdateProduct(ProductDataModel productDataModel)
{
_logger.LogInformation("Update data: {json}", JsonSerializer.Serialize(productDataModel));
ArgumentNullException.ThrowIfNull(productDataModel);
productDataModel.Validate();
_productStorageContract.UpdElement(productDataModel);
}
public void DeleteProduct(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");
_productStorageContract.DelElement(id);
}
}
}

View File

@@ -0,0 +1,70 @@
using Microsoft.Extensions.Logging;
using System.Text.Json;
using TheBlacksmithVakulaContract.BusinessLogicsContracts;
using TheBlacksmithVakulaContract.DataModels;
using TheBlacksmithVakulaContract.Exceptions;
using TheBlacksmithVakulaContract.Extensions;
using TheBlacksmithVakulaContract.StoragesContracts;
namespace TheBlacksmithVakulaBusinessLogic.Implementations
{
internal class RankBusinessLogicContract(IRankStorageContract rankStorageContract, ILogger logger) : IRankBusinessLogicContract
{
private readonly IRankStorageContract _rankStorageContract = rankStorageContract;
private readonly ILogger _logger = logger;
public List<RankDataModel> GetAllRanks()
{
_logger.LogInformation("GetAllRanks");
return _rankStorageContract.GetList() ?? throw new NullListException();
}
public List<RankDataModel> GetAllDataOfRank(string rankId)
{
_logger.LogInformation("GetAllDataOfRank for {rankId}", rankId);
if (rankId.IsEmpty()) throw new ArgumentNullException(nameof(rankId));
if (!rankId.IsGuid()) throw new ValidationException("The value in the field rankId is not a unique identifier.");
return _rankStorageContract.GetRankWithHistory(rankId) ?? throw new NullListException();
}
public RankDataModel GetRankByData(string data)
{
_logger.LogInformation("Get element by data: {data}", data);
if (data.IsEmpty()) throw new ArgumentNullException(nameof(data));
if (data.IsGuid()) return _rankStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data);
return _rankStorageContract.GetElementByName(data) ?? throw new ElementNotFoundException(data);
}
public void InsertRank(RankDataModel rankDataModel)
{
_logger.LogInformation("New data: {json}", JsonSerializer.Serialize(rankDataModel));
ArgumentNullException.ThrowIfNull(rankDataModel);
rankDataModel.Validate();
_rankStorageContract.AddElement(rankDataModel);
}
public void UpdateRank(RankDataModel rankDataModel)
{
_logger.LogInformation("Update data: {json}", JsonSerializer.Serialize(rankDataModel));
ArgumentNullException.ThrowIfNull(rankDataModel);
rankDataModel.Validate();
_rankStorageContract.UpdElement(rankDataModel);
}
public void DeleteRank(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");
_rankStorageContract.DelElement(id);
}
public void RestoreRank(string id)
{
_logger.LogInformation("Restore by id: {id}", id);
if (id.IsEmpty()) throw new ArgumentNullException(nameof(id));
if (!id.IsGuid()) throw new ValidationException("Id is not a unique identifier");
_rankStorageContract.ResElement(id);
}
}
}

View File

@@ -0,0 +1,50 @@
using Microsoft.Extensions.Logging;
using TheBlacksmithVakulaContract.BusinessLogicsContracts;
using TheBlacksmithVakulaContract.DataModels;
using TheBlacksmithVakulaContract.Exceptions;
using TheBlacksmithVakulaContract.Extensions;
using TheBlacksmithVakulaContract.StoragesContracts;
namespace TheBlacksmithVakulaBusinessLogic.Implementations
{
internal class SalaryBusinessLogicContract(ISalaryStorageContract salaryStorageContract, IOrderStorageContract orderStorageContract,
IBlacksmithStorageContract blacksmithStorageContract, ILogger logger) : ISalaryBusinessLogicContract
{
private readonly ISalaryStorageContract _salaryStorageContract = salaryStorageContract;
private readonly IOrderStorageContract _orderStorageContract = orderStorageContract;
private readonly IBlacksmithStorageContract _blacksmithStorageContract = blacksmithStorageContract;
private readonly ILogger _logger = logger;
public List<SalaryDataModel> GetAllSalariesByPeriod(DateTime fromDate, DateTime toDate)
{
_logger.LogInformation("GetAllSalaries params: {fromDate}, {toDate}", fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate)) throw new IncorrectDatesException(fromDate, toDate);
return _salaryStorageContract.GetList(fromDate, toDate) ?? throw new NullListException();
}
public List<SalaryDataModel> GetAllSalariesByPeriodByBlacksmith(DateTime fromDate, DateTime toDate, string blacksmithId)
{
if (fromDate.IsDateNotOlder(toDate)) throw new IncorrectDatesException(fromDate, toDate);
if (blacksmithId.IsEmpty()) throw new ArgumentNullException(nameof(blacksmithId));
if (!blacksmithId.IsGuid()) throw new ValidationException("The value in the field blacksmithId is not a unique identifier.");
_logger.LogInformation("GetAllSalaries params: {fromDate}, {toDate}, { blacksmithId}", fromDate, toDate, blacksmithId);
return _salaryStorageContract.GetList(fromDate, toDate, blacksmithId) ?? throw new NullListException();
}
public void CalculateSalaryByMounth(DateTime date)
{
_logger.LogInformation("CalculateSalaryByMounth: {date}", date);
var startDate = new DateTime(date.Year, date.Month, 1);
var finishDate = new DateTime(date.Year, date.Month, DateTime.DaysInMonth(date.Year, date.Month));
var blacksmiths = _blacksmithStorageContract.GetList() ?? throw new NullListException();
foreach (var blacksmith in blacksmiths)
{
var orders = _orderStorageContract.GetList(startDate, finishDate, blacksmithId: blacksmith.Id)?.Sum(x => x.Sum) ??
throw new NullListException();
var salary = orders * 0.5;
_logger.LogDebug("The employee {blacksmithId} was paid a salary of { salary}", blacksmith.Id, salary);
_salaryStorageContract.AddElement(new SalaryDataModel(blacksmith.Id, finishDate, salary));
}
}
}
}

View File

@@ -0,0 +1,23 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<InternalsVisibleTo Include="TheBlacksmithVakulaTests" />
<InternalsVisibleTo Include="TheBlacksmithVakulaWebApi" />
<InternalsVisibleTo Include="DinamicProxyGenAssembly2" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging" Version="9.0.4" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\TheBlacksmithVakulaContract\TheBlacksmithVakulaContract.csproj" />
</ItemGroup>
</Project>

View File

@@ -7,6 +7,12 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TheBlacksmithVakulaContract
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TheBlacksmithVakulaTests", "TheBlacksmithVakulaTests\TheBlacksmithVakulaTests.csproj", "{E713C757-C913-43D7-AC6C-F146E676EECF}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TheBlacksmithVakulaBusinessLogic", "TheBlacksmithVakulaBuisnessLogic\TheBlacksmithVakulaBusinessLogic.csproj", "{4EC98B18-0ED9-42F1-940F-3D620727D34E}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TheBlacksmithVakulaDatabase", "TheBlacksmithVakulaDatabase\TheBlacksmithVakulaDatabase.csproj", "{A68C4088-F1BD-47E6-8E14-8BCA8AE86B52}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TheBlacksmithVakulaWebApi", "TheBlacksmithVakulaWebApi\TheBlacksmithVakulaWebApi.csproj", "{19350294-4EF7-4476-9418-A119EF83CDE4}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@@ -21,8 +27,23 @@ Global
{E713C757-C913-43D7-AC6C-F146E676EECF}.Debug|Any CPU.Build.0 = Debug|Any CPU
{E713C757-C913-43D7-AC6C-F146E676EECF}.Release|Any CPU.ActiveCfg = Release|Any CPU
{E713C757-C913-43D7-AC6C-F146E676EECF}.Release|Any CPU.Build.0 = Release|Any CPU
{4EC98B18-0ED9-42F1-940F-3D620727D34E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{4EC98B18-0ED9-42F1-940F-3D620727D34E}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4EC98B18-0ED9-42F1-940F-3D620727D34E}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4EC98B18-0ED9-42F1-940F-3D620727D34E}.Release|Any CPU.Build.0 = Release|Any CPU
{A68C4088-F1BD-47E6-8E14-8BCA8AE86B52}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{A68C4088-F1BD-47E6-8E14-8BCA8AE86B52}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A68C4088-F1BD-47E6-8E14-8BCA8AE86B52}.Release|Any CPU.ActiveCfg = Release|Any CPU
{A68C4088-F1BD-47E6-8E14-8BCA8AE86B52}.Release|Any CPU.Build.0 = Release|Any CPU
{19350294-4EF7-4476-9418-A119EF83CDE4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{19350294-4EF7-4476-9418-A119EF83CDE4}.Debug|Any CPU.Build.0 = Debug|Any CPU
{19350294-4EF7-4476-9418-A119EF83CDE4}.Release|Any CPU.ActiveCfg = Release|Any CPU
{19350294-4EF7-4476-9418-A119EF83CDE4}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {D78097F2-2881-49D7-A49C-DFD5B169283B}
EndGlobalSection
EndGlobal

View File

@@ -0,0 +1,18 @@
using TheBlacksmithVakulaContract.AdapterContracts.OperationResponses;
using TheBlacksmithVakulaContract.BindingModels;
namespace TheBlacksmithVakulaContract.AdapterContracts
{
public interface IBilletAdapter
{
BilletOperationResponse GetList();
BilletOperationResponse GetElement(string data);
BilletOperationResponse RegisterBillet(BilletBindingModel billetModel);
BilletOperationResponse ChangeBilletInfo(BilletBindingModel billetModel);
BilletOperationResponse RemoveBillet(string id);
}
}

View File

@@ -0,0 +1,24 @@
using TheBlacksmithVakulaContract.AdapterContracts.OperationResponses;
using TheBlacksmithVakulaContract.BindingModels;
namespace TheBlacksmithVakulaContract.AdapterContracts
{
public interface IBlacksmithAdapter
{
BlacksmithOperationResponse GetList(bool includeDeleted);
BlacksmithOperationResponse GetRankList(string id, bool includeDeleted);
BlacksmithOperationResponse GetListByBirthDate(DateTime fromDate, DateTime toDate, bool includeDeleted);
BlacksmithOperationResponse GetListByEmploymentDate(DateTime fromDate, DateTime toDate, bool includeDeleted);
BlacksmithOperationResponse GetElement(string data);
BlacksmithOperationResponse RegisterBlacksmith(BlacksmithBindingModel blacksmithModel);
BlacksmithOperationResponse ChangeBlacksmithInfo(BlacksmithBindingModel blacksmithModel);
BlacksmithOperationResponse RemoveBlacksmith(string id);
}
}

View File

@@ -0,0 +1,18 @@
using TheBlacksmithVakulaContract.AdapterContracts.OperationResponses;
using TheBlacksmithVakulaContract.BindingModels;
namespace TheBlacksmithVakulaContract.AdapterContracts
{
public interface IBuyerAdapter
{
BuyerOperationResponse GetList();
BuyerOperationResponse GetElement(string data);
BuyerOperationResponse RegisterBuyer(BuyerBindingModel buyerModel);
BuyerOperationResponse ChangeBuyerInfo(BuyerBindingModel buyerModel);
BuyerOperationResponse RemoveBuyer(string id);
}
}

View File

@@ -0,0 +1,22 @@
using TheBlacksmithVakulaContract.AdapterContracts.OperationResponses;
using TheBlacksmithVakulaContract.BindingModels;
namespace TheBlacksmithVakulaContract.AdapterContracts
{
public interface IOrderAdapter
{
OrderOperationResponse GetList(DateTime fromDate, DateTime toDate);
OrderOperationResponse GetBlacksmithList(string id, DateTime fromDate, DateTime toDate);
OrderOperationResponse GetBuyerList(string id, DateTime fromDate, DateTime toDate);
OrderOperationResponse GetProductList(string id, DateTime fromDate, DateTime toDate);
OrderOperationResponse GetElement(string id);
OrderOperationResponse MakeOrder(OrderBindingModel orderModel);
OrderOperationResponse CancelOrder(string id);
}
}

View File

@@ -0,0 +1,22 @@
using TheBlacksmithVakulaContract.AdapterContracts.OperationResponses;
using TheBlacksmithVakulaContract.BindingModels;
namespace TheBlacksmithVakulaContract.AdapterContracts
{
public interface IProductAdapter
{
ProductOperationResponse GetList(bool includeDeleted);
ProductOperationResponse GetBilletList(string id, bool includeDeleted);
ProductOperationResponse GetHistory(string id);
ProductOperationResponse GetElement(string data);
ProductOperationResponse RegisterProduct(ProductBindingModel productModel);
ProductOperationResponse ChangeProductInfo(ProductBindingModel productModel);
ProductOperationResponse RemoveProduct(string id);
}
}

View File

@@ -0,0 +1,22 @@
using TheBlacksmithVakulaContract.AdapterContracts.OperationResponses;
using TheBlacksmithVakulaContract.BindingModels;
namespace TheBlacksmithVakulaContract.AdapterContracts
{
public interface IRankAdapter
{
RankOperationResponse GetList();
RankOperationResponse GetHistory(string id);
RankOperationResponse GetElement(string data);
RankOperationResponse RegisterRank(RankBindingModel rankModel);
RankOperationResponse ChangeRankInfo(RankBindingModel rankModel);
RankOperationResponse RemoveRank(string id);
RankOperationResponse RestoreRank(string id);
}
}

View File

@@ -0,0 +1,13 @@
using TheBlacksmithVakulaContract.AdapterContracts.OperationResponses;
namespace TheBlacksmithVakulaContract.AdapterContracts
{
public interface ISalaryAdapter
{
SalaryOperationResponse GetListByPeriod(DateTime fromDate, DateTime toDate);
SalaryOperationResponse GetListByPeriodByBlacksmith(DateTime fromDate, DateTime toDate, string blacksmithId);
SalaryOperationResponse CalculateSalary(DateTime date);
}
}

View File

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

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,22 @@
using TheBlacksmithVakulaContract.Infrastructure;
using TheBlacksmithVakulaContract.ViewModels;
namespace TheBlacksmithVakulaContract.AdapterContracts.OperationResponses
{
public class ProductOperationResponse : OperationResponse
{
public static ProductOperationResponse OK(List<ProductViewModel> data) => OK<ProductOperationResponse, List<ProductViewModel>>(data);
public static ProductOperationResponse OK(List<ProductHistoryViewModel> data) => OK<ProductOperationResponse, List<ProductHistoryViewModel>>(data);
public static ProductOperationResponse OK(ProductViewModel data) => OK<ProductOperationResponse, ProductViewModel>(data);
public static ProductOperationResponse NoContent() => NoContent<ProductOperationResponse>();
public static ProductOperationResponse NotFound(string message) => NotFound<ProductOperationResponse>(message);
public static ProductOperationResponse BadRequest(string message) => BadRequest<ProductOperationResponse>(message);
public static ProductOperationResponse InternalServerError(string message) => InternalServerError<ProductOperationResponse>(message);
}
}

View File

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

View File

@@ -0,0 +1,18 @@
using TheBlacksmithVakulaContract.Infrastructure;
using TheBlacksmithVakulaContract.ViewModels;
namespace TheBlacksmithVakulaContract.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,9 @@
namespace TheBlacksmithVakulaContract.BindingModels
{
public class BilletBindingModel
{
public string? Id { get; set; }
public string? BilletName { get; set; }
}
}

View File

@@ -0,0 +1,15 @@
namespace TheBlacksmithVakulaContract.BindingModels
{
public class BlacksmithBindingModel
{
public string? Id { get; set; }
public string? FIO { get; set; }
public string? RankId { get; set; }
public DateTime BirthDate { get; set; }
public DateTime EmploymentDate { get; set; }
}
}

View File

@@ -0,0 +1,13 @@
namespace TheBlacksmithVakulaContract.BindingModels
{
public class BuyerBindingModel
{
public string? Id { get; set; }
public string? FIO { get; set; }
public string? PhoneNumber { get; set; }
public double DiscountSize { get; set; }
}
}

View File

@@ -0,0 +1,15 @@
namespace TheBlacksmithVakulaContract.BindingModels
{
public class OrderBindingModel
{
public string? Id { get; set; }
public string? BlacksmithId { get; set; }
public string? BuyerId { get; set; }
public int DiscountType { get; set; }
public List<OrderProductBindingModel>? Products { get; set; }
}
}

View File

@@ -0,0 +1,11 @@
namespace TheBlacksmithVakulaContract.BindingModels
{
public class OrderProductBindingModel
{
public string? OrderId { get; set; }
public string? ProductId { get; set; }
public int Count { get; set; }
}
}

View File

@@ -0,0 +1,15 @@
namespace TheBlacksmithVakulaContract.BindingModels
{
public class ProductBindingModel
{
public string? Id { get; set; }
public string? ProductName { get; set; }
public string? ProductType { get; set; }
public string? BilletId { get; set; }
public double Price { get; set; }
}
}

View File

@@ -0,0 +1,13 @@
namespace TheBlacksmithVakulaContract.BindingModels
{
public class RankBindingModel
{
public string? Id { get; set; }
public string? RankId => Id;
public string? RankName { get; set; }
public string? RankType { get; set; }
}
}

View File

@@ -0,0 +1,17 @@
using TheBlacksmithVakulaContract.DataModels;
namespace TheBlacksmithVakulaContract.BusinessLogicsContracts
{
public interface IBilletBusinessLogicContract
{
List<BilletDataModel> GetAllBillets();
BilletDataModel GetBilletByData(string data);
void InsertBillet(BilletDataModel model);
void UpdateBillet(BilletDataModel model);
void DeleteBillet(string id);
}
}

View File

@@ -0,0 +1,23 @@
using TheBlacksmithVakulaContract.DataModels;
namespace TheBlacksmithVakulaContract.BusinessLogicsContracts
{
public interface IBlacksmithBusinessLogicContract
{
List<BlacksmithDataModel> GetAllBlacksmith(bool onlyActive = true);
List<BlacksmithDataModel> GetAllBlacksmithByRank(string rankId, bool onlyActive = true);
List<BlacksmithDataModel> GetAllBlacksmithByBirthDate(DateTime fromDate, DateTime toDate, bool onlyActive = true);
List<BlacksmithDataModel> GetAllBlacksmithByEmploymentDate(DateTime fromDate, DateTime toDate, bool onlyActive = true);
BlacksmithDataModel GetBlacksmithByData(string data);
void InsertBlacksmith(BlacksmithDataModel model);
void UpdateBlacksmith(BlacksmithDataModel model);
void DeleteBlacksmith(string id);
}
}

View File

@@ -0,0 +1,17 @@
using TheBlacksmithVakulaContract.DataModels;
namespace TheBlacksmithVakulaContract.BusinessLogicsContracts
{
public interface IBuyerBusinessLogicContract
{
List<BuyerDataModel> GetAllBuyers();
BuyerDataModel GetBuyerByData(string data);
void InsertBuyer(BuyerDataModel model);
void UpdateBuyer(BuyerDataModel model);
void DeleteBuyer(string id);
}
}

View File

@@ -0,0 +1,21 @@
using TheBlacksmithVakulaContract.DataModels;
namespace TheBlacksmithVakulaContract.BusinessLogicsContracts
{
public interface IOrderBusinessLogicContract
{
List<OrderDataModel> GetAllOrderByPeriod(DateTime startDate, DateTime endDate);
List<OrderDataModel> GetAllOrderByBlacksmithByPeriod(string blacksmithId, DateTime startDate, DateTime endDate);
List<OrderDataModel> GetAllOrderByBuyerByPeriod(string buyerId, DateTime startDate, DateTime endDate);
List<OrderDataModel> GetAllOrderByProductByPeriod(string productId, DateTime startDate, DateTime endDate);
OrderDataModel GetOrderByData(string data);
void InsertOrder(OrderDataModel model);
void CancelOrder(string id);
}
}

View File

@@ -0,0 +1,21 @@
using TheBlacksmithVakulaContract.DataModels;
namespace TheBlacksmithVakulaContract.BusinessLogicsContracts
{
public interface IProductBusinessLogicContract
{
List<ProductDataModel> GetAllProducts(bool onlyActive = true);
List<ProductDataModel> GetAllProductsByBillet(string billetId, bool onlyActive = true);
List<ProductHistoryDataModel> GetProductHistoryByProduct(string productId);
ProductDataModel GetProductByData(string data);
void InsertProduct(ProductDataModel model);
void UpdateProduct(ProductDataModel model);
void DeleteProduct(string id);
}
}

View File

@@ -0,0 +1,21 @@
using TheBlacksmithVakulaContract.DataModels;
namespace TheBlacksmithVakulaContract.BusinessLogicsContracts
{
public interface IRankBusinessLogicContract
{
List<RankDataModel> GetAllRanks();
List<RankDataModel> GetAllDataOfRank(string rankId);
RankDataModel GetRankByData(string data);
void InsertRank(RankDataModel model);
void UpdateRank(RankDataModel model);
void DeleteRank(string id);
void RestoreRank(string id);
}
}

View File

@@ -0,0 +1,13 @@
using TheBlacksmithVakulaContract.DataModels;
namespace TheBlacksmithVakulaContract.BusinessLogicsContracts
{
public interface ISalaryBusinessLogicContract
{
List<SalaryDataModel> GetAllSalariesByPeriod(DateTime startDate, DateTime endDate);
List<SalaryDataModel> GetAllSalariesByPeriodByBlacksmith(DateTime startDate, DateTime endDate, string blacksmithId);
void CalculateSalaryByMounth(DateTime date);
}
}

View File

@@ -1,18 +1,20 @@
using System.ComponentModel.DataAnnotations;
using TheBlacksmithVakulaContract.Exceptions;
using TheBlacksmithVakulaContract.Extensions;
using TheBlacksmithVakulaContract.Infrastructure;
namespace TheBlacksmithVakulaContract.DataModels
{
public class BilletDataModel(string id, string billetName, string prevBilletName, string prevPrevBilletName) : IValidation
public class BilletDataModel(string id, string billetName, string? prevBilletName, string? prevPrevBilletName) : IValidation
{
public string Id { get; private set; } = id;
public string BilletName { get; private set; } = billetName;
public string PrevBilletName { get; private set; } = prevBilletName;
public string? PrevBilletName { get; private set; } = prevBilletName;
public string PrevPrevBilletName { get; private set; } = prevPrevBilletName;
public string? PrevPrevBilletName { get; private set; } = prevPrevBilletName;
public BilletDataModel(string id, string billetName) : this(id, billetName, null, null) { }
public void Validate()
{

View File

@@ -6,6 +6,8 @@ namespace TheBlacksmithVakulaContract.DataModels
{
public class BlacksmithDataModel(string id, string fio, string rankId, DateTime birthDate, DateTime employmentDate, bool isDeleted) : IValidation
{
private readonly RankDataModel? _rank;
public string Id { get; private set; } = id;
public string FIO { get; private set; } = fio;
@@ -18,6 +20,16 @@ namespace TheBlacksmithVakulaContract.DataModels
public bool IsDeleted { get; private set; } = isDeleted;
public string RankName => _rank?.RankName ?? string.Empty;
public BlacksmithDataModel(string id, string fio, string rankId, DateTime birthDate, DateTime employmentDate, bool isDeleted, RankDataModel rank) : this(id, fio, rankId, birthDate, employmentDate, isDeleted)
{
_rank = rank;
}
public BlacksmithDataModel(string id, string fio, string rankId, DateTime birthDate, DateTime employmentDate) : this(id, fio, rankId, birthDate, employmentDate, false) { }
public void Validate()
{
if (Id.IsEmpty())

View File

@@ -5,26 +5,76 @@ using TheBlacksmithVakulaContract.Infrastructure;
namespace TheBlacksmithVakulaContract.DataModels
{
public class OrderDataModel(string id, string blacksmithId, string? buyerId, double sum, DiscountType discountType,
double discount, bool isCancel, List<OrderProductDataModel> products) : IValidation
public class OrderDataModel : IValidation
{
public string Id { get; private set; } = id;
private readonly BuyerDataModel? _buyer;
public string BlacksmithId { get; private set; } = blacksmithId;
private readonly BlacksmithDataModel? _blacksmith;
public string? BuyerId { get; private set; } = buyerId;
public string Id { get; private set; }
public string BlacksmithId { get; private set; }
public string? BuyerId { get; private set; }
public DateTime OrderDate { get; private set; } = DateTime.UtcNow;
public double Sum { get; private set; } = sum;
public double Sum { get; private set; }
public DiscountType DiscountType { get; private set; } = discountType;
public DiscountType DiscountType { get; private set; }
public double Discount { get; private set; } = discount;
public double Discount { get; private set; }
public bool IsCancel { get; private set; } = isCancel;
public bool IsCancel { get; private set; }
public List<OrderProductDataModel> Products { get; private set; } = products;
public List<OrderProductDataModel> Products { get; private set; }
public string BuyerFIO => _buyer?.FIO ?? string.Empty;
public string BlacksmithFIO => _blacksmith?.FIO ?? string.Empty;
public OrderDataModel(string id, string blacksmithId, string? buyerId, DiscountType discountType, bool isCancel, List<OrderProductDataModel> orderProducts)
{
Id = id;
BlacksmithId = blacksmithId;
BuyerId = buyerId;
DiscountType = discountType;
IsCancel = isCancel;
Products = orderProducts;
var percent = 0.0;
foreach (DiscountType elem in Enum.GetValues<DiscountType>())
{
if ((elem & discountType) != 0)
{
switch (elem)
{
case DiscountType.None:
break;
case DiscountType.OnSale:
percent += 0.1;
break;
case DiscountType.RegularCustomer:
percent += 0.5;
break;
case DiscountType.Certificate:
percent += 0.3;
break;
}
}
}
Sum = Products?.Sum(x => 1000 * x.Count) ?? 0;
Discount = Sum * percent;
}
public OrderDataModel(string id, string blacksmithId, string? buyerId, double sum, DiscountType discountType, double discount, bool isCancel, List<OrderProductDataModel> orderProducts, BlacksmithDataModel? blacksmith, BuyerDataModel? buyer) : this(id, blacksmithId, buyerId, discountType, isCancel, orderProducts)
{
Sum = sum;
Discount = discount;
_blacksmith = blacksmith;
_buyer = buyer;
}
public OrderDataModel(string id, string blacksmithId, string? buyerId, int discountType, List<OrderProductDataModel> products) : this(id, blacksmithId, buyerId, (DiscountType)discountType, false, products) { }
public void Validate()
{
@@ -41,7 +91,7 @@ namespace TheBlacksmithVakulaContract.DataModels
if (Sum <= 0)
throw new ValidationException("Field Sum is less than or equal to 0");
if ((Products?.Count ?? 0) == 0)
throw new ValidationException("The sale must include products");
throw new ValidationException("The order must include products");
}
}

View File

@@ -6,12 +6,21 @@ namespace TheBlacksmithVakulaContract.DataModels
{
public class OrderProductDataModel(string orderId, string productId, int count) : IValidation
{
private readonly ProductDataModel? _product;
public string OrderId { get; private set; } = orderId;
public string ProductId { get; private set; } = productId;
public int Count { get; private set; } = count;
public string ProductName => _product?.ProductName ?? string.Empty;
public OrderProductDataModel(string orderId, string productId, int count, ProductDataModel product) : this(orderId, productId, count)
{
_product = product;
}
public void Validate()
{
if (OrderId.IsEmpty())

View File

@@ -8,6 +8,8 @@ namespace TheBlacksmithVakulaContract.DataModels
public class ProductDataModel(string id, string productName, ProductType productType,
string billetId, double price, bool isDeleted) : IValidation
{
private readonly BilletDataModel? _billet;
public string Id { get; private set; } = id;
public string ProductName { get; private set; } = productName;
@@ -20,6 +22,15 @@ namespace TheBlacksmithVakulaContract.DataModels
public bool IsDeleted { get; private set; } = isDeleted;
public string BilletName => _billet?.BilletName ?? string.Empty;
public ProductDataModel(string id, string productName, ProductType productType, string billetId, double price, bool isDeleted, BilletDataModel billet) : this(id, productName, productType, billetId, price, isDeleted)
{
_billet = billet;
}
public ProductDataModel(string id, string productName, ProductType productType, string billetId, double price) : this(id, productName, productType, billetId, price, false) { }
public void Validate()
{
if (Id.IsEmpty())

View File

@@ -6,12 +6,21 @@ namespace TheBlacksmithVakulaContract.DataModels
{
public class ProductHistoryDataModel(string productId, double oldPrice) : IValidation
{
private readonly ProductDataModel? _product;
public string ProductId { get; private set; } = productId;
public double OldPrice { get; private set; } = oldPrice;
public DateTime ChangeDate { get; private set; } = DateTime.UtcNow;
public string ProductName => _product?.ProductName ?? string.Empty;
public ProductHistoryDataModel(string productId, double oldPrice, DateTime changeDate, ProductDataModel product) : this(productId, oldPrice)
{
ChangeDate = changeDate;
_product = product;
}
public void Validate()
{
if (ProductId.IsEmpty())

View File

@@ -1,34 +1,24 @@
using System.ComponentModel.DataAnnotations;
using TheBlacksmithVakulaContract.Enums;
using TheBlacksmithVakulaContract.Enums;
using TheBlacksmithVakulaContract.Exceptions;
using TheBlacksmithVakulaContract.Extensions;
using TheBlacksmithVakulaContract.Infrastructure;
namespace TheBlacksmithVakulaContract.DataModels
{
public class RankDataModel(string id, string rankId, string rankName, RankType rankType, bool isActual, DateTime changeDate) : IValidation
public class RankDataModel(string rankId, string rankName, RankType rankType) : IValidation
{
public string Id { get; private set; } = id;
public string RankId { get; private set; } = rankId;
public string Id { get; private set; } = rankId;
public string RankName { get; private set; } = rankName;
public RankType RankType { get; private set; } = rankType;
public bool IsActual { get; private set; } = isActual;
public DateTime ChangeDate { get; private set; } = changeDate;
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 (RankId.IsEmpty())
throw new ValidationException("Field RankId is empty");
if (!RankId.IsGuid())
throw new ValidationException("The value in the field RankId is not a unique identifier");
if (RankName.IsEmpty())
throw new ValidationException("Field RankName is empty");
if (RankType == RankType.None)

View File

@@ -4,13 +4,22 @@ using TheBlacksmithVakulaContract.Infrastructure;
namespace TheBlacksmithVakulaContract.DataModels
{
public class SalaryDataModel(string blacksmithId, DateTime salaryDate, double salary) : IValidation
public class SalaryDataModel(string blacksmithId, DateTime salaryDate, double blacksmithSalary) : IValidation
{
private readonly BlacksmithDataModel? _blacksmith;
public string BlacksmithId { get; private set; } = blacksmithId;
public DateTime SalaryDate { get; private set; } = salaryDate;
public double Salary { get; private set; } = salary;
public double Salary { get; private set; } = blacksmithSalary;
public string BlacksmithFIO => _blacksmith?.FIO ?? string.Empty;
public SalaryDataModel(string blacksmithId, DateTime salaryDate, double blacksmithSalary, BlacksmithDataModel blacksmith) : this(blacksmithId, salaryDate, blacksmithSalary)
{
_blacksmith = blacksmith;
}
public void Validate()
{

View File

@@ -0,0 +1,7 @@
namespace TheBlacksmithVakulaContract.Exceptions
{
public class ElementDeletedException : Exception
{
public ElementDeletedException(string id) : base($"Cannot modify a deleted item(id: { id})") { }
}
}

View File

@@ -0,0 +1,16 @@
namespace TheBlacksmithVakulaContract.Exceptions
{
public class ElementExistsException : Exception
{
public string ParamName { get; private set; }
public string ParamValue { get; private set; }
public ElementExistsException(string paramName, string paramValue) :
base($"There is already an element with value {paramValue} of parameter {paramName}")
{
ParamName = paramName;
ParamValue = paramValue;
}
}
}

View File

@@ -0,0 +1,12 @@
namespace TheBlacksmithVakulaContract.Exceptions
{
public class ElementNotFoundException : Exception
{
public string Value { get; private set; }
public ElementNotFoundException(string value) : base($"Element not found at value: {value}")
{
Value = value;
}
}
}

View File

@@ -0,0 +1,8 @@
namespace TheBlacksmithVakulaContract.Exceptions
{
public class IncorrectDatesException : Exception
{
public IncorrectDatesException(DateTime start, DateTime end) :
base($"The end date must be later than the start date.. StartDate: {start: dd.MM.YYYYEnd} Date: {end:dd.MM.YYYY}") { }
}
}

View File

@@ -0,0 +1,7 @@
namespace TheBlacksmithVakulaContract.Exceptions
{
public class NullListException : Exception
{
public NullListException() : base("The returned list is null") { }
}
}

View File

@@ -0,0 +1,7 @@
namespace TheBlacksmithVakulaContract.Exceptions
{
public class StorageException : Exception
{
public StorageException(Exception ex) : base($"Error while working in storage {ex.Message}", ex) { }
}
}

View File

@@ -1,6 +1,4 @@
namespace TheBlacksmithVakulaContract.Exceptions
{
public class ValidationException(string message) : Exception(message)
{
}
public class ValidationException(string message) : Exception(message) { }
}

View File

@@ -0,0 +1,10 @@
namespace TheBlacksmithVakulaContract.Extensions
{
public static class DateTimeExtensions
{
public static bool IsDateNotOlder(this DateTime date, DateTime olderDate)
{
return date >= olderDate;
}
}
}

View File

@@ -0,0 +1,7 @@
namespace TheBlacksmithVakulaContract.Infrastructure
{
public interface IConfigurationDatabase
{
string ConnectionString { get; }
}
}

View File

@@ -0,0 +1,43 @@
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Net;
namespace TheBlacksmithVakulaContract.Infrastructure
{
public class OperationResponse
{
protected HttpStatusCode StatusCode { get; set; }
protected 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

@@ -0,0 +1,21 @@
using TheBlacksmithVakulaContract.DataModels;
namespace TheBlacksmithVakulaContract.StoragesContracts
{
public interface IBilletStorageContract
{
List<BilletDataModel> GetList();
BilletDataModel? GetElementById(string id);
BilletDataModel? GetElementByName(string name);
BilletDataModel? GetElementByOldName(string name);
void AddElement(BilletDataModel element);
void UpdElement(BilletDataModel element);
void DelElement(string id);
}
}

View File

@@ -0,0 +1,20 @@
using TheBlacksmithVakulaContract.DataModels;
namespace TheBlacksmithVakulaContract.StoragesContracts
{
public interface IBlacksmithStorageContract
{
List<BlacksmithDataModel> GetList(bool onlyActive = true, string? rankId = null, DateTime? fromBirthDate = null,
DateTime? toBirthDate = null, DateTime? fromEmploymentDate = null, DateTime? toEmploymentDate = null);
BlacksmithDataModel? GetElementById(string id);
BlacksmithDataModel? GetElementByFIO(string fio);
void AddElement(BlacksmithDataModel element);
void UpdElement(BlacksmithDataModel element);
void DelElement(string id);
}
}

View File

@@ -0,0 +1,21 @@
using TheBlacksmithVakulaContract.DataModels;
namespace TheBlacksmithVakulaContract.StoragesContracts
{
public interface IBuyerStorageContract
{
List<BuyerDataModel> GetList();
BuyerDataModel? GetElementById(string id);
BuyerDataModel? GetElementByPhoneNumber(string phoneNumber);
BuyerDataModel? GetElementByFIO(string fio);
void AddElement(BuyerDataModel element);
void UpdElement(BuyerDataModel element);
void DelElement(string id);
}
}

View File

@@ -0,0 +1,16 @@
using TheBlacksmithVakulaContract.DataModels;
namespace TheBlacksmithVakulaContract.StoragesContracts
{
public interface IOrderStorageContract
{
List<OrderDataModel> GetList(DateTime? startDate = null, DateTime? endDate = null, string? blacksmithId = null,
string? productId = null, string? buyerId = null);
OrderDataModel? GetElementById(string id);
void AddElement(OrderDataModel element);
void DelElement(string id);
}
}

View File

@@ -0,0 +1,21 @@
using TheBlacksmithVakulaContract.DataModels;
namespace TheBlacksmithVakulaContract.StoragesContracts
{
public interface IProductStorageContract
{
List<ProductDataModel> GetList(bool onlyActive = true, string? billetId = null);
List<ProductHistoryDataModel> GetHistoryByProductId(string productId);
ProductDataModel? GetElementById(string id);
ProductDataModel? GetElementByName(string name);
void AddElement(ProductDataModel element);
void UpdElement(ProductDataModel element);
void DelElement(string id);
}
}

View File

@@ -0,0 +1,23 @@
using TheBlacksmithVakulaContract.DataModels;
namespace TheBlacksmithVakulaContract.StoragesContracts
{
public interface IRankStorageContract
{
List<RankDataModel> GetList();
List<RankDataModel> GetRankWithHistory(string rankId);
RankDataModel? GetElementById(string id);
RankDataModel? GetElementByName(string name);
void AddElement(RankDataModel element);
void UpdElement(RankDataModel element);
void DelElement(string id);
void ResElement(string id);
}
}

View File

@@ -0,0 +1,11 @@
using TheBlacksmithVakulaContract.DataModels;
namespace TheBlacksmithVakulaContract.StoragesContracts
{
public interface ISalaryStorageContract
{
List<SalaryDataModel> GetList(DateTime startDate, DateTime endDate, string? blacksmithId = null);
void AddElement(SalaryDataModel element);
}
}

View File

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

View File

@@ -0,0 +1,13 @@
namespace TheBlacksmithVakulaContract.ViewModels
{
public class BilletViewModel
{
public required string Id { get; set; }
public required string BilletName { get; set; }
public string? PrevBilletName { get; set; }
public string? PrevPrevBilletName { get; set; }
}
}

View File

@@ -0,0 +1,19 @@
namespace TheBlacksmithVakulaContract.ViewModels
{
public class BlacksmithViewModel
{
public required string Id { get; set; }
public required string FIO { get; set; }
public required string RankId { get; set; }
public required string RankName { get; set; }
public bool IsDeleted { get; set; }
public DateTime BirthDate { get; set; }
public DateTime EmploymentDate { get; set; }
}
}

View File

@@ -0,0 +1,13 @@
namespace TheBlacksmithVakulaContract.ViewModels
{
public class BuyerViewModel
{
public required string Id { get; set; }
public required string FIO { get; set; }
public required string PhoneNumber { get; set; }
public double DiscountSize { get; set; }
}
}

View File

@@ -0,0 +1,11 @@
namespace TheBlacksmithVakulaContract.ViewModels
{
public class OrderProductViewModel
{
public required string ProductId { get; set; }
public required string ProductName { get; set; }
public int Count { get; set; }
}
}

View File

@@ -0,0 +1,27 @@
namespace TheBlacksmithVakulaContract.ViewModels
{
public class OrderViewModel
{
public required string Id { get; set; }
public required string BlacksmithId { get; set; }
public required string BlacksmithFIO { get; set; }
public string? BuyerId { get; set; }
public string? BuyerFIO { get; set; }
public DateTime OrderDate { get; set; }
public double Sum { get; set; }
public required string DiscountType { get; set; }
public double Discount { get; set; }
public bool IsCancel { get; set; }
public required List<OrderProductViewModel> Products { get; set; }
}
}

View File

@@ -0,0 +1,11 @@
namespace TheBlacksmithVakulaContract.ViewModels
{
public class ProductHistoryViewModel
{
public required string ProductName { get; set; }
public double OldPrice { get; set; }
public DateTime ChangeDate { get; set; }
}
}

View File

@@ -0,0 +1,19 @@
namespace TheBlacksmithVakulaContract.ViewModels
{
public class ProductViewModel
{
public required string Id { get; set; }
public required string ProductName { get; set; }
public required string BilletId { get; set; }
public required string BilletName { get; set; }
public required string ProductType { get; set; }
public double Price { get; set; }
public bool IsDeleted { get; set; }
}
}

View File

@@ -0,0 +1,11 @@
namespace TheBlacksmithVakulaContract.ViewModels
{
public class RankViewModel
{
public required string Id { get; set; }
public required string RankName { get; set; }
public required string RankType { get; set; }
}
}

View File

@@ -0,0 +1,13 @@
namespace TheBlacksmithVakulaContract.ViewModels
{
public class SalaryViewModel
{
public required string BlacksmithId { get; set; }
public required string BlacksmithFIO { get; set; }
public DateTime SalaryDate { get; set; }
public double Salary { get; set; }
}
}

View File

@@ -0,0 +1,157 @@
using AutoMapper;
using Microsoft.EntityFrameworkCore;
using Npgsql;
using TheBlacksmithVakulaContract.DataModels;
using TheBlacksmithVakulaContract.Exceptions;
using TheBlacksmithVakulaContract.StoragesContracts;
using TheBlacksmithVakulaDatabase.Models;
namespace TheBlacksmithVakulaDatabase.Implementations
{
internal class BilletStorageContract : IBilletStorageContract
{
private readonly TheBlacksmithVakulaDbContext _dbContext;
private readonly Mapper _mapper;
public BilletStorageContract(TheBlacksmithVakulaDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Billet, BilletDataModel>();
cfg.CreateMap<BilletDataModel, Billet>();
});
_mapper = new Mapper(config);
}
public List<BilletDataModel> GetList()
{
try
{
return [.. _dbContext.Billets.Select(x => _mapper.Map<BilletDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public BilletDataModel? GetElementById(string id)
{
try
{
return _mapper.Map<BilletDataModel>(GetBilletById(id));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public BilletDataModel? GetElementByName(string name)
{
try
{
return _mapper.Map<BilletDataModel>(_dbContext.Billets.FirstOrDefault(x => x.BilletName == name));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public BilletDataModel? GetElementByOldName(string name)
{
try
{
return _mapper.Map<BilletDataModel>(_dbContext.Billets
.FirstOrDefault(x => x.PrevBilletName == name || x.PrevPrevBilletName == name));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void AddElement(BilletDataModel billetDataModel)
{
try
{
_dbContext.Billets.Add(_mapper.Map<Billet>(billetDataModel));
_dbContext.SaveChanges();
}
catch (InvalidOperationException ex) when (ex.TargetSite?.Name == "ThrowIdentityConflict")
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("Id", billetDataModel.Id);
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Billets_BilletName" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("BilletName", billetDataModel.BilletName);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void UpdElement(BilletDataModel billetDataModel)
{
try
{
var element = GetBilletById(billetDataModel.Id) ?? throw new ElementNotFoundException(billetDataModel.Id);
if (element.BilletName != billetDataModel.BilletName)
{
element.PrevPrevBilletName = element.PrevBilletName;
element.PrevBilletName = element.BilletName;
element.BilletName = billetDataModel.BilletName;
}
_dbContext.Billets.Update(element);
_dbContext.SaveChanges();
}
catch (ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Billets_BilletName" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("BilletName", billetDataModel.BilletName);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void DelElement(string id)
{
try
{
var element = GetBilletById(id) ?? throw new ElementNotFoundException(id);
_dbContext.Billets.Remove(element);
_dbContext.SaveChanges();
}
catch (ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
private Billet? GetBilletById(string id) => _dbContext.Billets.FirstOrDefault(x => x.Id == id);
}
}

View File

@@ -0,0 +1,150 @@
using AutoMapper;
using TheBlacksmithVakulaContract.DataModels;
using TheBlacksmithVakulaContract.Exceptions;
using TheBlacksmithVakulaContract.StoragesContracts;
using TheBlacksmithVakulaDatabase.Models;
namespace TheBlacksmithVakulaDatabase.Implementations;
internal class BlacksmithStorageContract : IBlacksmithStorageContract
{
private readonly TheBlacksmithVakulaDbContext _dbContext;
private readonly Mapper _mapper;
public BlacksmithStorageContract(TheBlacksmithVakulaDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Rank, RankDataModel>()
.ForMember(x => x.Id, x => x.MapFrom(src => src.RankId));
cfg.CreateMap<Blacksmith, BlacksmithDataModel>();
cfg.CreateMap<BlacksmithDataModel, Blacksmith>();
});
_mapper = new Mapper(config);
}
public List<BlacksmithDataModel> GetList(bool onlyActive = true, string? rankId = null, DateTime? fromBirthDate = null, DateTime? toBirthDate = null, DateTime? fromEmploymentDate = null, DateTime? toEmploymentDate = null)
{
try
{
var query = _dbContext.Blacksmiths.AsQueryable();
if (onlyActive)
{
query = query.Where(x => !x.IsDeleted);
}
if (rankId is not null)
{
query = query.Where(x => x.RankId == rankId);
}
if (fromBirthDate is not null && toBirthDate is not null)
{
query = query.Where(x => x.BirthDate >= fromBirthDate && x.BirthDate <= toBirthDate);
}
if (fromEmploymentDate is not null && toEmploymentDate is not null)
{
query = query.Where(x => x.EmploymentDate >= fromEmploymentDate && x.EmploymentDate <= toEmploymentDate);
}
return [.. JoinRank(query).Select(x => _mapper.Map<BlacksmithDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public BlacksmithDataModel? GetElementById(string id)
{
try
{
return _mapper.Map<BlacksmithDataModel>(GetBlacksmithById(id));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public BlacksmithDataModel? GetElementByFIO(string fio)
{
try
{
return _mapper.Map<BlacksmithDataModel>(AddPost(_dbContext.Blacksmiths.FirstOrDefault(x => x.FIO == fio && !x.IsDeleted)));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void AddElement(BlacksmithDataModel blacksmithDataModel)
{
try
{
_dbContext.Blacksmiths.Add(_mapper.Map<Blacksmith>(blacksmithDataModel));
_dbContext.SaveChanges();
}
catch (InvalidOperationException ex) when (ex.TargetSite?.Name == "ThrowIdentityConflict")
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("Id", blacksmithDataModel.Id);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void UpdElement(BlacksmithDataModel blacksmithDataModel)
{
try
{
var element = GetBlacksmithById(blacksmithDataModel.Id) ?? throw new ElementNotFoundException(blacksmithDataModel.Id);
_dbContext.Blacksmiths.Update(_mapper.Map(blacksmithDataModel, 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 = GetBlacksmithById(id) ?? throw new ElementNotFoundException(id);
element.IsDeleted = true;
_dbContext.SaveChanges();
}
catch (ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
private Blacksmith? GetBlacksmithById(string id) => AddPost(_dbContext.Blacksmiths.FirstOrDefault(x => x.Id == id && !x.IsDeleted));
private IQueryable<Blacksmith> JoinRank(IQueryable<Blacksmith> query)
=> query.GroupJoin(_dbContext.Ranks.Where(x => x.IsActual), x => x.RankId, y => y.RankId, (x, y) => new { Blacksmith = x, Rank = y })
.SelectMany(xy => xy.Rank.DefaultIfEmpty(), (x, y) => x.Blacksmith.AddRank(y));
private Blacksmith? AddPost(Blacksmith? blacksmith)
=> blacksmith?.AddRank(_dbContext.Ranks.FirstOrDefault(x => x.RankId == blacksmith.RankId && x.IsActual));
}

View File

@@ -0,0 +1,150 @@
using AutoMapper;
using Microsoft.EntityFrameworkCore;
using Npgsql;
using TheBlacksmithVakulaContract.DataModels;
using TheBlacksmithVakulaContract.Exceptions;
using TheBlacksmithVakulaContract.StoragesContracts;
using TheBlacksmithVakulaDatabase.Models;
namespace TheBlacksmithVakulaDatabase.Implementations
{
internal class BuyerStorageContract : IBuyerStorageContract
{
private readonly TheBlacksmithVakulaDbContext _dbContext;
private readonly Mapper _mapper;
public BuyerStorageContract(TheBlacksmithVakulaDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Buyer, BuyerDataModel>();
cfg.CreateMap<BuyerDataModel, Buyer>();
});
_mapper = new Mapper(config);
}
public List<BuyerDataModel> GetList()
{
try
{
return [.. _dbContext.Buyers.Select(x => _mapper.Map<BuyerDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public BuyerDataModel? GetElementById(string id)
{
try
{
return _mapper.Map<BuyerDataModel>(GetBuyerById(id));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public BuyerDataModel? GetElementByFIO(string fio)
{
try
{
return _mapper.Map<BuyerDataModel>(_dbContext.Buyers.FirstOrDefault(x => x.FIO == fio));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public BuyerDataModel? GetElementByPhoneNumber(string phoneNumber)
{
try
{
return _mapper.Map<BuyerDataModel>(_dbContext.Buyers.FirstOrDefault(x => x.PhoneNumber == phoneNumber));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void AddElement(BuyerDataModel buyerDataModel)
{
try
{
_dbContext.Buyers.Add(_mapper.Map<Buyer>(buyerDataModel));
_dbContext.SaveChanges();
}
catch (InvalidOperationException ex) when (ex.TargetSite?.Name == "ThrowIdentityConflict")
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("Id", buyerDataModel.Id);
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Buyers_PhoneNumber" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("PhoneNumber", buyerDataModel.PhoneNumber);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void UpdElement(BuyerDataModel buyerDataModel)
{
try
{
var element = GetBuyerById(buyerDataModel.Id) ?? throw new ElementNotFoundException(buyerDataModel.Id);
_dbContext.Buyers.Update(_mapper.Map(buyerDataModel, element));
_dbContext.SaveChanges();
}
catch (ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Buyers_PhoneNumber" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("PhoneNumber", buyerDataModel.PhoneNumber);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void DelElement(string id)
{
try
{
var element = GetBuyerById(id) ?? throw new ElementNotFoundException(id);
_dbContext.Buyers.Remove(element);
_dbContext.SaveChanges();
}
catch (ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
private Buyer? GetBuyerById(string id) => _dbContext.Buyers.FirstOrDefault(x => x.Id == id);
}
}

View File

@@ -0,0 +1,117 @@
using AutoMapper;
using Microsoft.EntityFrameworkCore;
using TheBlacksmithVakulaContract.DataModels;
using TheBlacksmithVakulaContract.Exceptions;
using TheBlacksmithVakulaContract.StoragesContracts;
using TheBlacksmithVakulaDatabase.Models;
namespace TheBlacksmithVakulaDatabase.Implementations;
internal class OrderStorageContract : IOrderStorageContract
{
private readonly TheBlacksmithVakulaDbContext _dbContext;
private readonly Mapper _mapper;
public OrderStorageContract(TheBlacksmithVakulaDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Billet, BilletDataModel>();
cfg.CreateMap<Buyer, BuyerDataModel>();
cfg.CreateMap<Product, ProductDataModel>();
cfg.CreateMap<Blacksmith, BlacksmithDataModel>();
cfg.CreateMap<OrderProduct, OrderProductDataModel>();
cfg.CreateMap<OrderProductDataModel, OrderProduct>();
cfg.CreateMap<Order, OrderDataModel>();
cfg.CreateMap<OrderDataModel, Order>()
.ForMember(x => x.IsCancel, x => x.MapFrom(src => false))
.ForMember(x => x.OrderProducts, x => x.MapFrom(src => src.Products));
});
_mapper = new Mapper(config);
}
public List<OrderDataModel> GetList(DateTime? startDate = null, DateTime? endDate = null, string? blacksmithId = null, string? buyerId = null, string? productId = null)
{
try
{
var query = _dbContext.Orders.Include(x => x.Buyer).Include(x => x.Blacksmith).Include(x => x.OrderProducts)!.ThenInclude(x => x.Product).AsQueryable();
if (startDate is not null && endDate is not null)
{
query = query.Where(x => x.OrderDate >= startDate && x.OrderDate < endDate);
}
if (blacksmithId is not null)
{
query = query.Where(x => x.BlacksmithId == blacksmithId);
}
if (buyerId is not null)
{
query = query.Where(x => x.BuyerId == buyerId);
}
if (productId is not null)
{
query = query.Where(x => x.OrderProducts!.Any(y => y.ProductId == productId));
}
return [.. query.Select(x => _mapper.Map<OrderDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public OrderDataModel? GetElementById(string id)
{
try
{
return _mapper.Map<OrderDataModel>(GetOrderById(id));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void AddElement(OrderDataModel orderDataModel)
{
try
{
_dbContext.Orders.Add(_mapper.Map<Order>(orderDataModel));
_dbContext.SaveChanges();
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void DelElement(string id)
{
try
{
var element = GetOrderById(id) ?? throw new ElementNotFoundException(id);
if (element.IsCancel)
{
throw new ElementDeletedException(id);
}
element.IsCancel = true;
_dbContext.SaveChanges();
}
catch (Exception ex) when (ex is ElementDeletedException || ex is ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
private Order? GetOrderById(string id) => _dbContext.Orders.Include(x => x.Buyer).Include(x => x.Blacksmith)
.Include(x => x.OrderProducts)!.ThenInclude(x => x.Product).FirstOrDefault(x => x.Id == id);
}

View File

@@ -0,0 +1,176 @@
using AutoMapper;
using Microsoft.EntityFrameworkCore;
using Npgsql;
using TheBlacksmithVakulaContract.DataModels;
using TheBlacksmithVakulaContract.Exceptions;
using TheBlacksmithVakulaContract.StoragesContracts;
using TheBlacksmithVakulaDatabase.Models;
namespace TheBlacksmithVakulaDatabase.Implementations;
internal class ProductStorageContract : IProductStorageContract
{
private readonly TheBlacksmithVakulaDbContext _dbContext;
private readonly Mapper _mapper;
public ProductStorageContract(TheBlacksmithVakulaDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Billet, BilletDataModel>();
cfg.CreateMap<Product, ProductDataModel>();
cfg.CreateMap<ProductDataModel, Product>()
.ForMember(x => x.IsDeleted, x => x.MapFrom(src => false));
cfg.CreateMap<ProductHistory, ProductHistoryDataModel>();
});
_mapper = new Mapper(config);
}
public List<ProductDataModel> GetList(bool onlyActive = true, string? billetId = null)
{
try
{
var query = _dbContext.Products.Include(x => x.Billet).AsQueryable();
if (onlyActive)
{
query = query.Where(x => !x.IsDeleted);
}
if (billetId is not null)
{
query = query.Where(x => x.BilletId == billetId);
}
return [.. query.Select(x => _mapper.Map<ProductDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public List<ProductHistoryDataModel> GetHistoryByProductId(string productId)
{
try
{
return [.. _dbContext.ProductHistories.Include(x => x.Product).Where(x => x.ProductId == productId).OrderByDescending(x => x.ChangeDate).Select(x => _mapper.Map<ProductHistoryDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public ProductDataModel? GetElementById(string id)
{
try
{
return _mapper.Map<ProductDataModel>(GetProductById(id));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public ProductDataModel? GetElementByName(string name)
{
try
{
return _mapper.Map<ProductDataModel>(_dbContext.Products.Include(x => x.Billet).FirstOrDefault(x => x.ProductName == name && !x.IsDeleted));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void AddElement(ProductDataModel productDataModel)
{
try
{
_dbContext.Products.Add(_mapper.Map<Product>(productDataModel));
_dbContext.SaveChanges();
}
catch (InvalidOperationException ex) when (ex.TargetSite?.Name == "ThrowIdentityConflict")
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("Id", productDataModel.Id);
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Products_ProductName_IsDeleted" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("ProductName", productDataModel.ProductName);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void UpdElement(ProductDataModel productDataModel)
{
try
{
var transaction = _dbContext.Database.BeginTransaction();
try
{
var element = GetProductById(productDataModel.Id) ?? throw new ElementNotFoundException(productDataModel.Id);
if (element.Price != productDataModel.Price)
{
_dbContext.ProductHistories.Add(new ProductHistory() { ProductId = element.Id, OldPrice = element.Price });
_dbContext.SaveChanges();
}
_dbContext.Products.Update(_mapper.Map(productDataModel, element));
_dbContext.SaveChanges();
transaction.Commit();
}
catch
{
transaction.Rollback();
throw;
}
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Products_ProductName_IsDeleted" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("ProductName", productDataModel.ProductName);
}
catch (Exception ex) when (ex is ElementDeletedException || ex is ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void DelElement(string id)
{
try
{
var element = GetProductById(id) ?? throw new ElementNotFoundException(id);
element.IsDeleted = true;
_dbContext.SaveChanges();
}
catch (ElementNotFoundException ex)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
private Product? GetProductById(string id) => _dbContext.Products.Include(x => x.Billet).FirstOrDefault(x => x.Id == id && !x.IsDeleted);
}

View File

@@ -0,0 +1,181 @@
using AutoMapper;
using Microsoft.EntityFrameworkCore;
using Npgsql;
using TheBlacksmithVakulaContract.DataModels;
using TheBlacksmithVakulaContract.Exceptions;
using TheBlacksmithVakulaContract.StoragesContracts;
using TheBlacksmithVakulaDatabase.Models;
namespace TheBlacksmithVakulaDatabase.Implementations
{
internal class RankStorageContract : IRankStorageContract
{
private readonly TheBlacksmithVakulaDbContext _dbContext;
private readonly Mapper _mapper;
public RankStorageContract(TheBlacksmithVakulaDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Rank, RankDataModel>()
.ForMember(x => x.Id, x => x.MapFrom(src => src.RankId));
cfg.CreateMap<RankDataModel, Rank>()
.ForMember(x => x.Id, x => x.Ignore())
.ForMember(x => x.RankId, x => x.MapFrom(src => src.Id))
.ForMember(x => x.IsActual, x => x.MapFrom(src => true))
.ForMember(x => x.ChangeDate, x => x.MapFrom(src => DateTime.UtcNow));
});
_mapper = new Mapper(config);
}
public List<RankDataModel> GetList()
{
try
{
return [.._dbContext.Ranks.Select(x => _mapper.Map<RankDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public List<RankDataModel> GetRankWithHistory(string postId)
{
try
{
return [.. _dbContext.Ranks.Where(x => x.RankId == postId).Select(x => _mapper.Map<RankDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public RankDataModel? GetElementById(string id)
{
try
{
return _mapper.Map<RankDataModel>(_dbContext.Ranks.FirstOrDefault(x => x.RankId == id && x.IsActual));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public RankDataModel? GetElementByName(string name)
{
try
{
return _mapper.Map<RankDataModel>(_dbContext.Ranks.FirstOrDefault(x => x.RankName == name && x.IsActual));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void AddElement(RankDataModel postDataModel)
{
try
{
_dbContext.Ranks.Add(_mapper.Map<Rank>(postDataModel));
_dbContext.SaveChanges();
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Ranks_RankName_IsActual" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("RankName", postDataModel.RankName);
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Ranks_RankId_IsActual" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("RankId", postDataModel.Id);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void UpdElement(RankDataModel postDataModel)
{
try
{
var transaction = _dbContext.Database.BeginTransaction();
try
{
var element = GetRankById(postDataModel.Id) ?? throw new ElementNotFoundException(postDataModel.Id);
if (!element.IsActual) throw new ElementDeletedException(postDataModel.Id);
element.IsActual = false;
_dbContext.SaveChanges();
var newElement = _mapper.Map<Rank>(postDataModel);
_dbContext.Ranks.Add(newElement);
_dbContext.SaveChanges();
transaction.Commit();
}
catch
{
transaction.Rollback();
throw;
}
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Ranks_RankName_IsActual" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("RankName", postDataModel.RankName);
}
catch (Exception ex) when (ex is ElementDeletedException || ex is ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void DelElement(string id)
{
try
{
var element = GetRankById(id) ?? throw new ElementNotFoundException(id);
if (!element.IsActual) throw new ElementDeletedException(id);
element.IsActual = false;
_dbContext.SaveChanges();
}
catch
{
_dbContext.ChangeTracker.Clear();
throw;
}
}
public void ResElement(string id)
{
try
{
var element = GetRankById(id) ?? throw new
ElementNotFoundException(id);
element.IsActual = true;
_dbContext.SaveChanges();
}
catch
{
_dbContext.ChangeTracker.Clear();
throw;
}
}
private Rank? GetRankById(string id) => _dbContext.Ranks.Where(x => x.RankId == id)
.OrderByDescending(x => x.ChangeDate).FirstOrDefault();
}
}

View File

@@ -0,0 +1,59 @@
using AutoMapper;
using Microsoft.EntityFrameworkCore;
using TheBlacksmithVakulaContract.DataModels;
using TheBlacksmithVakulaContract.Exceptions;
using TheBlacksmithVakulaContract.StoragesContracts;
using TheBlacksmithVakulaDatabase.Models;
namespace TheBlacksmithVakulaDatabase.Implementations;
internal class SalaryStorageContract : ISalaryStorageContract
{
private readonly TheBlacksmithVakulaDbContext _dbContext;
private readonly Mapper _mapper;
public SalaryStorageContract(TheBlacksmithVakulaDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Blacksmith, BlacksmithDataModel>();
cfg.CreateMap<Salary, SalaryDataModel>();
cfg.CreateMap<SalaryDataModel, Salary>()
.ForMember(dest => dest.BlacksmithSalary, opt => opt.MapFrom(src => src.Salary));
});
_mapper = new Mapper(config);
}
public List<SalaryDataModel> GetList(DateTime startDate, DateTime endDate, string? blacksmithId = null)
{
try
{
var query = _dbContext.Salaries.Include(x => x.Blacksmith).Where(x => x.SalaryDate >= startDate && x.SalaryDate <= endDate);
if (blacksmithId is not null)
{
query = query.Where(x => x.BlacksmithId == blacksmithId);
}
return [.. query.Select(x => _mapper.Map<SalaryDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void AddElement(SalaryDataModel salaryDataModel)
{
try
{
_dbContext.Salaries.Add(_mapper.Map<Salary>(salaryDataModel));
_dbContext.SaveChanges();
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
}

View File

@@ -0,0 +1,18 @@
using System.ComponentModel.DataAnnotations.Schema;
namespace TheBlacksmithVakulaDatabase.Models
{
internal class Billet
{
public required string Id { get; set; }
public required string BilletName { get; set; }
public string? PrevBilletName { get; set; }
public string? PrevPrevBilletName { get; set; }
[ForeignKey("BilletId")]
public List<Product>? Products { get; set; }
}
}

View File

@@ -0,0 +1,34 @@
using System.ComponentModel.DataAnnotations.Schema;
namespace TheBlacksmithVakulaDatabase.Models
{
internal class Blacksmith
{
public required string Id { get; set; }
public required string FIO { get; set; }
public required string RankId { get; set; }
public DateTime BirthDate { get; set; }
public DateTime EmploymentDate { get; set; }
public bool IsDeleted { get; set; }
[NotMapped]
public Rank? Rank { get; set; }
[ForeignKey("BlacksmithId")]
public List<Order>? Orders { get; set; }
[ForeignKey("BlacksmithId")]
public List<Salary>? Salaries { get; set; }
public Blacksmith AddRank(Rank? rank)
{
Rank = rank;
return this;
}
}
}

View File

@@ -0,0 +1,18 @@
using System.ComponentModel.DataAnnotations.Schema;
namespace TheBlacksmithVakulaDatabase.Models
{
internal class Buyer
{
public required string Id { get; set; }
public required string FIO { get; set; }
public required string PhoneNumber { get; set; }
public double DiscountSize { get; set; }
[ForeignKey("BuyerId")]
public List<Order>? Orders { get; set; }
}
}

View File

@@ -0,0 +1,31 @@
using System.ComponentModel.DataAnnotations.Schema;
using TheBlacksmithVakulaContract.Enums;
namespace TheBlacksmithVakulaDatabase.Models
{
internal class Order
{
public string Id { get; set; } = Guid.NewGuid().ToString();
public required string BlacksmithId { get; set; }
public string? BuyerId { get; set; }
public DateTime OrderDate { get; set; } = DateTime.UtcNow;
public double Sum { get; set; }
public DiscountType DiscountType { get; set; }
public double Discount { get; set; }
public bool IsCancel { get; set; }
public Blacksmith? Blacksmith { get; set; }
public Buyer? Buyer { get; set; }
[ForeignKey("OrderId")]
public List<OrderProduct>? OrderProducts { get; set; }
}
}

View File

@@ -0,0 +1,15 @@
namespace TheBlacksmithVakulaDatabase.Models
{
internal class OrderProduct
{
public required string OrderId { get; set; }
public required string ProductId { get; set; }
public int Count { get; set; }
public Order? Order { get; set; }
public Product? Product { get; set; }
}
}

View File

@@ -0,0 +1,28 @@
using System.ComponentModel.DataAnnotations.Schema;
using TheBlacksmithVakulaContract.Enums;
namespace TheBlacksmithVakulaDatabase.Models
{
internal class Product
{
public required string Id { get; set; }
public required string ProductName { get; set; }
public ProductType ProductType { get; set; }
public required string BilletId { get; set; }
public double Price { get; set; }
public bool IsDeleted { get; set; }
public Billet? Billet { get; set; }
[ForeignKey("ProductId")]
public List<ProductHistory>? ProductHistories { get; set; }
[ForeignKey("ProductId")]
public List<OrderProduct>? OrderProducts { get; set; }
}
}

View File

@@ -0,0 +1,15 @@
namespace TheBlacksmithVakulaDatabase.Models
{
internal class ProductHistory
{
public string Id { get; set; } = Guid.NewGuid().ToString();
public required string ProductId { get; set; }
public double OldPrice { get; set; }
public DateTime ChangeDate { get; set; } = DateTime.UtcNow;
public Product? Product { get; set; }
}
}

View File

@@ -0,0 +1,19 @@
using TheBlacksmithVakulaContract.Enums;
namespace TheBlacksmithVakulaDatabase.Models
{
internal class Rank
{
public string Id { get; set; } = Guid.NewGuid().ToString();
public required string RankId { get; set; }
public required string RankName { get; set; }
public RankType RankType { get; set; }
public bool IsActual { get; set; }
public DateTime ChangeDate { get; set; }
}
}

View File

@@ -0,0 +1,21 @@
using AutoMapper;
using AutoMapper.Configuration.Annotations;
using TheBlacksmithVakulaContract.DataModels;
namespace TheBlacksmithVakulaDatabase.Models
{
[AutoMap(typeof(SalaryDataModel), ReverseMap = true)]
internal class Salary
{
public string Id { get; set; } = Guid.NewGuid().ToString();
public required string BlacksmithId { get; set; }
public DateTime SalaryDate { get; set; }
[SourceMember("Salary")]
public double BlacksmithSalary { get; set; }
public Blacksmith? Blacksmith { get; set; }
}
}

View File

@@ -0,0 +1,26 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="AutoMapper" Version="14.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="9.0.4" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="9.0.4" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="9.0.4" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\TheBlacksmithVakulaContract\TheBlacksmithVakulaContract.csproj" />
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="TheBlacksmithVakulaTests" />
<InternalsVisibleTo Include="TheBlacksmithVakulaWebApi" />
<InternalsVisibleTo Include="DinamicProxyGenAssembly2" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,80 @@
using Microsoft.EntityFrameworkCore;
using TheBlacksmithVakulaContract.Infrastructure;
using TheBlacksmithVakulaDatabase.Models;
namespace TheBlacksmithVakulaDatabase
{
internal class TheBlacksmithVakulaDbContext : DbContext
{
private readonly IConfigurationDatabase? _configurationDatabase;
public TheBlacksmithVakulaDbContext(IConfigurationDatabase configurationDatabase)
{
_configurationDatabase = configurationDatabase;
AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true);
AppContext.SetSwitch("Npgsql.DisableDateTimeInfinityConversions", true);
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseNpgsql(_configurationDatabase?.ConnectionString, o => o.SetPostgresVersion(16, 2));
base.OnConfiguring(optionsBuilder);
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Buyer>().HasIndex(x => x.PhoneNumber).IsUnique();
modelBuilder.Entity<Order>()
.HasOne(e => e.Buyer)
.WithMany(e => e.Orders)
.OnDelete(DeleteBehavior.SetNull);
modelBuilder.Entity<Billet>().HasIndex(x => x.BilletName).IsUnique();
modelBuilder.Entity<Rank>()
.HasIndex(e => new { e.RankName, e.IsActual })
.IsUnique()
.HasFilter($"\"{nameof(Rank.IsActual)}\" = TRUE");
modelBuilder.Entity<Rank>()
.HasIndex(e => new { e.RankId, e.IsActual })
.IsUnique()
.HasFilter($"\"{nameof(Rank.IsActual)}\" = TRUE");
modelBuilder.Entity<Product>()
.HasIndex(x => new { x.ProductName, x.IsDeleted })
.IsUnique()
.HasFilter($"\"{nameof(Product.IsDeleted)}\" = FALSE");
modelBuilder.Entity<Product>()
.HasOne(e => e.Billet)
.WithMany(e => e.Products)
.OnDelete(DeleteBehavior.Restrict);
modelBuilder.Entity<OrderProduct>()
.HasKey(x => new { x.OrderId, x.ProductId });
}
public DbSet<Buyer> Buyers { get; set; }
public DbSet<Billet> Billets { get; set; }
public DbSet<Rank> Ranks { get; set; }
public DbSet<Product> Products { get; set; }
public DbSet<ProductHistory> ProductHistories { get; set; }
public DbSet<Salary> Salaries { get; set; }
public DbSet<Order> Orders { get; set; }
public DbSet<OrderProduct> OrderProducts { get; set; }
public DbSet<Blacksmith> Blacksmiths { get; set; }
}
}

View File

@@ -0,0 +1,369 @@
using TheBlacksmithVakulaBusinessLogic.Implementations;
using TheBlacksmithVakulaContract.BusinessLogicsContracts;
using TheBlacksmithVakulaContract.DataModels;
using TheBlacksmithVakulaContract.Exceptions;
using TheBlacksmithVakulaContract.StoragesContracts;
using Microsoft.Extensions.Logging;
using Moq;
namespace TheBlacksmithVakulaTests.BusinessLogicContractTests
{
[TestFixture]
public class BilletBusinessLogicContractTests
{
private IBilletBusinessLogicContract _billetBusinessLogicContract;
private Mock<IBilletStorageContract> _billetStorageContract;
[OneTimeSetUp]
public void OneTimeSetUp()
{
_billetStorageContract = new Mock<IBilletStorageContract>();
_billetBusinessLogicContract = new BilletBusinessLogicContract(_billetStorageContract.Object, new Mock<ILogger>().Object);
}
[SetUp]
public void SetUp()
{
_billetStorageContract.Reset();
}
[Test]
public void GetAllBillets_ReturnListOfRecords_Test()
{
//Arrange
var listOriginal = new List<BilletDataModel>()
{
new(Guid.NewGuid().ToString(), "name 1", null, null),
new(Guid.NewGuid().ToString(), "name 2", null, null),
new(Guid.NewGuid().ToString(), "name 3", null, null),
};
_billetStorageContract.Setup(x => x.GetList()).Returns(listOriginal);
//Act
var list = _billetBusinessLogicContract.GetAllBillets();
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.EquivalentTo(listOriginal));
}
[Test]
public void GetAllBillets_ReturnEmptyList_Test()
{
//Arrange
_billetStorageContract.Setup(x => x.GetList()).Returns([]);
//Act
var list = _billetBusinessLogicContract.GetAllBillets();
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
_billetStorageContract.Verify(x => x.GetList(), Times.Once);
}
[Test]
public void GetAllBillets_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _billetBusinessLogicContract.GetAllBillets(), Throws.TypeOf<NullListException>());
_billetStorageContract.Verify(x => x.GetList(), Times.Once);
}
[Test]
public void GetAllBillets_StorageThrowError_ThrowException_Test()
{
//Arrange
_billetStorageContract.Setup(x => x.GetList()).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _billetBusinessLogicContract.GetAllBillets(), Throws.TypeOf<StorageException>());
_billetStorageContract.Verify(x => x.GetList(), Times.Once);
}
[Test]
public void GetBilletByData_GetById_ReturnRecord_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
var record = new BilletDataModel(id, "name", null, null);
_billetStorageContract.Setup(x => x.GetElementById(id)).Returns(record);
//Act
var element = _billetBusinessLogicContract.GetBilletByData(id);
//Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.Id, Is.EqualTo(id));
_billetStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetBilletByData_GetByName_ReturnRecord_Test()
{
//Arrange
var billetName = "name";
var record = new BilletDataModel(Guid.NewGuid().ToString(), billetName, null, null);
_billetStorageContract.Setup(x => x.GetElementByName(billetName)).Returns(record);
//Act
var element = _billetBusinessLogicContract.GetBilletByData(billetName);
//Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.BilletName, Is.EqualTo(billetName));
_billetStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetBilletByData_GetByOldName_ReturnRecord_Test()
{
//Arrange
var billetOldName = "name before";
var record = new BilletDataModel(Guid.NewGuid().ToString(), "name", billetOldName, null);
_billetStorageContract.Setup(x => x.GetElementByOldName(billetOldName)).Returns(record);
//Act
var element = _billetBusinessLogicContract.GetBilletByData(billetOldName);
//Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.PrevBilletName, Is.EqualTo(billetOldName));
_billetStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Once);
_billetStorageContract.Verify(x => x.GetElementByOldName(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetBilletByData_EmptyData_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _billetBusinessLogicContract.GetBilletByData(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _billetBusinessLogicContract.GetBilletByData(string.Empty), Throws.TypeOf<ArgumentNullException>());
_billetStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Never);
_billetStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Never);
_billetStorageContract.Verify(x => x.GetElementByOldName(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetBilletByData__GetById_NotFoundRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _billetBusinessLogicContract.GetBilletByData(Guid.NewGuid().ToString()),
Throws.TypeOf<ElementNotFoundException>());
_billetStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
_billetStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Never);
_billetStorageContract.Verify(x => x.GetElementByOldName(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetBilletByData_GetByNameOrOldName_NotFoundRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _billetBusinessLogicContract.GetBilletByData("name"), Throws.TypeOf<ElementNotFoundException>());
_billetStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Never);
_billetStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Once);
_billetStorageContract.Verify(x => x.GetElementByOldName(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetBilletByData_StorageThrowError_ThrowException_Test()
{
//Arrange
_billetStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Throws(new StorageException(new InvalidOperationException()));
_billetStorageContract.Setup(x => x.GetElementByName(It.IsAny<string>()))
.Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _billetBusinessLogicContract.GetBilletByData(Guid.NewGuid().ToString()),
Throws.TypeOf<StorageException>());
Assert.That(() => _billetBusinessLogicContract.GetBilletByData("name"), Throws.TypeOf<StorageException>());
_billetStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
_billetStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Once);
_billetStorageContract.Verify(x => x.GetElementByOldName(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetBilletByData_GetByOldName_StorageThrowError_ThrowException_Test()
{
//Arrange
_billetStorageContract.Setup(x => x.GetElementByOldName(It.IsAny<string>()))
.Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _billetBusinessLogicContract.GetBilletByData("name"), Throws.TypeOf<StorageException>());
_billetStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Once);
_billetStorageContract.Verify(x => x.GetElementByOldName(It.IsAny<string>()), Times.Once);
}
[Test]
public void InsertBillet_CorrectRecord_Test()
{
//Arrange
var flag = false;
var record = new BilletDataModel(Guid.NewGuid().ToString(), "name", null, null);
_billetStorageContract.Setup(x => x.AddElement(It.IsAny<BilletDataModel>()))
.Callback((BilletDataModel x) =>
{
flag = x.Id == record.Id && x.BilletName == record.BilletName;
});
//Act
_billetBusinessLogicContract.InsertBillet(record);
//Assert
_billetStorageContract.Verify(x => x.AddElement(It.IsAny<BilletDataModel>()), Times.Once);
Assert.That(flag);
}
[Test]
public void InsertBillet_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_billetStorageContract.Setup(x => x.AddElement(It.IsAny<BilletDataModel>()))
.Throws(new ElementExistsException("Data", "Data"));
//Act&Assert
Assert.That(() => _billetBusinessLogicContract.InsertBillet(new(Guid.NewGuid().ToString(), "name", null, null)),
Throws.TypeOf<ElementExistsException>());
_billetStorageContract.Verify(x => x.AddElement(It.IsAny<BilletDataModel>()), Times.Once);
}
[Test]
public void InsertBillet_NullRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _billetBusinessLogicContract.InsertBillet(null), Throws.TypeOf<ArgumentNullException>());
_billetStorageContract.Verify(x => x.AddElement(It.IsAny<BilletDataModel>()), Times.Never);
}
[Test]
public void InsertBillet_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _billetBusinessLogicContract.InsertBillet(new BilletDataModel("id", "name", null, null)),
Throws.TypeOf<ValidationException>());
_billetStorageContract.Verify(x => x.AddElement(It.IsAny<BilletDataModel>()), Times.Never);
}
[Test]
public void InsertBillet_StorageThrowError_ThrowException_Test()
{
//Arrange
_billetStorageContract.Setup(x => x.AddElement(It.IsAny<BilletDataModel>()))
.Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _billetBusinessLogicContract.InsertBillet(new(Guid.NewGuid().ToString(), "name", null, null)),
Throws.TypeOf<StorageException>());
_billetStorageContract.Verify(x => x.AddElement(It.IsAny<BilletDataModel>()), Times.Once);
}
[Test]
public void UpdateBillet_CorrectRecord_Test()
{
//Arrange
var flag = false;
var record = new BilletDataModel(Guid.NewGuid().ToString(), "name", null, null);
_billetStorageContract.Setup(x => x.UpdElement(It.IsAny<BilletDataModel>()))
.Callback((BilletDataModel x) =>
{
flag = x.Id == record.Id && x.BilletName == record.BilletName;
});
//Act
_billetBusinessLogicContract.UpdateBillet(record);
//Assert
_billetStorageContract.Verify(x => x.UpdElement(It.IsAny<BilletDataModel>()), Times.Once);
Assert.That(flag);
}
[Test]
public void UpdateBillet_RecordWithIncorrectData_ThrowException_Test()
{
//Arrange
_billetStorageContract.Setup(x => x.UpdElement(It.IsAny<BilletDataModel>())).Throws(new ElementNotFoundException(""));
//Act&Assert
Assert.That(() => _billetBusinessLogicContract.UpdateBillet(new(Guid.NewGuid().ToString(), "name", null, null)),
Throws.TypeOf<ElementNotFoundException>());
_billetStorageContract.Verify(x => x.UpdElement(It.IsAny<BilletDataModel>()), Times.Once);
}
[Test]
public void UpdateBillet_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_billetStorageContract.Setup(x => x.UpdElement(It.IsAny<BilletDataModel>()))
.Throws(new ElementExistsException("Data", "Data"));
//Act&Assert
Assert.That(() => _billetBusinessLogicContract.UpdateBillet(new(Guid.NewGuid().ToString(), "name", null, null)),
Throws.TypeOf<ElementExistsException>());
_billetStorageContract.Verify(x => x.UpdElement(It.IsAny<BilletDataModel>()), Times.Once);
}
[Test]
public void UpdateBillet_NullRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _billetBusinessLogicContract.UpdateBillet(null), Throws.TypeOf<ArgumentNullException>());
_billetStorageContract.Verify(x => x.UpdElement(It.IsAny<BilletDataModel>()), Times.Never);
}
[Test]
public void UpdateBillet_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _billetBusinessLogicContract.UpdateBillet(new BilletDataModel("id", "name", null, null)),
Throws.TypeOf<ValidationException>());
_billetStorageContract.Verify(x => x.UpdElement(It.IsAny<BilletDataModel>()), Times.Never);
}
[Test]
public void UpdateBillet_StorageThrowError_ThrowException_Test()
{
//Arrange
_billetStorageContract.Setup(x => x.UpdElement(It.IsAny<BilletDataModel>()))
.Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _billetBusinessLogicContract.UpdateBillet(new(Guid.NewGuid().ToString(), "name", null, null)),
Throws.TypeOf<StorageException>());
_billetStorageContract.Verify(x => x.UpdElement(It.IsAny<BilletDataModel>()), Times.Once);
}
[Test]
public void DeleteBillet_CorrectRecord_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
var flag = false;
_billetStorageContract.Setup(x => x.DelElement(It.Is((string x) => x == id))).Callback(() => { flag = true; });
//Act
_billetBusinessLogicContract.DeleteBillet(id);
//Assert
_billetStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
Assert.That(flag);
}
[Test]
public void DeleteBillet_RecordWithIncorrectId_ThrowException_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
_billetStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new ElementNotFoundException(id));
//Act&Assert
Assert.That(() => _billetBusinessLogicContract.DeleteBillet(Guid.NewGuid().ToString()),
Throws.TypeOf<ElementNotFoundException>());
_billetStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
}
[Test]
public void DeleteBillet_IdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _billetBusinessLogicContract.DeleteBillet(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _billetBusinessLogicContract.DeleteBillet(string.Empty), Throws.TypeOf<ArgumentNullException>());
_billetStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Never);
}
[Test]
public void DeleteBillet_IdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _billetBusinessLogicContract.DeleteBillet("id"), Throws.TypeOf<ValidationException>());
_billetStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Never);
}
[Test]
public void DeleteBillet_StorageThrowError_ThrowException_Test()
{
//Arrange
_billetStorageContract.Setup(x => x.DelElement(It.IsAny<string>()))
.Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _billetBusinessLogicContract.DeleteBillet(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_billetStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
}
}
}

View File

@@ -0,0 +1,653 @@
using TheBlacksmithVakulaBusinessLogic.Implementations;
using TheBlacksmithVakulaContract.BusinessLogicsContracts;
using TheBlacksmithVakulaContract.DataModels;
using TheBlacksmithVakulaContract.StoragesContracts;
using TheBlacksmithVakulaContract.Exceptions;
using Microsoft.Extensions.Logging;
using Moq;
namespace TheBlacksmithVakulaTests.BusinessLogicContractTests
{
[TestFixture]
public class BlacksmithBusinessLogicContractTests
{
private IBlacksmithBusinessLogicContract _blacksmithBusinessLogicContract;
private Mock<IBlacksmithStorageContract> _blacksmithStorageContract;
[OneTimeSetUp]
public void OneTimeSetUp()
{
_blacksmithStorageContract = new Mock<IBlacksmithStorageContract>();
_blacksmithBusinessLogicContract = new BlacksmithBusinessLogicContract(_blacksmithStorageContract.Object,
new Mock<ILogger>().Object);
}
[SetUp]
public void SetUp()
{
_blacksmithStorageContract.Reset();
}
[Test]
public void GetAllBlacksmith_ReturnListOfRecords_Test()
{
//Arrange
var listOriginal = new List<BlacksmithDataModel>()
{
new(Guid.NewGuid().ToString(), "fio 1", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1),
DateTime.Now, false),
new(Guid.NewGuid().ToString(), "fio 2", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1),
DateTime.Now, true),
new(Guid.NewGuid().ToString(), "fio 3", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1),
DateTime.Now, false),
};
_blacksmithStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Returns(listOriginal);
//Act
var listOnlyActive = _blacksmithBusinessLogicContract.GetAllBlacksmith(true);
var list = _blacksmithBusinessLogicContract.GetAllBlacksmith(false);
//Assert
Assert.Multiple(() =>
{
Assert.That(listOnlyActive, Is.Not.Null);
Assert.That(list, Is.Not.Null);
Assert.That(listOnlyActive, Is.EquivalentTo(listOriginal));
Assert.That(list, Is.EquivalentTo(listOriginal));
});
_blacksmithStorageContract.Verify(x => x.GetList(true, null, null, null, null, null), Times.Once);
_blacksmithStorageContract.Verify(x => x.GetList(false, null, null, null, null, null), Times.Once);
}
[Test]
public void GetAllBlacksmith_ReturnEmptyList_Test()
{
//Arrange
_blacksmithStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Returns([]);
//Act
var listOnlyActive = _blacksmithBusinessLogicContract.GetAllBlacksmith(true);
var list = _blacksmithBusinessLogicContract.GetAllBlacksmith(false);
//Assert
Assert.Multiple(() =>
{
Assert.That(listOnlyActive, Is.Not.Null);
Assert.That(list, Is.Not.Null);
Assert.That(listOnlyActive, Has.Count.EqualTo(0));
Assert.That(list, Has.Count.EqualTo(0));
});
_blacksmithStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), null, null, null, null, null), Times.Exactly(2));
}
[Test]
public void GetAllBlacksmith_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _blacksmithBusinessLogicContract.GetAllBlacksmith(It.IsAny<bool>()), Throws.TypeOf<NullListException>());
_blacksmithStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Once);
}
[Test]
public void GetAllBlacksmith_StorageThrowError_ThrowException_Test()
{
//Arrange
_blacksmithStorageContract.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
Assert.That(() => _blacksmithBusinessLogicContract.GetAllBlacksmith(It.IsAny<bool>()), Throws.TypeOf<StorageException>());
_blacksmithStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), null, null, null, null, null), Times.Once);
}
[Test]
public void GetAllBlacksmithByRank_ReturnListOfRecords_Test()
{
//Arrange
var rankId = Guid.NewGuid().ToString();
var listOriginal = new List<BlacksmithDataModel>()
{
new(Guid.NewGuid().ToString(), "fio 1", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1),
DateTime.Now, false),
new(Guid.NewGuid().ToString(), "fio 2", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1),
DateTime.Now, true),
new(Guid.NewGuid().ToString(), "fio 3", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1),
DateTime.Now, false)
};
_blacksmithStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Returns(listOriginal);
//Act
var listOnlyActive = _blacksmithBusinessLogicContract.GetAllBlacksmithByRank(rankId, true);
var list = _blacksmithBusinessLogicContract.GetAllBlacksmithByRank(rankId, false);
//Assert
Assert.Multiple(() =>
{
Assert.That(listOnlyActive, Is.Not.Null);
Assert.That(list, Is.Not.Null);
Assert.That(listOnlyActive, Is.EquivalentTo(listOriginal));
Assert.That(list, Is.EquivalentTo(listOriginal));
});
_blacksmithStorageContract.Verify(x => x.GetList(true, rankId, null, null, null, null), Times.Once);
_blacksmithStorageContract.Verify(x => x.GetList(false, rankId, null, null, null, null), Times.Once);
}
[Test]
public void GetAllBlacksmithByRank_ReturnEmptyList_Test()
{
//Arrange
_blacksmithStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Returns([]);
//Act
var listOnlyActive = _blacksmithBusinessLogicContract.GetAllBlacksmithByRank(Guid.NewGuid().ToString(), true);
var list = _blacksmithBusinessLogicContract.GetAllBlacksmithByRank(Guid.NewGuid().ToString(), false);
//Assert
Assert.Multiple(() =>
{
Assert.That(listOnlyActive, Is.Not.Null);
Assert.That(list, Is.Not.Null);
Assert.That(listOnlyActive, Has.Count.EqualTo(0));
Assert.That(list, Has.Count.EqualTo(0));
});
_blacksmithStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string>(), It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Exactly(2));
}
[Test]
public void GetAllBlacksmithByRank_RankIdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _blacksmithBusinessLogicContract.GetAllBlacksmithByRank(null, It.IsAny<bool>()),
Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _blacksmithBusinessLogicContract.GetAllBlacksmithByRank(string.Empty, It.IsAny<bool>()),
Throws.TypeOf<ArgumentNullException>());
_blacksmithStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string>(), It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Never);
}
[Test]
public void GetAllBlacksmithByRank_RankIdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _blacksmithBusinessLogicContract.GetAllBlacksmithByRank("rankId", It.IsAny<bool>()),
Throws.TypeOf<ValidationException>());
_blacksmithStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string>(), It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Never);
}
[Test]
public void GetAllBlacksmithByRank_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _blacksmithBusinessLogicContract.GetAllBlacksmithByRank(Guid.NewGuid().ToString(), It.IsAny<bool>()),
Throws.TypeOf<NullListException>());
_blacksmithStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string>(), It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Once);
}
[Test]
public void GetAllBlacksmithByRank_StorageThrowError_ThrowException_Test()
{
//Arrange
_blacksmithStorageContract.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
Assert.That(() => _blacksmithBusinessLogicContract.GetAllBlacksmithByRank(Guid.NewGuid().ToString(), It.IsAny<bool>()),
Throws.TypeOf<StorageException>());
_blacksmithStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Once);
}
[Test]
public void GetAllBlacksmithByBirthDate_ReturnListOfRecords_Test()
{
//Arrange
var date = DateTime.UtcNow;
var listOriginal = new List<BlacksmithDataModel>()
{
new(Guid.NewGuid().ToString(), "fio 1", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1),
DateTime.Now, false),
new(Guid.NewGuid().ToString(), "fio 2", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1),
DateTime.Now, true),
new(Guid.NewGuid().ToString(), "fio 3", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1),
DateTime.Now, false)
};
_blacksmithStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Returns(listOriginal);
//Act
var listOnlyActive = _blacksmithBusinessLogicContract.GetAllBlacksmithByBirthDate(date, date.AddDays(1), true);
var list = _blacksmithBusinessLogicContract.GetAllBlacksmithByBirthDate(date, date.AddDays(1), false);
//Assert
Assert.Multiple(() =>
{
Assert.That(listOnlyActive, Is.Not.Null);
Assert.That(list, Is.Not.Null);
Assert.That(listOnlyActive, Is.EquivalentTo(listOriginal));
Assert.That(list, Is.EquivalentTo(listOriginal));
});
_blacksmithStorageContract.Verify(x => x.GetList(true, null, date, date.AddDays(1), null, null), Times.Once);
_blacksmithStorageContract.Verify(x => x.GetList(false, null, date, date.AddDays(1), null, null), Times.Once);
}
[Test]
public void GetAllBlacksmithByBirthDate_ReturnEmptyList_Test()
{
//Arrange
_blacksmithStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Returns([]);
//Act
var listOnlyActive = _blacksmithBusinessLogicContract.GetAllBlacksmithByBirthDate(DateTime.UtcNow,
DateTime.UtcNow.AddDays(1), true);
var list = _blacksmithBusinessLogicContract.GetAllBlacksmith(false);
//Assert
Assert.Multiple(() =>
{
Assert.That(listOnlyActive, Is.Not.Null);
Assert.That(list, Is.Not.Null);
Assert.That(listOnlyActive, Has.Count.EqualTo(0));
Assert.That(list, Has.Count.EqualTo(0));
});
_blacksmithStorageContract.Verify(x => x.GetList(true, null, It.IsAny<DateTime?>(), It.IsAny<DateTime?>(),
null, null), Times.Once);
_blacksmithStorageContract.Verify(x => x.GetList(false, null, It.IsAny<DateTime?>(), It.IsAny<DateTime?>(),
null, null), Times.Once);
}
[Test]
public void GetAllBlacksmithByBirthDate_IncorrectDates_ThrowException_Test()
{
//Arrange
var date = DateTime.UtcNow;
//Act&Assert
Assert.That(() => _blacksmithBusinessLogicContract.GetAllBlacksmithByBirthDate(date, date, It.IsAny<bool>()),
Throws.TypeOf<IncorrectDatesException>());
Assert.That(() => _blacksmithBusinessLogicContract.GetAllBlacksmithByBirthDate(date, date.AddSeconds(-1), It.IsAny<bool>()),
Throws.TypeOf<IncorrectDatesException>());
_blacksmithStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Never);
}
[Test]
public void GetAllBlacksmithByBirthDate_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _blacksmithBusinessLogicContract.GetAllBlacksmithByBirthDate(DateTime.UtcNow,
DateTime.UtcNow.AddDays(1), It.IsAny<bool>()), Throws.TypeOf<NullListException>());
_blacksmithStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(),
It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Once);
}
[Test]
public void GetAllBlacksmithByBirthDate_StorageThrowError_ThrowException_Test()
{
//Arrange
_blacksmithStorageContract.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
Assert.That(() => _blacksmithBusinessLogicContract.GetAllBlacksmithByBirthDate(DateTime.UtcNow,
DateTime.UtcNow.AddDays(1), It.IsAny<bool>()), Throws.TypeOf<StorageException>());
_blacksmithStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Once);
}
[Test]
public void GetAllBlacksmithByEmploymentDate_ReturnListOfRecords_Test()
{
//Arrange
var date = DateTime.UtcNow;
var listOriginal = new List<BlacksmithDataModel>()
{
new(Guid.NewGuid().ToString(), "fio 1", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1),
DateTime.Now, false),
new(Guid.NewGuid().ToString(), "fio 2", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1),
DateTime.Now, true),
new(Guid.NewGuid().ToString(), "fio 3", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1),
DateTime.Now, false)
};
_blacksmithStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Returns(listOriginal);
//Act
var listOnlyActive = _blacksmithBusinessLogicContract.GetAllBlacksmithByEmploymentDate(date, date.AddDays(1), true);
var list = _blacksmithBusinessLogicContract.GetAllBlacksmithByEmploymentDate(date, date.AddDays(1), false);
//Assert
Assert.Multiple(() =>
{
Assert.That(listOnlyActive, Is.Not.Null);
Assert.That(list, Is.Not.Null);
Assert.That(listOnlyActive, Is.EquivalentTo(listOriginal));
Assert.That(list, Is.EquivalentTo(listOriginal));
});
_blacksmithStorageContract.Verify(x => x.GetList(true, null, null, null, date, date.AddDays(1)), Times.Once);
_blacksmithStorageContract.Verify(x => x.GetList(false, null, null, null, date, date.AddDays(1)), Times.Once);
}
[Test]
public void GetAllBlacksmithByEmploymentDate_ReturnEmptyList_Test()
{
//Arrange
_blacksmithStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Returns([]);
//Act
var listOnlyActive = _blacksmithBusinessLogicContract.GetAllBlacksmithByEmploymentDate(DateTime.UtcNow,
DateTime.UtcNow.AddDays(1), true);
var list = _blacksmithBusinessLogicContract.GetAllBlacksmithByEmploymentDate(DateTime.UtcNow,
DateTime.UtcNow.AddDays(1), false);
//Assert
Assert.Multiple(() =>
{
Assert.That(listOnlyActive, Is.Not.Null);
Assert.That(list, Is.Not.Null);
Assert.That(listOnlyActive, Has.Count.EqualTo(0));
Assert.That(list, Has.Count.EqualTo(0));
});
_blacksmithStorageContract.Verify(x => x.GetList(true, null, null, null,
It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Once);
_blacksmithStorageContract.Verify(x => x.GetList(false, null, null, null,
It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Once);
}
[Test]
public void GetAllBlacksmithByEmploymentDate_IncorrectDates_ThrowException_Test()
{
//Arrange
var date = DateTime.UtcNow;
//Act&Assert
Assert.That(() => _blacksmithBusinessLogicContract.GetAllBlacksmithByEmploymentDate(date, date, It.IsAny<bool>()),
Throws.TypeOf<IncorrectDatesException>());
Assert.That(() => _blacksmithBusinessLogicContract.GetAllBlacksmithByEmploymentDate(date, date.AddSeconds(-1),
It.IsAny<bool>()), Throws.TypeOf<IncorrectDatesException>());
_blacksmithStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Never);
}
[Test]
public void GetAllBlacksmithByEmploymentDate_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _blacksmithBusinessLogicContract.GetAllBlacksmithByEmploymentDate(DateTime.UtcNow,
DateTime.UtcNow.AddDays(1), It.IsAny<bool>()), Throws.TypeOf<NullListException>());
_blacksmithStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Once);
}
[Test]
public void GetAllBlacksmithByEmploymentDate_StorageThrowError_ThrowException_Test()
{
//Arrange
_blacksmithStorageContract.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
Assert.That(() => _blacksmithBusinessLogicContract.GetAllBlacksmithByEmploymentDate(DateTime.UtcNow,
DateTime.UtcNow.AddDays(1), It.IsAny<bool>()), Throws.TypeOf<StorageException>());
_blacksmithStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Once);
}
[Test]
public void GetBlacksmithByData_GetById_ReturnRecord_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
var record = new BlacksmithDataModel(id, "fio", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1),
DateTime.Now, false);
_blacksmithStorageContract.Setup(x => x.GetElementById(id)).Returns(record);
//Act
var element = _blacksmithBusinessLogicContract.GetBlacksmithByData(id);
//Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.Id, Is.EqualTo(id));
_blacksmithStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetBlacksmithByData_GetByFio_ReturnRecord_Test()
{
//Arrange
var fio = "fio";
var record = new BlacksmithDataModel(Guid.NewGuid().ToString(), fio, Guid.NewGuid().ToString(),
DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false);
_blacksmithStorageContract.Setup(x => x.GetElementByFIO(fio)).Returns(record);
//Act
var element = _blacksmithBusinessLogicContract.GetBlacksmithByData(fio);
//Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.FIO, Is.EqualTo(fio));
_blacksmithStorageContract.Verify(x => x.GetElementByFIO(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetBlacksmithByData_EmptyData_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _blacksmithBusinessLogicContract.GetBlacksmithByData(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _blacksmithBusinessLogicContract.GetBlacksmithByData(string.Empty),
Throws.TypeOf<ArgumentNullException>());
_blacksmithStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Never);
_blacksmithStorageContract.Verify(x => x.GetElementByFIO(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetBlacksmithByData_GetById_NotFoundRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _blacksmithBusinessLogicContract.GetBlacksmithByData(Guid.NewGuid().ToString()),
Throws.TypeOf<ElementNotFoundException>());
_blacksmithStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
_blacksmithStorageContract.Verify(x => x.GetElementByFIO(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetBlacksmithByData_GetByFio_NotFoundRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _blacksmithBusinessLogicContract.GetBlacksmithByData("fio"), Throws.TypeOf<ElementNotFoundException>());
_blacksmithStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Never);
_blacksmithStorageContract.Verify(x => x.GetElementByFIO(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetBlacksmithByData_StorageThrowError_ThrowException_Test()
{
//Arrange
_blacksmithStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Throws(new StorageException(new InvalidOperationException()));
_blacksmithStorageContract.Setup(x => x.GetElementByFIO(It.IsAny<string>()))
.Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _blacksmithBusinessLogicContract.GetBlacksmithByData(Guid.NewGuid().ToString()),
Throws.TypeOf<StorageException>());
Assert.That(() => _blacksmithBusinessLogicContract.GetBlacksmithByData("fio"), Throws.TypeOf<StorageException>());
_blacksmithStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
_blacksmithStorageContract.Verify(x => x.GetElementByFIO(It.IsAny<string>()), Times.Once);
}
[Test]
public void InsertBlacksmith_CorrectRecord_Test()
{
//Arrange
var flag = false;
var record = new BlacksmithDataModel(Guid.NewGuid().ToString(), "fio", Guid.NewGuid().ToString(),
DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false);
_blacksmithStorageContract.Setup(x => x.AddElement(It.IsAny<BlacksmithDataModel>()))
.Callback((BlacksmithDataModel x) =>
{
flag = x.Id == record.Id && x.FIO == record.FIO &&
x.RankId == record.RankId && x.BirthDate == record.BirthDate &&
x.EmploymentDate == record.EmploymentDate &&
x.IsDeleted == record.IsDeleted;
});
//Act
_blacksmithBusinessLogicContract.InsertBlacksmith(record);
//Assert
_blacksmithStorageContract.Verify(x => x.AddElement(It.IsAny<BlacksmithDataModel>()), Times.Once);
Assert.That(flag);
}
[Test]
public void InsertBlacksmith_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_blacksmithStorageContract.Setup(x => x.AddElement(It.IsAny<BlacksmithDataModel>()))
.Throws(new ElementExistsException("Data", "Data"));
//Act&Assert
Assert.That(() => _blacksmithBusinessLogicContract.InsertBlacksmith(new(Guid.NewGuid().ToString(), "fio",
Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false)),
Throws.TypeOf<ElementExistsException>());
_blacksmithStorageContract.Verify(x => x.AddElement(It.IsAny<BlacksmithDataModel>()), Times.Once);
}
[Test]
public void InsertBlacksmith_NullRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _blacksmithBusinessLogicContract.InsertBlacksmith(null),
Throws.TypeOf<ArgumentNullException>());
_blacksmithStorageContract.Verify(x => x.AddElement(It.IsAny<BlacksmithDataModel>()), Times.Never);
}
[Test]
public void InsertBlacksmith_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _blacksmithBusinessLogicContract.InsertBlacksmith(new BlacksmithDataModel("id", "fio",
Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false)),
Throws.TypeOf<ValidationException>());
_blacksmithStorageContract.Verify(x => x.AddElement(It.IsAny<BlacksmithDataModel>()), Times.Never);
}
[Test]
public void InsertBlacksmith_StorageThrowError_ThrowException_Test()
{
//Arrange
_blacksmithStorageContract.Setup(x => x.AddElement(It.IsAny<BlacksmithDataModel>()))
.Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _blacksmithBusinessLogicContract.InsertBlacksmith(new(Guid.NewGuid().ToString(), "fio",
Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false)),
Throws.TypeOf<StorageException>());
_blacksmithStorageContract.Verify(x => x.AddElement(It.IsAny<BlacksmithDataModel>()), Times.Once);
}
[Test]
public void UpdateBlacksmith_CorrectRecord_Test()
{
//Arrange
var flag = false;
var record = new BlacksmithDataModel(Guid.NewGuid().ToString(), "fio", Guid.NewGuid().ToString(),
DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false);
_blacksmithStorageContract.Setup(x => x.UpdElement(It.IsAny<BlacksmithDataModel>()))
.Callback((BlacksmithDataModel x) =>
{
flag = x.Id == record.Id && x.FIO == record.FIO &&
x.RankId == record.RankId && x.BirthDate == record.BirthDate &&
x.EmploymentDate == record.EmploymentDate &&
x.IsDeleted == record.IsDeleted;
});
//Act
_blacksmithBusinessLogicContract.UpdateBlacksmith(record);
//Assert
_blacksmithStorageContract.Verify(x => x.UpdElement(It.IsAny<BlacksmithDataModel>()), Times.Once); Assert.That(flag);
}
[Test]
public void UpdateBlacksmith_RecordWithIncorrectData_ThrowException_Test()
{
//Arrange
_blacksmithStorageContract.Setup(x => x.UpdElement(It.IsAny<BlacksmithDataModel>()))
.Throws(new ElementNotFoundException(""));
//Act&Assert
Assert.That(() => _blacksmithBusinessLogicContract.UpdateBlacksmith(new(Guid.NewGuid().ToString(), "fio",
Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false)),
Throws.TypeOf<ElementNotFoundException>());
_blacksmithStorageContract.Verify(x => x.UpdElement(It.IsAny<BlacksmithDataModel>()), Times.Once);
}
[Test]
public void UpdateBlacksmith_NullRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _blacksmithBusinessLogicContract.UpdateBlacksmith(null),
Throws.TypeOf<ArgumentNullException>());
_blacksmithStorageContract.Verify(x => x.UpdElement(It.IsAny<BlacksmithDataModel>()), Times.Never);
}
[Test]
public void UpdateBlacksmith_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _blacksmithBusinessLogicContract.UpdateBlacksmith(new BlacksmithDataModel("id", "fio",
Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false)),
Throws.TypeOf<ValidationException>());
_blacksmithStorageContract.Verify(x => x.UpdElement(It.IsAny<BlacksmithDataModel>()), Times.Never);
}
[Test]
public void UpdateBlacksmith_StorageThrowError_ThrowException_Test()
{
//Arrange
_blacksmithStorageContract.Setup(x => x.UpdElement(It.IsAny<BlacksmithDataModel>()))
.Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _blacksmithBusinessLogicContract.UpdateBlacksmith(new(Guid.NewGuid().ToString(), "fio",
Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false)),
Throws.TypeOf<StorageException>());
_blacksmithStorageContract.Verify(x => x.UpdElement(It.IsAny<BlacksmithDataModel>()), Times.Once);
}
[Test]
public void DeleteBlacksmith_CorrectRecord_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
var flag = false;
_blacksmithStorageContract.Setup(x => x.DelElement(It.Is((string x) => x == id))).Callback(() => { flag = true; });
//Act
_blacksmithBusinessLogicContract.DeleteBlacksmith(id);
//Assert
_blacksmithStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
Assert.That(flag);
}
[Test]
public void DeleteBlacksmith_RecordWithIncorrectId_ThrowException_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
_blacksmithStorageContract.Setup(x => x.DelElement(It.Is((string x) => x != id))).Throws(new ElementNotFoundException(id));
//Act&Assert
Assert.That(() => _blacksmithBusinessLogicContract.DeleteBlacksmith(Guid.NewGuid().ToString()),
Throws.TypeOf<ElementNotFoundException>());
_blacksmithStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
}
[Test]
public void DeleteBlacksmith_IdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _blacksmithBusinessLogicContract.DeleteBlacksmith(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _blacksmithBusinessLogicContract.DeleteBlacksmith(string.Empty), Throws.TypeOf<ArgumentNullException>());
_blacksmithStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Never);
}
[Test]
public void DeleteBlacksmith_IdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _blacksmithBusinessLogicContract.DeleteBlacksmith("id"), Throws.TypeOf<ValidationException>());
_blacksmithStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Never);
}
[Test]
public void DeleteBlacksmith_StorageThrowError_ThrowException_Test()
{
//Arrange
_blacksmithStorageContract.Setup(x => x.DelElement(It.IsAny<string>()))
.Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _blacksmithBusinessLogicContract.DeleteBlacksmith(Guid.NewGuid().ToString()),
Throws.TypeOf<StorageException>());
_blacksmithStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
}
}
}

View File

@@ -0,0 +1,375 @@
using TheBlacksmithVakulaContract.BusinessLogicsContracts;
using TheBlacksmithVakulaContract.DataModels;
using TheBlacksmithVakulaContract.Exceptions;
using TheBlacksmithVakulaContract.StoragesContracts;
using TheBlacksmithVakulaBusinessLogic.Implementations;
using Microsoft.Extensions.Logging;
using Moq;
namespace TheBlacksmithVakulaTests.BusinessLogicContractTests
{
[TestFixture]
public class BuyerBusinessLogicContractTests
{
private IBuyerBusinessLogicContract _buyerBusinessLogicContract;
private Mock<IBuyerStorageContract> _buyerStorageContract;
[OneTimeSetUp]
public void OneTimeSetUp()
{
_buyerStorageContract = new Mock<IBuyerStorageContract>();
_buyerBusinessLogicContract = new BuyerBusinessLogicContract(_buyerStorageContract.Object, new Mock<ILogger>().Object);
}
[SetUp]
public void SetUp()
{
_buyerStorageContract.Reset();
}
[Test]
public void GetAllBuyers_ReturnListOfRecords_Test()
{
//Arrange
var listOriginal = new List<BuyerDataModel>()
{
new(Guid.NewGuid().ToString(), "fio 1", "+7-111-111-11-11", 0),
new(Guid.NewGuid().ToString(), "fio 2", "+7-555-444-33-23", 10),
new(Guid.NewGuid().ToString(), "fio 3", "+7-777-777-7777", 0)
};
_buyerStorageContract.Setup(x => x.GetList()).Returns(listOriginal);
//Act
var list = _buyerBusinessLogicContract.GetAllBuyers();
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.EquivalentTo(listOriginal));
}
[Test]
public void GetAllBuyers_ReturnEmptyList_Test()
{
//Arrange
_buyerStorageContract.Setup(x => x.GetList()).Returns([]);
//Act
var list = _buyerBusinessLogicContract.GetAllBuyers();
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
_buyerStorageContract.Verify(x => x.GetList(), Times.Once);
}
[Test]
public void GetAllBuyers_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _buyerBusinessLogicContract.GetAllBuyers(), Throws.TypeOf<NullListException>());
_buyerStorageContract.Verify(x => x.GetList(), Times.Once);
}
[Test]
public void GetAllBuyers_StorageThrowError_ThrowException_Test()
{
//Arrange
_buyerStorageContract.Setup(x => x.GetList()).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _buyerBusinessLogicContract.GetAllBuyers(), Throws.TypeOf<StorageException>());
_buyerStorageContract.Verify(x => x.GetList(), Times.Once);
}
[Test]
public void GetBuyerByData_GetById_ReturnRecord_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
var record = new BuyerDataModel(id, "fio", "+7-111-111-11-11", 0);
_buyerStorageContract.Setup(x => x.GetElementById(id)).Returns(record);
//Act
var element = _buyerBusinessLogicContract.GetBuyerByData(id);
//Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.Id, Is.EqualTo(id));
_buyerStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetBuyerByData_GetByFio_ReturnRecord_Test()
{
//Arrange
var fio = "fio";
var record = new BuyerDataModel(Guid.NewGuid().ToString(), fio, "+7-111 - 111 - 11 - 11", 0);
_buyerStorageContract.Setup(x => x.GetElementByFIO(fio)).Returns(record);
//Act
var element = _buyerBusinessLogicContract.GetBuyerByData(fio);
//Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.FIO, Is.EqualTo(fio));
_buyerStorageContract.Verify(x => x.GetElementByFIO(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetBuyerByData_GetByPhoneNumber_ReturnRecord_Test()
{
//Arrange
var phoneNumber = "+7-111-111-11-11";
var record = new BuyerDataModel(Guid.NewGuid().ToString(), "fio", phoneNumber, 0);
_buyerStorageContract.Setup(x => x.GetElementByPhoneNumber(phoneNumber)).Returns(record);
//Act
var element = _buyerBusinessLogicContract.GetBuyerByData(phoneNumber);
//Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.PhoneNumber, Is.EqualTo(phoneNumber));
_buyerStorageContract.Verify(x => x.GetElementByPhoneNumber(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetBuyerByData_EmptyData_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _buyerBusinessLogicContract.GetBuyerByData(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _buyerBusinessLogicContract.GetBuyerByData(string.Empty), Throws.TypeOf<ArgumentNullException>());
_buyerStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Never);
_buyerStorageContract.Verify(x => x.GetElementByPhoneNumber(It.IsAny<string>()), Times.Never);
_buyerStorageContract.Verify(x => x.GetElementByFIO(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetBuyerByData_GetById_NotFoundRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _buyerBusinessLogicContract.GetBuyerByData(Guid.NewGuid().ToString()),
Throws.TypeOf<ElementNotFoundException>());
_buyerStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
_buyerStorageContract.Verify(x => x.GetElementByPhoneNumber(It.IsAny<string>()), Times.Never);
_buyerStorageContract.Verify(x => x.GetElementByFIO(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetBuyerByData_GetByFio_NotFoundRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _buyerBusinessLogicContract.GetBuyerByData("fio"), Throws.TypeOf<ElementNotFoundException>());
_buyerStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Never);
_buyerStorageContract.Verify(x => x.GetElementByFIO(It.IsAny<string>()), Times.Once);
_buyerStorageContract.Verify(x => x.GetElementByPhoneNumber(It.IsAny<string>()), Times.Never);
}
[Test]
public void
GetBuyerByData_GetByPhoneNumber_NotFoundRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _buyerBusinessLogicContract.GetBuyerByData("+7-111-111-11-12"),
Throws.TypeOf<ElementNotFoundException>());
_buyerStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Never);
_buyerStorageContract.Verify(x => x.GetElementByFIO(It.IsAny<string>()), Times.Never);
_buyerStorageContract.Verify(x => x.GetElementByPhoneNumber(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetBuyerByData_StorageThrowError_ThrowException_Test()
{
//Arrange
_buyerStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Throws(new StorageException(new InvalidOperationException()));
_buyerStorageContract.Setup(x => x.GetElementByFIO(It.IsAny<string>()))
.Throws(new StorageException(new InvalidOperationException()));
_buyerStorageContract.Setup(x => x.GetElementByPhoneNumber(It.IsAny<string>()))
.Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _buyerBusinessLogicContract.GetBuyerByData(Guid.NewGuid().ToString()),
Throws.TypeOf<StorageException>());
Assert.That(() => _buyerBusinessLogicContract.GetBuyerByData("fio"), Throws.TypeOf<StorageException>());
Assert.That(() => _buyerBusinessLogicContract.GetBuyerByData("+7-111-111-11-12"),
Throws.TypeOf<StorageException>());
_buyerStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
_buyerStorageContract.Verify(x => x.GetElementByFIO(It.IsAny<string>()), Times.Once);
_buyerStorageContract.Verify(x => x.GetElementByPhoneNumber(It.IsAny<string>()), Times.Once);
}
[Test]
public void InsertBuyer_CorrectRecord_Test()
{
//Arrange
var flag = false;
var record = new BuyerDataModel(Guid.NewGuid().ToString(), "fio", "+7-111-111-11-11", 10);
_buyerStorageContract.Setup(x => x.AddElement(It.IsAny<BuyerDataModel>()))
.Callback((BuyerDataModel x) =>
{
flag = x.Id == record.Id && x.FIO == record.FIO &&
x.PhoneNumber == record.PhoneNumber &&
x.DiscountSize == record.DiscountSize;
});
//Act
_buyerBusinessLogicContract.InsertBuyer(record);
//Assert
_buyerStorageContract.Verify(x => x.AddElement(It.IsAny<BuyerDataModel>()), Times.Once);
Assert.That(flag);
}
[Test]
public void InsertBuyer_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_buyerStorageContract.Setup(x => x.AddElement(It.IsAny<BuyerDataModel>()))
.Throws(new ElementExistsException("Data", "Data"));
//Act&Assert
Assert.That(() => _buyerBusinessLogicContract.InsertBuyer(new(Guid.NewGuid().ToString(), "fio", "+7-111-111-11-11", 0)),
Throws.TypeOf<ElementExistsException>());
_buyerStorageContract.Verify(x => x.AddElement(It.IsAny<BuyerDataModel>()), Times.Once);
}
[Test]
public void InsertBuyer_NullRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _buyerBusinessLogicContract.InsertBuyer(null), Throws.TypeOf<ArgumentNullException>());
_buyerStorageContract.Verify(x => x.AddElement(It.IsAny<BuyerDataModel>()), Times.Never);
}
[Test]
public void InsertBuyer_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _buyerBusinessLogicContract.InsertBuyer(new BuyerDataModel("id", "fio", "+7-111-111-11-11", 10)),
Throws.TypeOf<ValidationException>());
_buyerStorageContract.Verify(x => x.AddElement(It.IsAny<BuyerDataModel>()), Times.Never);
}
[Test]
public void InsertBuyer_StorageThrowError_ThrowException_Test()
{
//Arrange
_buyerStorageContract.Setup(x => x.AddElement(It.IsAny<BuyerDataModel>()))
.Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _buyerBusinessLogicContract.InsertBuyer(new(Guid.NewGuid().ToString(), "fio", "+7-111-111-11-11", 0)),
Throws.TypeOf<StorageException>());
_buyerStorageContract.Verify(x => x.AddElement(It.IsAny<BuyerDataModel>()), Times.Once);
}
[Test]
public void UpdateBuyer_CorrectRecord_Test()
{
//Arrange
var flag = false;
var record = new BuyerDataModel(Guid.NewGuid().ToString(), "fio", "+7-111-111-11-11", 0);
_buyerStorageContract.Setup(x => x.UpdElement(It.IsAny<BuyerDataModel>()))
.Callback((BuyerDataModel x) =>
{
flag = x.Id == record.Id && x.FIO == record.FIO &&
x.PhoneNumber == record.PhoneNumber &&
x.DiscountSize == record.DiscountSize;
});
//Act
_buyerBusinessLogicContract.UpdateBuyer(record);
//Assert
_buyerStorageContract.Verify(x => x.UpdElement(It.IsAny<BuyerDataModel>()), Times.Once);
Assert.That(flag);
}
[Test]
public void UpdateBuyer_RecordWithIncorrectData_ThrowException_Test()
{
//Arrange
_buyerStorageContract.Setup(x => x.UpdElement(It.IsAny<BuyerDataModel>())).Throws(new ElementNotFoundException(""));
//Act&Assert
Assert.That(() => _buyerBusinessLogicContract.UpdateBuyer(new(Guid.NewGuid().ToString(), "fio", "+7-111-111-11-11", 0)),
Throws.TypeOf<ElementNotFoundException>());
_buyerStorageContract.Verify(x => x.UpdElement(It.IsAny<BuyerDataModel>()), Times.Once);
}
[Test]
public void UpdateBuyer_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_buyerStorageContract.Setup(x => x.UpdElement(It.IsAny<BuyerDataModel>()))
.Throws(new ElementExistsException("Data", "Data"));
//Act&Assert
Assert.That(() => _buyerBusinessLogicContract.UpdateBuyer(new(Guid.NewGuid().ToString(), "fio", "+7-111-111-11-11", 0)),
Throws.TypeOf<ElementExistsException>());
_buyerStorageContract.Verify(x => x.UpdElement(It.IsAny<BuyerDataModel>()), Times.Once);
}
[Test]
public void UpdateBuyer_NullRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _buyerBusinessLogicContract.UpdateBuyer(null), Throws.TypeOf<ArgumentNullException>());
_buyerStorageContract.Verify(x => x.UpdElement(It.IsAny<BuyerDataModel>()), Times.Never);
}
[Test]
public void UpdateBuyer_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _buyerBusinessLogicContract.UpdateBuyer(new BuyerDataModel("id", "fio", "+7-111-111-11-11", 10)),
Throws.TypeOf<ValidationException>());
_buyerStorageContract.Verify(x => x.UpdElement(It.IsAny<BuyerDataModel>()), Times.Never);
}
[Test]
public void UpdateBuyer_StorageThrowError_ThrowException_Test()
{
//Arrange
_buyerStorageContract.Setup(x => x.UpdElement(It.IsAny<BuyerDataModel>()))
.Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _buyerBusinessLogicContract.UpdateBuyer(new(Guid.NewGuid().ToString(), "fio", "+7-111-111-11-11", 0)),
Throws.TypeOf<StorageException>());
_buyerStorageContract.Verify(x => x.UpdElement(It.IsAny<BuyerDataModel>()), Times.Once);
}
[Test]
public void DeleteBuyer_CorrectRecord_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
var flag = false;
_buyerStorageContract.Setup(x => x.DelElement(It.Is((string x) => x == id))).Callback(() => { flag = true; });
//Act
_buyerBusinessLogicContract.DeleteBuyer(id);
//Assert
_buyerStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
Assert.That(flag);
}
[Test]
public void DeleteBuyer_RecordWithIncorrectId_ThrowException_Test()
{
//Arrange
_buyerStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new ElementNotFoundException(""));
//Act&Assert
Assert.That(() => _buyerBusinessLogicContract.DeleteBuyer(Guid.NewGuid().ToString()),
Throws.TypeOf<ElementNotFoundException>());
_buyerStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
}
[Test]
public void DeleteBuyer_IdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _buyerBusinessLogicContract.DeleteBuyer(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _buyerBusinessLogicContract.DeleteBuyer(string.Empty), Throws.TypeOf<ArgumentNullException>());
_buyerStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Never);
}
[Test]
public void DeleteBuyer_IdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _buyerBusinessLogicContract.DeleteBuyer("id"), Throws.TypeOf<ValidationException>());
_buyerStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Never);
}
[Test]
public void DeleteBuyer_StorageThrowError_ThrowException_Test()
{
//Arrange
_buyerStorageContract.Setup(x => x.DelElement(It.IsAny<string>()))
.Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _buyerBusinessLogicContract.DeleteBuyer(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_buyerStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
}
}
}

View File

@@ -0,0 +1,586 @@
using TheBlacksmithVakulaBusinessLogic.Implementations;
using TheBlacksmithVakulaContract.BusinessLogicsContracts;
using TheBlacksmithVakulaContract.Enums;
using TheBlacksmithVakulaContract.Exceptions;
using TheBlacksmithVakulaContract.StoragesContracts;
using TheBlacksmithVakulaContract.DataModels;
using Microsoft.Extensions.Logging;
using Moq;
namespace TheBlacksmithVakulaTests.BusinessLogicContractTests
{
[TestFixture]
public class OrderBusinessLogicContractTests
{
private IOrderBusinessLogicContract _orderBusinessLogicContract;
private Mock<IOrderStorageContract> _orderStorageContract;
[OneTimeSetUp]
public void OneTimeSetUp()
{
_orderStorageContract = new Mock<IOrderStorageContract>();
_orderBusinessLogicContract = new OrderBusinessLogicContract(_orderStorageContract.Object, new Mock<ILogger>().Object);
}
[SetUp]
public void SetUp()
{
_orderStorageContract.Reset();
}
[Test]
public void GetAllOrderByPeriod_ReturnListOfRecords_Test()
{
//Arrange
var date = DateTime.UtcNow;
var listOriginal = new List<OrderDataModel>()
{
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, DiscountType.None, false,
[new OrderProductDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]),
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, DiscountType.None, false, []),
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, DiscountType.None, false, []),
};
_orderStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Returns(listOriginal);
//Act
var list = _orderBusinessLogicContract.GetAllOrderByPeriod(date, date.AddDays(1));
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.EquivalentTo(listOriginal));
_orderStorageContract.Verify(x => x.GetList(date, date.AddDays(1), null, null, null), Times.Once);
}
[Test]
public void GetAllOrderByPeriod_ReturnEmptyList_Test()
{
//Arrange
_orderStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Returns([]);
//Act
var list = _orderBusinessLogicContract.GetAllOrderByPeriod(DateTime.UtcNow, DateTime.UtcNow.AddDays(1));
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
_orderStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllOrderByPeriod_IncorrectDates_ThrowException_Test()
{
//Arrange
var date = DateTime.UtcNow;
//Act&Assert
Assert.That(() => _orderBusinessLogicContract.GetAllOrderByPeriod(date, date), Throws.TypeOf<IncorrectDatesException>());
Assert.That(() => _orderBusinessLogicContract.GetAllOrderByPeriod(date, date.AddSeconds(-1)),
Throws.TypeOf<IncorrectDatesException>());
_orderStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllOrderByPeriod_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _orderBusinessLogicContract.GetAllOrderByPeriod(DateTime.UtcNow, DateTime.UtcNow.AddDays(1)),
Throws.TypeOf<NullListException>());
_orderStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllOrderByPeriod_StorageThrowError_ThrowException_Test()
{
//Arrange
_orderStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
.Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _orderBusinessLogicContract.GetAllOrderByPeriod(DateTime.UtcNow, DateTime.UtcNow.AddDays(1)),
Throws.TypeOf<StorageException>());
_orderStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllOrderByBlacksmithByPeriod_ReturnListOfRecords_Test()
{
//Arrange
var date = DateTime.UtcNow;
var blacksmithId = Guid.NewGuid().ToString();
var listOriginal = new List<OrderDataModel>()
{
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, DiscountType.None, false,
[new OrderProductDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]),
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, DiscountType.None, false, []),
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, DiscountType.None, false, []),
};
_orderStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Returns(listOriginal);
//Act
var list = _orderBusinessLogicContract.GetAllOrderByBlacksmithByPeriod(blacksmithId, date, date.AddDays(1));
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.EquivalentTo(listOriginal));
_orderStorageContract.Verify(x => x.GetList(date, date.AddDays(1), blacksmithId, null, null), Times.Once);
}
[Test]
public void GetAllOrderByBlacksmithByPeriod_ReturnEmptyList_Test()
{
//Arrange
_orderStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Returns([]);
//Act
var list = _orderBusinessLogicContract.GetAllOrderByBlacksmithByPeriod(Guid.NewGuid().ToString(), DateTime.UtcNow,
DateTime.UtcNow.AddDays(1));
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
_orderStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllOrderByBlacksmithByPeriod_IncorrectDates_ThrowException_Test()
{
//Arrange
var date = DateTime.UtcNow;
//Act&Assert
Assert.That(() => _orderBusinessLogicContract.GetAllOrderByBlacksmithByPeriod(Guid.NewGuid().ToString(), date, date),
Throws.TypeOf<IncorrectDatesException>());
Assert.That(() => _orderBusinessLogicContract.GetAllOrderByBlacksmithByPeriod(Guid.NewGuid().ToString(),
date, date.AddSeconds(-1)), Throws.TypeOf<IncorrectDatesException>());
_orderStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllOrderByBlacksmithByPeriod_BlacksmithIdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _orderBusinessLogicContract.GetAllOrderByBlacksmithByPeriod(null, DateTime.UtcNow,
DateTime.UtcNow.AddDays(1)), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _orderBusinessLogicContract.GetAllOrderByBlacksmithByPeriod(string.Empty, DateTime.UtcNow,
DateTime.UtcNow.AddDays(1)), Throws.TypeOf<ArgumentNullException>());
_orderStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllOrderByBlacksmithByPeriod_BlacksmithIdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _orderBusinessLogicContract.GetAllOrderByBlacksmithByPeriod("blacksmithId",
DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<ValidationException>());
_orderStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllOrderByBlacksmithByPeriod_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _orderBusinessLogicContract.GetAllOrderByBlacksmithByPeriod(Guid.NewGuid().ToString(),
DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<NullListException>());
_orderStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllOrderByBlacksmithByPeriod_StorageThrowError_ThrowException_Test()
{
//Arrange
_orderStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
.Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _orderBusinessLogicContract.GetAllOrderByBlacksmithByPeriod(Guid.NewGuid().ToString(),
DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<StorageException>());
_orderStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllOrderByBuyerByPeriod_ReturnListOfRecords_Test()
{
//Arrange
var date = DateTime.UtcNow;
var buyerId = Guid.NewGuid().ToString();
var listOriginal = new List<OrderDataModel>()
{
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, DiscountType.None, false,
[new OrderProductDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]),
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, DiscountType.None, false, []),
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, DiscountType.None, false, [])
};
_orderStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<string?>(), It.IsAny<string?>(), It.IsAny<string?>())).Returns(listOriginal);
//Act
var list = _orderBusinessLogicContract.GetAllOrderByBuyerByPeriod(buyerId, date, date.AddDays(1));
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.EquivalentTo(listOriginal));
_orderStorageContract.Verify(x => x.GetList(date, date.AddDays(1), null, null, buyerId), Times.Once);
}
[Test]
public void GetAllOrderByBuyerByPeriod_ReturnEmptyList_Test()
{
//Arrange
_orderStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Returns([]);
//Act
var list = _orderBusinessLogicContract.GetAllOrderByBuyerByPeriod(Guid.NewGuid().ToString(),
DateTime.UtcNow, DateTime.UtcNow.AddDays(1));
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
_orderStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllOrderByBuyerByPeriod_IncorrectDates_ThrowException_Test()
{
//Arrange
var date = DateTime.UtcNow;
//Act&Assert
Assert.That(() => _orderBusinessLogicContract.GetAllOrderByBuyerByPeriod(Guid.NewGuid().ToString(),
date, date), Throws.TypeOf<IncorrectDatesException>());
Assert.That(() => _orderBusinessLogicContract.GetAllOrderByBuyerByPeriod(Guid.NewGuid().ToString(),
date, date.AddSeconds(-1)), Throws.TypeOf<IncorrectDatesException>());
_orderStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllOrderByBuyerByPeriod_BuyerIdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _orderBusinessLogicContract.GetAllOrderByBuyerByPeriod(null, DateTime.UtcNow,
DateTime.UtcNow.AddDays(1)), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _orderBusinessLogicContract.GetAllOrderByBuyerByPeriod(string.Empty,
DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<ArgumentNullException>());
_orderStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllOrderByBuyerByPeriod_BuyerIdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _orderBusinessLogicContract.GetAllOrderByBuyerByPeriod("buyerId", DateTime.UtcNow,
DateTime.UtcNow.AddDays(1)), Throws.TypeOf<ValidationException>());
_orderStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllOrderByBuyerByPeriod_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _orderBusinessLogicContract.GetAllOrderByBuyerByPeriod(Guid.NewGuid().ToString(),
DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<NullListException>());
_orderStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllOrderByBuyerByPeriod_StorageThrowError_ThrowException_Test()
{
//Arrange
_orderStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
.Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _orderBusinessLogicContract.GetAllOrderByBuyerByPeriod(Guid.NewGuid().ToString(),
DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<StorageException>());
_orderStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllOrderByProductByPeriod_ReturnListOfRecords_Test()
{
//Arrange
var date = DateTime.UtcNow;
var productId = Guid.NewGuid().ToString();
var listOriginal = new List<OrderDataModel>()
{
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, DiscountType.None, false,
[new OrderProductDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]),
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, DiscountType.None, false, []),
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, DiscountType.None, false, []),
};
_orderStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Returns(listOriginal);
//Act
var list = _orderBusinessLogicContract.GetAllOrderByProductByPeriod(productId, date, date.AddDays(1));
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.EquivalentTo(listOriginal));
_orderStorageContract.Verify(x => x.GetList(date, date.AddDays(1), null, productId, null), Times.Once);
}
[Test]
public void GetAllOrderByProductByPeriod_ReturnEmptyList_Test()
{
//Arrange
_orderStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Returns([]);
//Act
var list = _orderBusinessLogicContract.GetAllOrderByProductByPeriod(Guid.NewGuid().ToString(), DateTime.UtcNow,
DateTime.UtcNow.AddDays(1));
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
_orderStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllOrderByProductByPeriod_IncorrectDates_ThrowException_Test()
{
//Arrange
var date = DateTime.UtcNow;
//Act&Assert
Assert.That(() => _orderBusinessLogicContract.GetAllOrderByProductByPeriod(Guid.NewGuid().ToString(), date, date),
Throws.TypeOf<IncorrectDatesException>());
Assert.That(() => _orderBusinessLogicContract.GetAllOrderByProductByPeriod(Guid.NewGuid().ToString(), date,
date.AddSeconds(-1)), Throws.TypeOf<IncorrectDatesException>());
_orderStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllOrderByProductByPeriod_ProductIdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _orderBusinessLogicContract.GetAllOrderByProductByPeriod(null, DateTime.UtcNow,
DateTime.UtcNow.AddDays(1)), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _orderBusinessLogicContract.GetAllOrderByProductByPeriod(string.Empty,
DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<ArgumentNullException>());
_orderStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllOrderByProductByPeriod_ProductIdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _orderBusinessLogicContract.GetAllOrderByProductByPeriod("productId",
DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<ValidationException>());
_orderStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllOrderByProductByPeriod_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _orderBusinessLogicContract.GetAllOrderByProductByPeriod(Guid.NewGuid().ToString(), DateTime.UtcNow,
DateTime.UtcNow.AddDays(1)), Throws.TypeOf<NullListException>());
_orderStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllOrderByProductByPeriod_StorageThrowError_ThrowException_Test()
{
//Arrange
_orderStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
.Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _orderBusinessLogicContract.GetAllOrderByProductByPeriod(Guid.NewGuid().ToString(), DateTime.UtcNow,
DateTime.UtcNow.AddDays(1)), Throws.TypeOf<StorageException>());
_orderStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetOrderByData_GetById_ReturnRecord_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
var record = new OrderDataModel(id, Guid.NewGuid().ToString(), null, DiscountType.None, false,
[new OrderProductDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]);
_orderStorageContract.Setup(x => x.GetElementById(id)).Returns(record);
//Act
var element = _orderBusinessLogicContract.GetOrderByData(id);
//Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.Id, Is.EqualTo(id));
_orderStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetOrderByData_EmptyData_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _orderBusinessLogicContract.GetOrderByData(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _orderBusinessLogicContract.GetOrderByData(string.Empty), Throws.TypeOf<ArgumentNullException>());
_orderStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetOrderByData_IdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _orderBusinessLogicContract.GetOrderByData("saleId"), Throws.TypeOf<ValidationException>());
_orderStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetOrderByData_GetById_NotFoundRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _orderBusinessLogicContract.GetOrderByData(Guid.NewGuid().ToString()),
Throws.TypeOf<ElementNotFoundException>());
_orderStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetOrderByData_StorageThrowError_ThrowException_Test()
{
//Arrange
_orderStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _orderBusinessLogicContract.GetOrderByData(Guid.NewGuid().ToString()),
Throws.TypeOf<StorageException>());
_orderStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void InsertOrder_CorrectRecord_Test()
{
//Arrange
var flag = false;
var record = new OrderDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(),
Guid.NewGuid().ToString(), DiscountType.None, false,
[new OrderProductDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]);
_orderStorageContract.Setup(x => x.AddElement(It.IsAny<OrderDataModel>()))
.Callback((OrderDataModel x) =>
{
flag = x.Id == record.Id && x.BlacksmithId ==
record.BlacksmithId && x.BuyerId == record.BuyerId &&
x.OrderDate == record.OrderDate && x.Sum ==
record.Sum && x.DiscountType == record.DiscountType &&
x.Discount == record.Discount && x.IsCancel ==
record.IsCancel && x.Products.Count == record.Products.Count &&
x.Products.First().ProductId ==
record.Products.First().ProductId &&
x.Products.First().OrderId ==
record.Products.First().OrderId &&
x.Products.First().Count ==
record.Products.First().Count;
});
//Act
_orderBusinessLogicContract.InsertOrder(record);
//Assert
_orderStorageContract.Verify(x => x.AddElement(It.IsAny<OrderDataModel>()), Times.Once);
Assert.That(flag);
}
[Test]
public void InsertOrder_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_orderStorageContract.Setup(x => x.AddElement(It.IsAny<OrderDataModel>()))
.Throws(new ElementExistsException("Data", "Data"));
//Act&Assert
Assert.That(() => _orderBusinessLogicContract.InsertOrder(new(Guid.NewGuid().ToString(),
Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), DiscountType.None, false,
[new OrderProductDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])),
Throws.TypeOf<ElementExistsException>());
_orderStorageContract.Verify(x => x.AddElement(It.IsAny<OrderDataModel>()), Times.Once);
}
[Test]
public void InsertOrder_NullRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _orderBusinessLogicContract.InsertOrder(null), Throws.TypeOf<ArgumentNullException>());
_orderStorageContract.Verify(x => x.AddElement(It.IsAny<OrderDataModel>()), Times.Never);
}
[Test]
public void InsertOrder_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _orderBusinessLogicContract.InsertOrder(new OrderDataModel("id", Guid.NewGuid().ToString(),
Guid.NewGuid().ToString(), DiscountType.None, false, [])), Throws.TypeOf<ValidationException>());
_orderStorageContract.Verify(x => x.AddElement(It.IsAny<OrderDataModel>()), Times.Never);
}
[Test]
public void InsertOrder_StorageThrowError_ThrowException_Test()
{
//Arrange
_orderStorageContract.Setup(x => x.AddElement(It.IsAny<OrderDataModel>()))
.Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _orderBusinessLogicContract.InsertOrder(new(Guid.NewGuid().ToString(),
Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), DiscountType.None, false,
[new OrderProductDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])),
Throws.TypeOf<StorageException>());
_orderStorageContract.Verify(x => x.AddElement(It.IsAny<OrderDataModel>()), Times.Once);
}
[Test]
public void CancelOrder_CorrectRecord_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
var flag = false;
_orderStorageContract.Setup(x => x.DelElement(It.Is((string x) => x == id))).Callback(() => { flag = true; });
//Act
_orderBusinessLogicContract.CancelOrder(id);
//Assert
_orderStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
Assert.That(flag);
}
[Test]
public void CancelOrder_RecordWithIncorrectId_ThrowException_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
_orderStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new ElementNotFoundException(id));
//Act&Assert
Assert.That(() => _orderBusinessLogicContract.CancelOrder(Guid.NewGuid().ToString()),
Throws.TypeOf<ElementNotFoundException>());
_orderStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
}
[Test]
public void CancelOrder_IdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _orderBusinessLogicContract.CancelOrder(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _orderBusinessLogicContract.CancelOrder(string.Empty), Throws.TypeOf<ArgumentNullException>());
_orderStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Never);
}
[Test]
public void CancelOrder_IdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _orderBusinessLogicContract.CancelOrder("id"), Throws.TypeOf<ValidationException>());
_orderStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Never);
}
[Test]
public void CancelOrder_StorageThrowError_ThrowException_Test()
{
//Arrange
_orderStorageContract.Setup(x => x.DelElement(It.IsAny<string>()))
.Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _orderBusinessLogicContract.CancelOrder(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_orderStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
}
}
}

View File

@@ -0,0 +1,525 @@
using TheBlacksmithVakulaContract.BusinessLogicsContracts;
using TheBlacksmithVakulaContract.StoragesContracts;
using TheBlacksmithVakulaBusinessLogic.Implementations;
using TheBlacksmithVakulaContract.DataModels;
using TheBlacksmithVakulaContract.Exceptions;
using TheBlacksmithVakulaContract.Enums;
using Microsoft.Extensions.Logging;
using Moq;
namespace TheBlacksmithVakulaTests.BusinessLogicContractTests
{
[TestFixture]
public class ProductBusinessLogicContractTests
{
private IProductBusinessLogicContract _productBusinessLogicContract;
private Mock<IProductStorageContract> _productStorageContract;
[OneTimeSetUp]
public void OneTimeSetUp()
{
_productStorageContract = new Mock<IProductStorageContract>();
_productBusinessLogicContract = new ProductBusinessLogicContract(_productStorageContract.Object, new Mock<ILogger>().Object);
}
[SetUp]
public void SetUp()
{
_productStorageContract.Reset();
}
[Test]
public void GetAllProducts_ReturnListOfRecords_Test()
{
//Arrange
var listOriginal = new List<ProductDataModel>()
{
new(Guid.NewGuid().ToString(), "name 1", ProductType.Weapon, Guid.NewGuid().ToString(), 10, false),
new(Guid.NewGuid().ToString(), "name 2", ProductType.Weapon, Guid.NewGuid().ToString(), 10, true),
new(Guid.NewGuid().ToString(), "name 3", ProductType.Weapon, Guid.NewGuid().ToString(), 10, false),
};
_productStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string>())).Returns(listOriginal);
//Act
var listOnlyActive = _productBusinessLogicContract.GetAllProducts(true);
var list = _productBusinessLogicContract.GetAllProducts(false);
//Assert
Assert.Multiple(() =>
{
Assert.That(listOnlyActive, Is.Not.Null);
Assert.That(list, Is.Not.Null);
Assert.That(listOnlyActive, Is.EquivalentTo(listOriginal));
Assert.That(list, Is.EquivalentTo(listOriginal));
});
_productStorageContract.Verify(x => x.GetList(true, null), Times.Once);
_productStorageContract.Verify(x => x.GetList(false, null), Times.Once);
}
[Test]
public void GetAllProducts_ReturnEmptyList_Test()
{
//Arrange
_productStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string>())).Returns([]);
//Act
var listOnlyActive = _productBusinessLogicContract.GetAllProducts(true);
var list = _productBusinessLogicContract.GetAllProducts(false);
//Assert
Assert.Multiple(() =>
{
Assert.That(listOnlyActive, Is.Not.Null);
Assert.That(list, Is.Not.Null);
Assert.That(listOnlyActive, Has.Count.EqualTo(0));
Assert.That(list, Has.Count.EqualTo(0));
});
_productStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), null), Times.Exactly(2));
}
[Test]
public void GetAllProducts_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _productBusinessLogicContract.GetAllProducts(It.IsAny<bool>()), Throws.TypeOf<NullListException>());
_productStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllProducts_StorageThrowError_ThrowException_Test()
{
//Arrange
_productStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string>()))
.Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _productBusinessLogicContract.GetAllProducts(It.IsAny<bool>()), Throws.TypeOf<StorageException>());
_productStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllProductsByBillet_ReturnListOfRecords_Test()
{
//Arrange
var billetId = Guid.NewGuid().ToString();
var listOriginal = new List<ProductDataModel>()
{
new(Guid.NewGuid().ToString(), "name 1",ProductType.Weapon, Guid.NewGuid().ToString(), 10, false),
new(Guid.NewGuid().ToString(), "name 2", ProductType.Weapon, Guid.NewGuid().ToString(), 10, true),
new(Guid.NewGuid().ToString(), "name 3", ProductType.Weapon, Guid.NewGuid().ToString(), 10, false),
};
_productStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string>())).Returns(listOriginal);
//Act
var listOnlyActive = _productBusinessLogicContract.GetAllProductsByBillet(billetId, true);
var list = _productBusinessLogicContract.GetAllProductsByBillet(billetId, false);
//Assert
Assert.Multiple(() =>
{
Assert.That(listOnlyActive, Is.Not.Null);
Assert.That(list, Is.Not.Null);
Assert.That(listOnlyActive, Is.EquivalentTo(listOriginal));
Assert.That(list, Is.EquivalentTo(listOriginal));
});
_productStorageContract.Verify(x => x.GetList(true, billetId), Times.Once);
_productStorageContract.Verify(x => x.GetList(false, billetId), Times.Once);
}
[Test]
public void GetAllProductsByBillet_ReturnEmptyList_Test()
{
//Arrange
var billetId = Guid.NewGuid().ToString();
_productStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string>())).Returns([]);
//Act
var listOnlyActive = _productBusinessLogicContract.GetAllProductsByBillet(billetId, true);
var list = _productBusinessLogicContract.GetAllProductsByBillet(billetId, false);
//Assert
Assert.Multiple(() =>
{
Assert.That(listOnlyActive, Is.Not.Null);
Assert.That(list, Is.Not.Null);
Assert.That(listOnlyActive, Has.Count.EqualTo(0));
Assert.That(list, Has.Count.EqualTo(0));
});
_productStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), billetId), Times.Exactly(2));
}
[Test]
public void
GetAllProductsByBillet_BilletIdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _productBusinessLogicContract.GetAllProductsByBillet(null, It.IsAny<bool>()),
Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _productBusinessLogicContract.GetAllProductsByBillet(string.Empty, It.IsAny<bool>()),
Throws.TypeOf<ArgumentNullException>());
_productStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void
GetAllProductsByBillet_BilletIdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _productBusinessLogicContract.GetAllProductsByBillet("billetId", It.IsAny<bool>()),
Throws.TypeOf<ValidationException>());
_productStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllProductsByBillet_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _productBusinessLogicContract.GetAllProductsByBillet(Guid.NewGuid().ToString(), It.IsAny<bool>()),
Throws.TypeOf<NullListException>());
_productStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void
GetAllProductsByBillet_StorageThrowError_ThrowException_Test()
{
//Arrange
_productStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string>()))
.Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _productBusinessLogicContract.GetAllProductsByBillet(Guid.NewGuid().ToString(), It.IsAny<bool>()),
Throws.TypeOf<StorageException>());
_productStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetProductHistoryByProduct_ReturnListOfRecords_Test()
{
//Arrange
var productId = Guid.NewGuid().ToString();
var listOriginal = new List<ProductHistoryDataModel>()
{
new(Guid.NewGuid().ToString(), 10),
new(Guid.NewGuid().ToString(), 15),
new(Guid.NewGuid().ToString(), 10),
};
_productStorageContract.Setup(x => x.GetHistoryByProductId(It.IsAny<string>())).Returns(listOriginal);
//Act
var list = _productBusinessLogicContract.GetProductHistoryByProduct(productId);
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.EquivalentTo(listOriginal));
_productStorageContract.Verify(x => x.GetHistoryByProductId(productId), Times.Once);
}
[Test]
public void GetProductHistoryByProduct_ReturnEmptyList_Test()
{
//Arrange
_productStorageContract.Setup(x => x.GetHistoryByProductId(It.IsAny<string>())).Returns([]);
//Act
var list = _productBusinessLogicContract.GetProductHistoryByProduct(Guid.NewGuid().ToString());
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
_productStorageContract.Verify(x => x.GetHistoryByProductId(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetProductHistoryByProduct_ProductIdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _productBusinessLogicContract.GetProductHistoryByProduct(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _productBusinessLogicContract.GetProductHistoryByProduct(string.Empty),
Throws.TypeOf<ArgumentNullException>());
_productStorageContract.Verify(x => x.GetHistoryByProductId(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetProductHistoryByProduct_ProductIdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _productBusinessLogicContract.GetProductHistoryByProduct("productId"),
Throws.TypeOf<ValidationException>());
_productStorageContract.Verify(x => x.GetHistoryByProductId(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetProductHistoryByProduct_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _productBusinessLogicContract.GetProductHistoryByProduct(Guid.NewGuid().ToString()),
Throws.TypeOf<NullListException>());
_productStorageContract.Verify(x => x.GetHistoryByProductId(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetProductHistoryByProduct_StorageThrowError_ThrowException_Test()
{
//Arrange
_productStorageContract.Setup(x => x.GetHistoryByProductId(It.IsAny<string>()))
.Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _productBusinessLogicContract.GetProductHistoryByProduct(Guid.NewGuid().ToString()),
Throws.TypeOf<StorageException>());
_productStorageContract.Verify(x => x.GetHistoryByProductId(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetProductByData_GetById_ReturnRecord_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
var record = new ProductDataModel(id, "name", ProductType.Weapon, Guid.NewGuid().ToString(), 10, false);
_productStorageContract.Setup(x => x.GetElementById(id)).Returns(record);
//Act
var element = _productBusinessLogicContract.GetProductByData(id);
//Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.Id, Is.EqualTo(id));
_productStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetProductByData_GetByName_ReturnRecord_Test()
{
//Arrange
var name = "name";
var record = new ProductDataModel(Guid.NewGuid().ToString(), name, ProductType.Weapon, Guid.NewGuid().ToString(), 10, false);
_productStorageContract.Setup(x => x.GetElementByName(name)).Returns(record);
//Act
var element = _productBusinessLogicContract.GetProductByData(name);
//Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.ProductName, Is.EqualTo(name));
_productStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetProductByData_EmptyData_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _productBusinessLogicContract.GetProductByData(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _productBusinessLogicContract.GetProductByData(string.Empty), Throws.TypeOf<ArgumentNullException>());
_productStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Never);
_productStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetProductByData_GetById_NotFoundRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _productBusinessLogicContract.GetProductByData(Guid.NewGuid().ToString()),
Throws.TypeOf<ElementNotFoundException>());
_productStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetProductByData_GetByName_NotFoundRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _productBusinessLogicContract.GetProductByData("name"), Throws.TypeOf<ElementNotFoundException>());
_productStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetProductByData_StorageThrowError_ThrowException_Test()
{
//Arrange
_productStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Throws(new StorageException(new InvalidOperationException()));
_productStorageContract.Setup(x => x.GetElementByName(It.IsAny<string>()))
.Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _productBusinessLogicContract.GetProductByData(Guid.NewGuid().ToString()),
Throws.TypeOf<StorageException>());
Assert.That(() => _productBusinessLogicContract.GetProductByData("name"), Throws.TypeOf<StorageException>());
_productStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
_productStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Once);
}
[Test]
public void InsertProduct_CorrectRecord_Test()
{
//Arrange
var flag = false;
var record = new ProductDataModel(Guid.NewGuid().ToString(), "name", ProductType.Weapon,
Guid.NewGuid().ToString(), 10, false);
_productStorageContract.Setup(x => x.AddElement(It.IsAny<ProductDataModel>()))
.Callback((ProductDataModel x) =>
{
flag = x.Id == record.Id && x.ProductName ==
record.ProductName && x.ProductType == record.ProductType &&
x.BilletId == record.BilletId && x.Price ==
record.Price && x.IsDeleted == record.IsDeleted;
});
//Act
_productBusinessLogicContract.InsertProduct(record);
//Assert
_productStorageContract.Verify(x => x.AddElement(It.IsAny<ProductDataModel>()), Times.Once);
Assert.That(flag);
}
[Test]
public void InsertProduct_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_productStorageContract.Setup(x => x.AddElement(It.IsAny<ProductDataModel>()))
.Throws(new ElementExistsException("Data", "Data"));
//Act&Assert
Assert.That(() => _productBusinessLogicContract.InsertProduct(new(Guid.NewGuid().ToString(), "name",
ProductType.Weapon, Guid.NewGuid().ToString(), 10, false)), Throws.TypeOf<ElementExistsException>());
_productStorageContract.Verify(x => x.AddElement(It.IsAny<ProductDataModel>()), Times.Once);
}
[Test]
public void InsertProduct_NullRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _productBusinessLogicContract.InsertProduct(null), Throws.TypeOf<ArgumentNullException>());
_productStorageContract.Verify(x => x.AddElement(It.IsAny<ProductDataModel>()), Times.Never);
}
[Test]
public void InsertProduct_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _productBusinessLogicContract.InsertProduct(new ProductDataModel("id", "name",
ProductType.Weapon, Guid.NewGuid().ToString(), 10, false)), Throws.TypeOf<ValidationException>());
_productStorageContract.Verify(x => x.AddElement(It.IsAny<ProductDataModel>()), Times.Never);
}
[Test]
public void InsertProduct_StorageThrowError_ThrowException_Test()
{
//Arrange
_productStorageContract.Setup(x => x.AddElement(It.IsAny<ProductDataModel>()))
.Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _productBusinessLogicContract.InsertProduct(new(Guid.NewGuid().ToString(), "name",
ProductType.Weapon, Guid.NewGuid().ToString(), 10, false)), Throws.TypeOf<StorageException>());
_productStorageContract.Verify(x => x.AddElement(It.IsAny<ProductDataModel>()), Times.Once);
}
[Test]
public void UpdateProduct_CorrectRecord_Test()
{
//Arrange
var flag = false;
var record = new ProductDataModel(Guid.NewGuid().ToString(), "name", ProductType.Weapon,
Guid.NewGuid().ToString(), 10, false);
_productStorageContract.Setup(x => x.UpdElement(It.IsAny<ProductDataModel>()))
.Callback((ProductDataModel x) =>
{
flag = x.Id == record.Id && x.ProductName ==
record.ProductName && x.ProductType == record.ProductType &&
x.BilletId == record.BilletId && x.Price ==
record.Price && x.IsDeleted == record.IsDeleted;
});
//Act
_productBusinessLogicContract.UpdateProduct(record);
//Assert
_productStorageContract.Verify(x => x.UpdElement(It.IsAny<ProductDataModel>()), Times.Once);
Assert.That(flag);
}
[Test]
public void UpdateProduct_RecordWithIncorrectData_ThrowException_Test()
{
//Arrange
_productStorageContract.Setup(x => x.UpdElement(It.IsAny<ProductDataModel>())).Throws(new ElementNotFoundException(""));
//Act&Assert
Assert.That(() => _productBusinessLogicContract.UpdateProduct(new(Guid.NewGuid().ToString(), "name",
ProductType.Weapon, Guid.NewGuid().ToString(), 10, false)), Throws.TypeOf<ElementNotFoundException>());
_productStorageContract.Verify(x => x.UpdElement(It.IsAny<ProductDataModel>()), Times.Once);
}
[Test]
public void UpdateProduct_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_productStorageContract.Setup(x => x.UpdElement(It.IsAny<ProductDataModel>()))
.Throws(new ElementExistsException("Data", "Data"));
//Act&Assert
Assert.That(() => _productBusinessLogicContract.UpdateProduct(new(Guid.NewGuid().ToString(), "name",
ProductType.Weapon, Guid.NewGuid().ToString(), 10, false)), Throws.TypeOf<ElementExistsException>());
_productStorageContract.Verify(x => x.UpdElement(It.IsAny<ProductDataModel>()), Times.Once);
}
[Test]
public void UpdateProduct_NullRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _productBusinessLogicContract.UpdateProduct(null), Throws.TypeOf<ArgumentNullException>());
_productStorageContract.Verify(x => x.UpdElement(It.IsAny<ProductDataModel>()), Times.Never);
}
[Test]
public void UpdateProduct_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _productBusinessLogicContract.UpdateProduct(new ProductDataModel("id", "name",
ProductType.Weapon, Guid.NewGuid().ToString(), 10, false)), Throws.TypeOf<ValidationException>());
_productStorageContract.Verify(x => x.UpdElement(It.IsAny<ProductDataModel>()), Times.Never);
}
[Test]
public void UpdateProduct_StorageThrowError_ThrowException_Test()
{
//Arrange
_productStorageContract.Setup(x => x.UpdElement(It.IsAny<ProductDataModel>()))
.Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _productBusinessLogicContract.UpdateProduct(new(Guid.NewGuid().ToString(), "name",
ProductType.Weapon, Guid.NewGuid().ToString(), 10, false)), Throws.TypeOf<StorageException>());
_productStorageContract.Verify(x => x.UpdElement(It.IsAny<ProductDataModel>()), Times.Once);
}
[Test]
public void DeleteProduct_CorrectRecord_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
var flag = false;
_productStorageContract.Setup(x => x.DelElement(It.Is((string x) => x == id))).Callback(() => { flag = true; });
//Act
_productBusinessLogicContract.DeleteProduct(id);
//Assert
_productStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
Assert.That(flag);
}
[Test]
public void DeleteProduct_RecordWithIncorrectId_ThrowException_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
_productStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new ElementNotFoundException(id));
//Act&Assert
Assert.That(() => _productBusinessLogicContract.DeleteProduct(Guid.NewGuid().ToString()),
Throws.TypeOf<ElementNotFoundException>());
_productStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
}
[Test]
public void DeleteProduct_IdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _productBusinessLogicContract.DeleteProduct(null),
Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _productBusinessLogicContract.DeleteProduct(string.Empty), Throws.TypeOf<ArgumentNullException>());
_productStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Never);
}
[Test]
public void DeleteProduct_IdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _productBusinessLogicContract.DeleteProduct("id"), Throws.TypeOf<ValidationException>());
_productStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Never);
}
[Test]
public void DeleteProduct_StorageThrowError_ThrowException_Test()
{
//Arrange
_productStorageContract.Setup(x => x.DelElement(It.IsAny<string>()))
.Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _productBusinessLogicContract.DeleteProduct(Guid.NewGuid().ToString()),
Throws.TypeOf<StorageException>());
_productStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
}
}
}

View File

@@ -0,0 +1,475 @@
using TheBlacksmithVakulaBusinessLogic.Implementations;
using TheBlacksmithVakulaContract.BusinessLogicsContracts;
using TheBlacksmithVakulaContract.StoragesContracts;
using TheBlacksmithVakulaContract.Exceptions;
using TheBlacksmithVakulaContract.DataModels;
using TheBlacksmithVakulaContract.Enums;
using Microsoft.Extensions.Logging;
using Moq;
namespace TheBlacksmithVakulaTests.BusinessLogicContractTests
{
[TestFixture]
public class RankBusinessLogicContractTests
{
private IRankBusinessLogicContract _rankBusinessLogicContract;
private Mock<IRankStorageContract> _rankStorageContract;
[OneTimeSetUp]
public void OneTimeSetUp()
{
_rankStorageContract = new Mock<IRankStorageContract>();
_rankBusinessLogicContract = new RankBusinessLogicContract(_rankStorageContract.Object, new Mock<ILogger>().Object);
}
[SetUp]
public void SetUp()
{
_rankStorageContract.Reset();
}
[Test]
public void GetAllRanks_ReturnListOfRecords_Test()
{
//Arrange
var listOriginal = new List<RankDataModel>()
{
new(Guid.NewGuid().ToString(),"name 1", RankType.Student),
new(Guid.NewGuid().ToString(),"name 2", RankType.Student),
new(Guid.NewGuid().ToString(),"name 3", RankType.Student),
};
_rankStorageContract.Setup(x => x.GetList()).Returns(listOriginal);
//Act
var listAll = _rankBusinessLogicContract.GetAllRanks();
//Assert
Assert.Multiple(() =>
{
Assert.That(listAll, Is.Not.Null);
Assert.That(listAll, Is.EquivalentTo(listOriginal));
});
_rankStorageContract.Verify(x => x.GetList(), Times.Once);
}
[Test]
public void GetAllRanks_ReturnEmptyList_Test()
{
//Arrange
_rankStorageContract.Setup(x => x.GetList()).Returns([]);
//Act
var listAll = _rankBusinessLogicContract.GetAllRanks();
//Assert
Assert.Multiple(() =>
{
Assert.That(listAll, Is.Not.Null);
Assert.That(listAll, Has.Count.EqualTo(0));
});
}
[Test]
public void GetAllRanks_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _rankBusinessLogicContract.GetAllRanks(), Throws.TypeOf<NullListException>());
_rankStorageContract.Verify(x => x.GetList(), Times.Once);
}
[Test]
public void GetAllRanks_StorageThrowError_ThrowException_Test()
{
//Arrange
_rankStorageContract.Setup(x => x.GetList()).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _rankBusinessLogicContract.GetAllRanks(),
Throws.TypeOf<StorageException>()); _rankStorageContract.Verify(x => x.GetList(), Times.Once);
}
[Test]
public void GetAllDataOfRank_ReturnListOfRecords_Test()
{
//Arrange
var rankId = Guid.NewGuid().ToString();
var listOriginal = new List<RankDataModel>()
{
new(rankId,"name 1", RankType.Student),
new(rankId, "name 2", RankType.Student)
};
_rankStorageContract.Setup(x => x.GetRankWithHistory(It.IsAny<string>())).Returns(listOriginal);
//Act
var list = _rankBusinessLogicContract.GetAllDataOfRank(rankId);
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(2));
_rankStorageContract.Verify(x => x.GetRankWithHistory(rankId), Times.Once);
}
[Test]
public void GetAllDataOfRank_ReturnEmptyList_Test()
{
//Arrange
_rankStorageContract.Setup(x => x.GetRankWithHistory(It.IsAny<string>())).Returns([]);
//Act
var list = _rankBusinessLogicContract.GetAllDataOfRank(Guid.NewGuid().ToString());
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
_rankStorageContract.Verify(x => x.GetRankWithHistory(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllDataOfRank_RankIdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _rankBusinessLogicContract.GetAllDataOfRank(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _rankBusinessLogicContract.GetAllDataOfRank(string.Empty), Throws.TypeOf<ArgumentNullException>());
_rankStorageContract.Verify(x => x.GetRankWithHistory(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllDataOfRank_RankIdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _rankBusinessLogicContract.GetAllDataOfRank("id"), Throws.TypeOf<ValidationException>());
_rankStorageContract.Verify(x => x.GetRankWithHistory(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllDataOfRank_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _rankBusinessLogicContract.GetAllDataOfRank(Guid.NewGuid().ToString()),
Throws.TypeOf<NullListException>());
_rankStorageContract.Verify(x => x.GetRankWithHistory(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllDataOfRank_StorageThrowError_ThrowException_Test()
{
//Arrange
_rankStorageContract.Setup(x => x.GetRankWithHistory(It.IsAny<string>()))
.Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _rankBusinessLogicContract.GetAllDataOfRank(Guid.NewGuid().ToString()),
Throws.TypeOf<StorageException>());
_rankStorageContract.Verify(x => x.GetRankWithHistory(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetRankByData_GetById_ReturnRecord_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
var record = new RankDataModel(id, "name", RankType.Student);
_rankStorageContract.Setup(x => x.GetElementById(id)).Returns(record);
//Act
var element = _rankBusinessLogicContract.GetRankByData(id);
//Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.Id, Is.EqualTo(id));
_rankStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetRankByData_GetByName_ReturnRecord_Test()
{
//Arrange
var rankName = "name";
var record = new RankDataModel(Guid.NewGuid().ToString(), rankName, RankType.Student);
_rankStorageContract.Setup(x => x.GetElementByName(rankName)).Returns(record);
//Act
var element = _rankBusinessLogicContract.GetRankByData(rankName);
//Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.RankName, Is.EqualTo(rankName));
_rankStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetRankByData_EmptyData_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _rankBusinessLogicContract.GetRankByData(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _rankBusinessLogicContract.GetRankByData(string.Empty), Throws.TypeOf<ArgumentNullException>());
_rankStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Never);
_rankStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetRankByData_GetById_NotFoundRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _rankBusinessLogicContract.GetRankByData(Guid.NewGuid().ToString()),
Throws.TypeOf<ElementNotFoundException>());
_rankStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
_rankStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetRankByData_GetByName_NotFoundRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _rankBusinessLogicContract.GetRankByData("name"), Throws.TypeOf<ElementNotFoundException>());
_rankStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Never);
_rankStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetRankByData_StorageThrowError_ThrowException_Test()
{
//Arrange
_rankStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Throws(new StorageException(new InvalidOperationException()));
_rankStorageContract.Setup(x => x.GetElementByName(It.IsAny<string>()))
.Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _rankBusinessLogicContract.GetRankByData(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
Assert.That(() => _rankBusinessLogicContract.GetRankByData("name"), Throws.TypeOf<StorageException>());
_rankStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
_rankStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Once);
}
[Test]
public void InsertRank_CorrectRecord_Test()
{
//Arrange
var flag = false;
var record = new RankDataModel(Guid.NewGuid().ToString(), "name", RankType.Student);
_rankStorageContract.Setup(x => x.AddElement(It.IsAny<RankDataModel>()))
.Callback((RankDataModel x) =>
{
flag = x.Id == record.Id && x.RankName ==
record.RankName && x.RankType == record.RankType;
});
//Act
_rankBusinessLogicContract.InsertRank(record);
//Assert
_rankStorageContract.Verify(x => x.AddElement(It.IsAny<RankDataModel>()), Times.Once);
Assert.That(flag);
}
[Test]
public void InsertRank_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_rankStorageContract.Setup(x => x.AddElement(It.IsAny<RankDataModel>()))
.Throws(new ElementExistsException("Data", "Data"));
//Act&Assert
Assert.That(() =>
_rankBusinessLogicContract.InsertRank(new(Guid.NewGuid().ToString(), "name", RankType.Student)),
Throws.TypeOf<ElementExistsException>());
_rankStorageContract.Verify(x => x.AddElement(It.IsAny<RankDataModel>()), Times.Once);
}
[Test]
public void InsertRank_NullRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _rankBusinessLogicContract.InsertRank(null), Throws.TypeOf<ArgumentNullException>());
_rankStorageContract.Verify(x => x.AddElement(It.IsAny<RankDataModel>()), Times.Never);
}
[Test]
public void InsertRank_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _rankBusinessLogicContract
.InsertRank(new RankDataModel("id", "name", RankType.Student)),
Throws.TypeOf<ValidationException>());
_rankStorageContract.Verify(x => x.AddElement(It.IsAny<RankDataModel>()), Times.Never);
}
[Test]
public void InsertRank_StorageThrowError_ThrowException_Test()
{
//Arrange
_rankStorageContract.Setup(x => x.AddElement(It.IsAny<RankDataModel>()))
.Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _rankBusinessLogicContract
.InsertRank(new(Guid.NewGuid().ToString(), "name", RankType.Student)),
Throws.TypeOf<StorageException>());
_rankStorageContract.Verify(x => x.AddElement(It.IsAny<RankDataModel>()), Times.Once);
}
[Test]
public void UpdateRank_CorrectRecord_Test()
{
//Arrange
var flag = false;
var record = new RankDataModel(Guid.NewGuid().ToString(), "name", RankType.Student);
_rankStorageContract.Setup(x => x.UpdElement(It.IsAny<RankDataModel>()))
.Callback((RankDataModel x) =>
{
flag = x.Id == record.Id && x.RankName ==
record.RankName && x.RankType == record.RankType;
});
//Act
_rankBusinessLogicContract.UpdateRank(record);
//Assert
_rankStorageContract.Verify(x => x.UpdElement(It.IsAny<RankDataModel>()), Times.Once); Assert.That(flag);
}
[Test]
public void UpdateRank_RecordWithIncorrectData_ThrowException_Test()
{
//Arrange
_rankStorageContract.Setup(x => x.UpdElement(It.IsAny<RankDataModel>())).Throws(new ElementNotFoundException(""));
//Act&Assert
Assert.That(() => _rankBusinessLogicContract
.UpdateRank(new(Guid.NewGuid().ToString(), "name 1", RankType.Student)),
Throws.TypeOf<ElementNotFoundException>());
_rankStorageContract.Verify(x => x.UpdElement(It.IsAny<RankDataModel>()), Times.Once);
}
[Test]
public void UpdateRank_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_rankStorageContract.Setup(x => x.UpdElement(It.IsAny<RankDataModel>()))
.Throws(new ElementExistsException("Data", "Data"));
//Act&Assert
Assert.That(() => _rankBusinessLogicContract
.UpdateRank(new(Guid.NewGuid().ToString(), "name", RankType.Student)),
Throws.TypeOf<ElementExistsException>());
_rankStorageContract.Verify(x => x.UpdElement(It.IsAny<RankDataModel>()), Times.Once);
}
[Test]
public void UpdateRank_NullRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _rankBusinessLogicContract.UpdateRank(null), Throws.TypeOf<ArgumentNullException>());
_rankStorageContract.Verify(x => x.UpdElement(It.IsAny<RankDataModel>()), Times.Never);
}
[Test]
public void UpdateRank_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _rankBusinessLogicContract
.UpdateRank(new RankDataModel("id", "name", RankType.Student)),
Throws.TypeOf<ValidationException>());
_rankStorageContract.Verify(x => x.UpdElement(It.IsAny<RankDataModel>()), Times.Never);
}
[Test]
public void UpdateRank_StorageThrowError_ThrowException_Test()
{
//Arrange
_rankStorageContract.Setup(x => x.UpdElement(It.IsAny<RankDataModel>()))
.Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _rankBusinessLogicContract
.UpdateRank(new(Guid.NewGuid().ToString(), "name", RankType.Student)),
Throws.TypeOf<StorageException>());
_rankStorageContract.Verify(x => x.UpdElement(It.IsAny<RankDataModel>()), Times.Once);
}
[Test]
public void DeleteRank_CorrectRecord_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
var flag = false;
_rankStorageContract.Setup(x => x.DelElement(It.Is((string x) => x == id))).Callback(() => { flag = true; });
//Act
_rankBusinessLogicContract.DeleteRank(id);
//Assert
_rankStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
Assert.That(flag);
}
[Test]
public void DeleteRank_RecordWithIncorrectId_ThrowException_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
_rankStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new ElementNotFoundException(id));
//Act&Assert
Assert.That(() => _rankBusinessLogicContract.DeleteRank(Guid.NewGuid().ToString()),
Throws.TypeOf<ElementNotFoundException>());
_rankStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
}
[Test]
public void DeleteRank_IdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _rankBusinessLogicContract.DeleteRank(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _rankBusinessLogicContract.DeleteRank(string.Empty), Throws.TypeOf<ArgumentNullException>());
_rankStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Never);
}
[Test]
public void DeleteRank_IdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _rankBusinessLogicContract.DeleteRank("id"), Throws.TypeOf<ValidationException>());
_rankStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Never);
}
[Test]
public void DeleteRank_StorageThrowError_ThrowException_Test()
{
//Arrange
_rankStorageContract.Setup(x => x.DelElement(It.IsAny<string>()))
.Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _rankBusinessLogicContract.DeleteRank(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_rankStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
}
[Test]
public void RestoreRank_CorrectRecord_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
var flag = false;
_rankStorageContract.Setup(x => x.ResElement(It.Is((string x) => x == id))).Callback(() => { flag = true; });
//Act
_rankBusinessLogicContract.RestoreRank(id);
//Assert
_rankStorageContract.Verify(x => x.ResElement(It.IsAny<string>()), Times.Once);
Assert.That(flag);
}
[Test]
public void RestoreRank_RecordWithIncorrectId_ThrowException_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
_rankStorageContract.Setup(x => x.ResElement(It.IsAny<string>())).Throws(new ElementNotFoundException(id));
//Act&Assert
Assert.That(() => _rankBusinessLogicContract.RestoreRank(Guid.NewGuid().ToString()),
Throws.TypeOf<ElementNotFoundException>());
_rankStorageContract.Verify(x => x.ResElement(It.IsAny<string>()), Times.Once);
}
[Test]
public void RestoreRank_IdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _rankBusinessLogicContract.RestoreRank(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _rankBusinessLogicContract.RestoreRank(string.Empty), Throws.TypeOf<ArgumentNullException>());
_rankStorageContract.Verify(x => x.ResElement(It.IsAny<string>()), Times.Never);
}
[Test]
public void RestoreRank_IdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _rankBusinessLogicContract.RestoreRank("id"), Throws.TypeOf<ValidationException>());
_rankStorageContract.Verify(x => x.ResElement(It.IsAny<string>()), Times.Never);
}
[Test]
public void RestoreRank_StorageThrowError_ThrowException_Test()
{
//Arrange
_rankStorageContract.Setup(x => x.ResElement(It.IsAny<string>()))
.Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _rankBusinessLogicContract.RestoreRank(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_rankStorageContract.Verify(x => x.ResElement(It.IsAny<string>()), Times.Once);
}
}
}

View File

@@ -0,0 +1,321 @@
using TheBlacksmithVakulaBusinessLogic.Implementations;
using TheBlacksmithVakulaContract.BusinessLogicsContracts;
using TheBlacksmithVakulaContract.DataModels;
using TheBlacksmithVakulaContract.Enums;
using TheBlacksmithVakulaContract.Exceptions;
using TheBlacksmithVakulaContract.StoragesContracts;
using Microsoft.Extensions.Logging;
using Moq;
namespace TheBlacksmithVakulaTests.BusinessLogicContractTests
{
[TestFixture]
public class SalaryBusinessLogicContractTests
{
private ISalaryBusinessLogicContract _salaryBusinessLogicContract;
private Mock<ISalaryStorageContract> _salaryStorageContract;
private Mock<IOrderStorageContract> _orderStorageContract;
private Mock<IRankStorageContract> _rankStorageContract;
private Mock<IBlacksmithStorageContract> _blacksmithStorageContract;
[OneTimeSetUp]
public void OneTimeSetUp()
{
_salaryStorageContract = new Mock<ISalaryStorageContract>();
_orderStorageContract = new Mock<IOrderStorageContract>();
_rankStorageContract = new Mock<IRankStorageContract>();
_blacksmithStorageContract = new Mock<IBlacksmithStorageContract>();
_salaryBusinessLogicContract = new SalaryBusinessLogicContract(_salaryStorageContract.Object,
_orderStorageContract.Object, _blacksmithStorageContract.Object, new Mock<ILogger>().Object);
}
[SetUp]
public void SetUp()
{
_salaryStorageContract.Reset();
_orderStorageContract.Reset();
_rankStorageContract.Reset();
_blacksmithStorageContract.Reset();
}
[Test]
public void GetAllSalaries_ReturnListOfRecords_Test()
{
//Arrange
var startDate = DateTime.UtcNow;
var endDate = DateTime.UtcNow.AddDays(1);
var listOriginal = new List<SalaryDataModel>()
{
new(Guid.NewGuid().ToString(), DateTime.UtcNow, 10),
new(Guid.NewGuid().ToString(), DateTime.UtcNow.AddDays(1), 14),
new(Guid.NewGuid().ToString(), DateTime.UtcNow.AddDays(-1), 30),
};
_salaryStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>()))
.Returns(listOriginal);
//Act
var list = _salaryBusinessLogicContract.GetAllSalariesByPeriod(startDate, endDate);
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.EquivalentTo(listOriginal));
_salaryStorageContract.Verify(x => x.GetList(startDate, endDate, null), Times.Once);
}
[Test]
public void GetAllSalaries_ReturnEmptyList_Test()
{
//Arrange
_salaryStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>())).Returns([]);
//Act
var list = _salaryBusinessLogicContract.GetAllSalariesByPeriod(DateTime.UtcNow, DateTime.UtcNow.AddDays(1));
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
_salaryStorageContract.Verify(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSalaries_IncorrectDates_ThrowException_Test()
{
//Arrange
var dateTime = DateTime.UtcNow;
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.GetAllSalariesByPeriod(dateTime, dateTime),
Throws.TypeOf<IncorrectDatesException>());
Assert.That(() => _salaryBusinessLogicContract.GetAllSalariesByPeriod(dateTime, dateTime.AddSeconds(-1)),
Throws.TypeOf<IncorrectDatesException>());
_salaryStorageContract.Verify(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSalaries_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.GetAllSalariesByPeriod(DateTime.UtcNow, DateTime.UtcNow.AddDays(1)),
Throws.TypeOf<NullListException>());
_salaryStorageContract.Verify(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSalaries_StorageThrowError_ThrowException_Test()
{
//Arrange
_salaryStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>()))
.Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.GetAllSalariesByPeriod(DateTime.UtcNow, DateTime.UtcNow.AddDays(1)),
Throws.TypeOf<StorageException>());
_salaryStorageContract.Verify(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSalariesByBlacksmith_ReturnListOfRecords_Test()
{
//Arrange
var startDate = DateTime.UtcNow;
var endDate = DateTime.UtcNow.AddDays(1);
var blacksmithId = Guid.NewGuid().ToString();
var listOriginal = new List<SalaryDataModel>()
{
new(Guid.NewGuid().ToString(), DateTime.UtcNow, 10),
new(Guid.NewGuid().ToString(), DateTime.UtcNow.AddDays(1), 14),
new(Guid.NewGuid().ToString(), DateTime.UtcNow.AddDays(-1), 30),
};
_salaryStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(),
It.IsAny<DateTime>(), It.IsAny<string>())).Returns(listOriginal);
//Act
var list = _salaryBusinessLogicContract.GetAllSalariesByPeriodByBlacksmith(startDate, endDate, blacksmithId);
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.EquivalentTo(listOriginal));
_salaryStorageContract.Verify(x => x.GetList(startDate, endDate, blacksmithId), Times.Once);
}
[Test]
public void GetAllSalariesByBlacksmith_ReturnEmptyList_Test()
{
//Arrange
_salaryStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>())).Returns([]);
//Act
var list = _salaryBusinessLogicContract.GetAllSalariesByPeriodByBlacksmith(DateTime.UtcNow, DateTime.UtcNow.AddDays(1),
Guid.NewGuid().ToString());
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
_salaryStorageContract.Verify(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSalariesByBlacksmith_IncorrectDates_ThrowException_Test()
{
//Arrange
var dateTime = DateTime.UtcNow;
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.GetAllSalariesByPeriodByBlacksmith(dateTime, dateTime,
Guid.NewGuid().ToString()), Throws.TypeOf<IncorrectDatesException>());
Assert.That(() => _salaryBusinessLogicContract.GetAllSalariesByPeriodByBlacksmith(dateTime, dateTime.AddSeconds(-1),
Guid.NewGuid().ToString()), Throws.TypeOf<IncorrectDatesException>());
_salaryStorageContract.Verify(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSalariesByBlacksmith_BlacksmithIdIsNUllOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.GetAllSalariesByPeriodByBlacksmith(DateTime.UtcNow,
DateTime.UtcNow.AddDays(1), null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _salaryBusinessLogicContract.GetAllSalariesByPeriodByBlacksmith(DateTime.UtcNow,
DateTime.UtcNow.AddDays(1), string.Empty), Throws.TypeOf<ArgumentNullException>());
_salaryStorageContract.Verify(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSalariesByBlacksmith_BlacksmithIdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.GetAllSalariesByPeriodByBlacksmith(DateTime.UtcNow,
DateTime.UtcNow.AddDays(1), "blacksmithId"), Throws.TypeOf<ValidationException>());
_salaryStorageContract.Verify(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSalariesByBlacksmith_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.GetAllSalariesByPeriodByBlacksmith(DateTime.UtcNow,
DateTime.UtcNow.AddDays(1), Guid.NewGuid().ToString()), Throws.TypeOf<NullListException>());
_salaryStorageContract.Verify(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSalariesByBlacksmith_StorageThrowError_ThrowException_Test()
{
//Arrange
_salaryStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(),
It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.GetAllSalariesByPeriodByBlacksmith(DateTime.UtcNow,
DateTime.UtcNow.AddDays(1), Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_salaryStorageContract.Verify(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void CalculateSalaryByMounth_CalculateSalary_Test()
{
//Arrange
var blacksmithId = Guid.NewGuid().ToString();
var orderSum = 2000.0;
_orderStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(),
It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns([new OrderDataModel(Guid.NewGuid().ToString(), blacksmithId, null, DiscountType.None, false, [new OrderProductDataModel("110", "22", 2)])]);
_blacksmithStorageContract.Setup(x => x.GetList(It.IsAny<bool>(),
It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Returns([new BlacksmithDataModel(blacksmithId, "Test", Guid.NewGuid().ToString(),
DateTime.UtcNow, DateTime.UtcNow, false)]);
var sum = 0.0;
var expectedSum = orderSum * 0.5;
_salaryStorageContract.Setup(x => x.AddElement(It.IsAny<SalaryDataModel>()))
.Callback((SalaryDataModel x) =>
{
sum = x.Salary;
});
//Act
_salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow);
//Assert
Assert.That(sum, Is.EqualTo(expectedSum));
}
[Test]
public void CalculateSalaryByMounth_WithSeveralBlacksmiths_Test()
{
//Arrange
var blacksmith1Id = Guid.NewGuid().ToString();
var blacksmith2Id = Guid.NewGuid().ToString();
var blacksmith3Id = Guid.NewGuid().ToString();
var list = new List<BlacksmithDataModel>()
{
new(blacksmith1Id, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false),
new(blacksmith2Id, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false),
new(blacksmith3Id, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)
};
_orderStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(),
It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns([new OrderDataModel(Guid.NewGuid().ToString(), blacksmith1Id, null, DiscountType.None, false, []),
new OrderDataModel(Guid.NewGuid().ToString(), blacksmith1Id, null, DiscountType.None, false, []),
new OrderDataModel(Guid.NewGuid().ToString(), blacksmith2Id, null, DiscountType.None, false, []),
new OrderDataModel(Guid.NewGuid().ToString(), blacksmith3Id, null, DiscountType.None, false, []),
new OrderDataModel(Guid.NewGuid().ToString(), blacksmith3Id, null, DiscountType.None, false, [])]);
_rankStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new RankDataModel(Guid.NewGuid().ToString(), "name", RankType.Student));
_blacksmithStorageContract.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
_salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow);
//Assert
_salaryStorageContract.Verify(x => x.AddElement(It.IsAny<SalaryDataModel>()), Times.Exactly(list.Count));
}
[Test]
public void CalculateSalaryByMounth_OrderStorageReturnNull_ThrowException_Test()
{
//Arrange
var blacksmithId = Guid.NewGuid().ToString();
_rankStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new RankDataModel(Guid.NewGuid().ToString(), "name", RankType.Student));
_blacksmithStorageContract.Setup(x => x.GetList(It.IsAny<bool>(),
It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Returns([new BlacksmithDataModel(blacksmithId, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)]);
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow), Throws.TypeOf<NullListException>());
}
[Test]
public void CalculateSalaryByMounth_BlacksmithStorageReturnNull_ThrowException_Test()
{
//Arrange
var blacksmithId = Guid.NewGuid().ToString();
_orderStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(),
It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns([new OrderDataModel(Guid.NewGuid().ToString(), blacksmithId, null, DiscountType.None, false, [])]);
_rankStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new RankDataModel(Guid.NewGuid().ToString(), "name", RankType.Student));
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow), Throws.TypeOf<NullListException>());
}
[Test]
public void CalculateSalaryByMounth_OrderStorageThrowException_ThrowException_Test()
{
//Arrange
var blacksmithId = Guid.NewGuid().ToString();
_orderStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(),
It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
.Throws(new StorageException(new InvalidOperationException()));
_rankStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new RankDataModel(Guid.NewGuid().ToString(), "name", RankType.Student));
_blacksmithStorageContract.Setup(x => x.GetList(It.IsAny<bool>(),
It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Returns([new BlacksmithDataModel(blacksmithId, "Test", Guid.NewGuid().ToString(),
DateTime.UtcNow, DateTime.UtcNow, false)]);
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow), Throws.TypeOf<StorageException>());
}
[Test]
public void CalculateSalaryByMounth_BlacksmithStorageThrowException_ThrowException_Test()
{
//Arrange
var blacksmithId = Guid.NewGuid().ToString();
_orderStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(),
It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns([new OrderDataModel(Guid.NewGuid().ToString(), blacksmithId, null, DiscountType.None, false, [])]);
_rankStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new RankDataModel(Guid.NewGuid().ToString(), "name", RankType.Student));
_blacksmithStorageContract.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
Assert.That(() => _salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow), Throws.TypeOf<StorageException>());
}
}
}

View File

@@ -1,5 +1,5 @@
using System.ComponentModel.DataAnnotations;
using TheBlacksmithVakulaContract.DataModels;
using TheBlacksmithVakulaContract.DataModels;
using TheBlacksmithVakulaContract.Exceptions;
namespace TheBlacksmithVakulaTests.DataModelsTests
{

View File

@@ -107,7 +107,7 @@ namespace TheBlacksmithVakulaTests.DataModelsTests
private static OrderDataModel CreateDataModel(string? id, string? blacksmithId,
string? buyerId, double sum, DiscountType discountType, double discount, bool
isCancel, List<OrderProductDataModel>? products) =>
new(id, blacksmithId, buyerId, sum, discountType, discount, isCancel, products);
new(id, blacksmithId, buyerId, sum, discountType, discount, isCancel, products, null, null);
private static List<OrderProductDataModel> CreateSubDataModel() =>
[new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 1)];

View File

@@ -1,6 +1,6 @@
using System.ComponentModel.DataAnnotations;
using TheBlacksmithVakulaContract.DataModels;
using TheBlacksmithVakulaContract.DataModels;
using TheBlacksmithVakulaContract.Enums;
using TheBlacksmithVakulaContract.Exceptions;
namespace TheBlacksmithVakulaTests.DataModelsTests
{
@@ -10,57 +10,32 @@ namespace TheBlacksmithVakulaTests.DataModelsTests
[Test]
public void IdIsNullOrEmptyTest()
{
var rank = CreateDataModel(null, Guid.NewGuid().ToString(), "name",
RankType.Student, true, DateTime.UtcNow);
var rank = CreateDataModel(null, "name", RankType.Student);
Assert.That(() => rank.Validate(), Throws.TypeOf<ValidationException>());
rank = CreateDataModel(string.Empty, Guid.NewGuid().ToString(),
"name", RankType.Student, true, DateTime.UtcNow);
rank = CreateDataModel(string.Empty, "name", RankType.Student);
Assert.That(() => rank.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void IdIsNotGuidTest()
{
var post = CreateDataModel("id", Guid.NewGuid().ToString(), "name",
RankType.Student, true, DateTime.UtcNow);
var post = CreateDataModel("id", "name", RankType.Student);
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void RankIdIsNullEmptyTest()
{
var rank = CreateDataModel(Guid.NewGuid().ToString(), null, "name",
RankType.Student, true, DateTime.UtcNow);
Assert.That(() => rank.Validate(), Throws.TypeOf<ValidationException>());
rank = CreateDataModel(Guid.NewGuid().ToString(), string.Empty,
"name", RankType.Student, true, DateTime.UtcNow);
Assert.That(() => rank.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void RankIdIsNotGuidTest()
{
var rank = CreateDataModel(Guid.NewGuid().ToString(), "rankId",
"name", RankType.Student, true, DateTime.UtcNow);
Assert.That(() => rank.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void RankNameIsEmptyTest()
{
var rank = CreateDataModel(Guid.NewGuid().ToString(),
Guid.NewGuid().ToString(), null, RankType.Student, true, DateTime.UtcNow);
var rank = CreateDataModel(Guid.NewGuid().ToString(), null, RankType.Student);
Assert.That(() => rank.Validate(), Throws.TypeOf<ValidationException>());
rank = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(),
string.Empty, RankType.Student, true, DateTime.UtcNow);
rank = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, RankType.Student);
Assert.That(() => rank.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void RankTypeIsNoneTest()
{
var rank = CreateDataModel(Guid.NewGuid().ToString(),
Guid.NewGuid().ToString(), "name", RankType.None, true, DateTime.UtcNow);
var rank = CreateDataModel(Guid.NewGuid().ToString(), "name", RankType.None);
Assert.That(() => rank.Validate(), Throws.TypeOf<ValidationException>());
}
@@ -71,23 +46,17 @@ namespace TheBlacksmithVakulaTests.DataModelsTests
var rankId = Guid.NewGuid().ToString();
var rankName = "name";
var rankType = RankType.Student;
var isActual = false;
var changeDate = DateTime.UtcNow.AddDays(-1);
var rank = CreateDataModel(id, rankId, rankName, rankType, isActual, changeDate);
var rank = CreateDataModel(id, rankName, rankType);
Assert.That(() => rank.Validate(), Throws.Nothing);
Assert.Multiple(() =>
{
Assert.That(rank.Id, Is.EqualTo(id));
Assert.That(rank.RankId, Is.EqualTo(rankId));
Assert.That(rank.RankName, Is.EqualTo(rankName));
Assert.That(rank.RankType, Is.EqualTo(rankType));
Assert.That(rank.IsActual, Is.EqualTo(isActual));
Assert.That(rank.ChangeDate, Is.EqualTo(changeDate));
});
}
private static RankDataModel CreateDataModel(string? id, string? rankId,
string? rankName, RankType rankType, bool isActual, DateTime changeDate) =>
new (id, rankId, rankName, rankType, isActual, changeDate);
private static RankDataModel CreateDataModel(string? id, string? rankName, RankType rankType) =>
new(id, rankName, rankType);
}
}

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