30 Commits

Author SHA1 Message Date
a74de025fa Сданный вариант 2025-04-05 10:13:18 +04:00
user
32bc39635c вроде finish 2025-04-05 00:43:28 +04:00
user
9a0e2ec59d Вроде финиш 2025-04-03 21:47:45 +04:00
user
4c7ae6bd67 начало 2025-03-30 17:33:47 +04:00
user
bce6d47a99 Merge branch 'Task_2Hard' into Task_3Hard 2025-03-30 17:26:47 +04:00
user
78d614b893 fix 2.0 2025-03-30 17:21:43 +04:00
user
22c101c77c Revert "supply fix"
This reverts commit 4e3fd46750.
2025-03-30 17:11:34 +04:00
user
4e3fd46750 supply fix 2025-03-30 17:09:41 +04:00
user
2cb5ce2793 Revert "supply fix 2.0"
This reverts commit cc7d7289f7.
2025-03-30 16:54:19 +04:00
user
cc7d7289f7 supply fix 2.0 2025-03-30 16:40:30 +04:00
user
015a963762 InsertSupply fix 2025-03-30 16:19:57 +04:00
user
69c63f5499 InsertSupply 2025-03-30 14:28:02 +04:00
user
94f2c60a08 Наследование ISaleStorage 2025-03-17 02:39:08 +04:00
user
e54574147a Revert "Добавил наследование от ISaleStorage"
This reverts commit 9045e90326.
2025-03-17 02:38:38 +04:00
user
9045e90326 Добавил наследование от ISaleStorage 2025-03-17 02:38:26 +04:00
72d33599fc Сданный вариант 2025-03-12 12:45:28 +04:00
eb3191410a Сданный вариант, Automap 2025-03-12 11:49:17 +04:00
c9753ff960 поменял переменную 2025-03-12 10:59:48 +04:00
ab45eb0546 3 готовая 2025-03-12 08:58:59 +04:00
user
98f99f607f готовая 2 hard 2025-03-12 01:01:36 +04:00
de63a5844a До начала тестов! 2025-03-10 12:22:57 +04:00
03e10326d0 начал делать 2025-03-02 23:27:51 +04:00
679672a33b Merge branch 'Task_1Hard' into Task_2Hard 2025-02-22 10:10:22 +04:00
397fd64eaf TearDown 2025-02-22 09:30:53 +04:00
user
21258b1c31 Вроде все сделанно 2025-02-21 22:47:51 +04:00
9730a641c4 Сделал datamodels 2025-02-21 17:37:05 +04:00
aac12212f3 Cocktail тесты 2025-02-19 16:00:45 +04:00
user
9d60cd4c17 В процессе работы с тестами 2025-02-19 12:42:25 +04:00
c841dc0821 Сданный вариант 2025-02-08 09:09:25 +04:00
user
63b0aa95bf Сделанный вариант 2025-02-08 01:09:11 +04:00
106 changed files with 9003 additions and 1 deletions

View File

@@ -0,0 +1,70 @@
using SquirrelContract.BusinessLogicContracts;
using SquirrelContract.StoragesContracts;
using Microsoft.Extensions.Logging;
using SquirrelContract.Exceptions;
using SquirrelContract.Extensions;
using System.Text.Json;
using System.Text.RegularExpressions;
using SquirrelContract.DataModels;
namespace SquirrelBusinessLogic.Implementations;
internal class ClientBusinessLogicContract(IClientStorageContract clientStorageContract, ILogger logger) : IClientBusinessLogicContract
{
private readonly ILogger _logger = logger;
private readonly IClientStorageContract _clientStorageContract = clientStorageContract;
public List<ClientDataModel> GetAllClients()
{
_logger.LogInformation("GetAllClients");
return _clientStorageContract.GetList() ?? throw new NullListException();
}
public ClientDataModel GetClientByData(string data)
{
_logger.LogInformation("Get element by data: {data}", data);
if (data.IsEmpty())
{
throw new ArgumentNullException(nameof(data));
}
if (data.IsGuid())
{
return _clientStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data);
}
if (Regex.IsMatch(data, @"^((8|\+7)[\- ]?)?(\(?\d{3}\)?[\- ]?)?[\d\- ]{7,10}$"))
{
return _clientStorageContract.GetElementByPhoneNumber(data) ?? throw new ElementNotFoundException(data);
}
return _clientStorageContract.GetElementByFIO(data) ?? throw new ElementNotFoundException(data);
}
public void InsertClient(ClientDataModel clientDataModel)
{
_logger.LogInformation("New data: {json}", JsonSerializer.Serialize(clientDataModel));
ArgumentNullException.ThrowIfNull(clientDataModel);
clientDataModel.Validate();
_clientStorageContract.AddElement(clientDataModel);
}
public void UpdateClient(ClientDataModel clientDataModel)
{
_logger.LogInformation("Update data: {json}", JsonSerializer.Serialize(clientDataModel));
ArgumentNullException.ThrowIfNull(clientDataModel);
clientDataModel.Validate();
_clientStorageContract.UpdElement(clientDataModel);
}
public void DeleteClient(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");
}
_clientStorageContract.DelElement(id);
}
}

View File

@@ -0,0 +1,79 @@
using Microsoft.Extensions.Logging;
using SquirrelContract.BusinessLogicContracts;
using SquirrelContract.DataModels;
using SquirrelContract.Exceptions;
using SquirrelContract.Extensions;
using SquirrelContract.StoragesContracts;
using System.Text.Json;
using System.Text.RegularExpressions;
namespace SquirrelBusinessLogic.Implementations;
internal class CocktailBusinessLogicContract(ICocktailStorageContract cocktailStorageContract, ILogger logger) : ICocktailBusinessLogicContract
{
private readonly ILogger _logger = logger;
private readonly ICocktailStorageContract _cocktailStorageContract = cocktailStorageContract;
public List<CocktailDataModel> GetAllCocktails()
{
_logger.LogInformation("GetAllCocktails");
return _cocktailStorageContract.GetList() ?? throw new NullListException();
}
public List<CocktailHistoryDataModel> GetCocktailHistoryByCocktail(string cocktailId)
{
_logger.LogInformation("GetCocktailHistoryByCocktail for {cocktailId}", cocktailId);
if (cocktailId.IsEmpty())
{
throw new ArgumentNullException(nameof(cocktailId));
}
if (!cocktailId.IsGuid())
{
throw new ValidationException("The value in the field cocktailId is not a unique identifier.");
}
return _cocktailStorageContract.GetHistoryByCocktailId(cocktailId) ?? throw new NullListException();
}
public CocktailDataModel GetCocktailByData(string data)
{
_logger.LogInformation("Get element by data: {data}", data);
if (data.IsEmpty())
{
throw new ArgumentNullException(nameof(data));
}
if (data.IsGuid())
{
return _cocktailStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data);
}
return _cocktailStorageContract.GetElementByName(data) ?? throw new ElementNotFoundException(data);
}
public void InsertCocktail(CocktailDataModel cocktailDataModel)
{
_logger.LogInformation("New data: {json}", JsonSerializer.Serialize(cocktailDataModel));
ArgumentNullException.ThrowIfNull(cocktailDataModel);
cocktailDataModel.Validate();
_cocktailStorageContract.AddElement(cocktailDataModel);
}
public void UpdateCocktail(CocktailDataModel cocktailDataModel)
{
_logger.LogInformation("Update data: {json}", JsonSerializer.Serialize(cocktailDataModel));
ArgumentNullException.ThrowIfNull(cocktailDataModel);
cocktailDataModel.Validate();
_cocktailStorageContract.UpdElement(cocktailDataModel);
}
public void DeleteCocktail(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");
}
_cocktailStorageContract.DelElement(id);
}
}

View File

@@ -0,0 +1,104 @@
using Microsoft.Extensions.Logging;
using SquirrelContract.BusinessLogicContracts;
using SquirrelContract.DataModels;
using SquirrelContract.Exceptions;
using SquirrelContract.Extensions;
using SquirrelContract.StoragesContracts;
using System.Text.Json;
using System.Text.RegularExpressions;
namespace SquirrelBusinessLogic.Implementations;
internal class EmployeeBusinessLogicContract(IEmployeeStorageContract employeeStorageContract, ILogger logger) : IEmployeeBusinessLogicContract
{
private readonly ILogger _logger = logger;
private readonly IEmployeeStorageContract _employeeStorageContract = employeeStorageContract;
public List<EmployeeDataModel> GetAllEmployees(bool onlyActive = true)
{
_logger.LogInformation("GetAllEmployees params: {onlyActive}", onlyActive);
return _employeeStorageContract.GetList(onlyActive) ?? throw new NullListException();
}
public List<EmployeeDataModel> GetAllEmployeesByPost(string postId, bool onlyActive = true)
{
_logger.LogInformation("GetAllEmployees params: {postId}, {onlyActive},", postId, onlyActive);
if (postId.IsEmpty())
{
throw new ArgumentNullException(nameof(postId));
}
if (!postId.IsGuid())
{
throw new ValidationException("The value in the field postId is not a unique identifier.");
}
return _employeeStorageContract.GetList(onlyActive, postId) ?? throw new NullListException();
}
public List<EmployeeDataModel> GetAllEmployeesByBirthDate(DateTime fromDate, DateTime toDate, bool onlyActive = true)
{
_logger.LogInformation("GetAllEmployees params: {onlyActive}, {fromDate}, {toDate}", onlyActive, fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate);
}
return _employeeStorageContract.GetList(onlyActive, fromBirthDate: fromDate, toBirthDate: toDate) ?? throw new NullListException();
}
public List<EmployeeDataModel> GetAllEmployeesByEmploymentDate(DateTime fromDate, DateTime toDate, bool onlyActive = true)
{
_logger.LogInformation("GetAllEmployees params: {onlyActive}, {fromDate}, {toDate}", onlyActive, fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate);
}
return _employeeStorageContract.GetList(onlyActive, fromEmploymentDate: fromDate, toEmploymentDate: toDate) ?? throw new NullListException();
}
public EmployeeDataModel GetEmployeeByData(string data)
{
_logger.LogInformation("Get element by data: {data}", data);
if (data.IsEmpty())
{
throw new ArgumentNullException(nameof(data));
}
if (data.IsGuid())
{
return _employeeStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data);
}
if (Regex.IsMatch(data, @"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$"))
{
return _employeeStorageContract.GetElementByEmail(data) ?? throw new ElementNotFoundException(data);
}
return _employeeStorageContract.GetElementByFIO(data) ?? throw new ElementNotFoundException(data);
}
public void InsertEmployee(EmployeeDataModel employeeDataModel)
{
_logger.LogInformation("New data: {json}", JsonSerializer.Serialize(employeeDataModel));
ArgumentNullException.ThrowIfNull(employeeDataModel);
employeeDataModel.Validate();
_employeeStorageContract.AddElement(employeeDataModel);
}
public void UpdateEmployee(EmployeeDataModel employeeDataModel)
{
_logger.LogInformation("Update data: {json}", JsonSerializer.Serialize(employeeDataModel));
ArgumentNullException.ThrowIfNull(employeeDataModel);
employeeDataModel.Validate();
_employeeStorageContract.UpdElement(employeeDataModel);
}
public void DeleteEmployee(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");
}
_employeeStorageContract.DelElement(id);
}
}

View File

@@ -0,0 +1,92 @@
using Microsoft.Extensions.Logging;
using SquirrelContract.BusinessLogicContracts;
using SquirrelContract.DataModels;
using SquirrelContract.Exceptions;
using SquirrelContract.Extensions;
using SquirrelContract.StoragesContracts;
using System.Text.Json;
namespace SquirrelBusinessLogic.Implementations;
internal class PostBusinessLogicContract(IPostStorageContract postStorageContract, ILogger logger) : IPostBusinessLogicContract
{
private readonly ILogger _logger = logger;
private readonly IPostStorageContract _postStorageContract = postStorageContract;
public List<PostDataModel> GetAllPosts(bool onlyActive = true)
{
_logger.LogInformation("GetAllPosts params: {onlyActive}", onlyActive);
return _postStorageContract.GetList(onlyActive) ?? throw new NullListException();
}
public List<PostDataModel> GetAllDataOfPost(string postId)
{
_logger.LogInformation("GetAllDataOfPost for {postId}", postId);
if (postId.IsEmpty())
{
throw new ArgumentNullException(nameof(postId));
}
if (!postId.IsGuid())
{
throw new ValidationException("The value in the field postId is not a unique identifier.");
}
return _postStorageContract.GetPostWithHistory(postId) ?? throw new NullListException();
}
public PostDataModel GetPostByData(string data)
{
_logger.LogInformation("Get element by data: {data}", data);
if (data.IsEmpty())
{
throw new ArgumentNullException(nameof(data));
}
if (data.IsGuid())
{
return _postStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data);
}
return _postStorageContract.GetElementByName(data) ?? throw new ElementNotFoundException(data);
}
public void InsertPost(PostDataModel postDataModel)
{
_logger.LogInformation("New data: {json}", JsonSerializer.Serialize(postDataModel));
ArgumentNullException.ThrowIfNull(postDataModel);
postDataModel.Validate();
_postStorageContract.AddElement(postDataModel);
}
public void UpdatePost(PostDataModel postDataModel)
{
_logger.LogInformation("Update data: {json}", JsonSerializer.Serialize(postDataModel));
ArgumentNullException.ThrowIfNull(postDataModel);
postDataModel.Validate();
_postStorageContract.UpdElement(postDataModel);
}
public void DeletePost(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");
}
_postStorageContract.DelElement(id);
}
public void RestorePost(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");
}
_postStorageContract.ResElement(id);
}
}

View File

@@ -0,0 +1,63 @@
using BarBelochkaContract.DataModels;
using Microsoft.Extensions.Logging;
using SquirrelContract.BusinessLogicContracts;
using SquirrelContract.Exceptions;
using SquirrelContract.Extensions;
using SquirrelContract.StoragesContracts;
namespace SquirrelBusinessLogic.Implementations;
internal class SalaryBusinessLogicContract(ISalaryStorageContract salaryStorageContract,
ISaleStorageContract saleStorageContract, IPostStorageContract postStorageContract, IEmployeeStorageContract employeeStorageContract, ILogger logger) : ISalaryBusinessLogicContract
{
private readonly ILogger _logger = logger;
private readonly ISalaryStorageContract _salaryStorageContract = salaryStorageContract;
private readonly ISaleStorageContract _saleStorageContract = saleStorageContract;
private readonly IPostStorageContract _postStorageContract = postStorageContract;
private readonly IEmployeeStorageContract _employeeStorageContract = employeeStorageContract;
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> GetAllSalariesByPeriodByEmployee(DateTime fromDate, DateTime toDate, string employeeId)
{
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate);
}
if (employeeId.IsEmpty())
{
throw new ArgumentNullException(nameof(employeeId));
}
if (!employeeId.IsGuid())
{
throw new ValidationException("The value in the field employeeId is not a unique identifier.");
}
_logger.LogInformation("GetAllSalaries params: {fromDate}, {toDate}, {employeeId}", fromDate, toDate, employeeId);
return _salaryStorageContract.GetList(fromDate, toDate, employeeId) ?? 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 employees = _employeeStorageContract.GetList() ?? throw new NullListException();
foreach (var employee in employees)
{
var sales = _saleStorageContract.GetList(startDate, finishDate, employeeId: employee.Id)?.Sum(x => x.Sum) ??
throw new NullListException();
var post = _postStorageContract.GetElementById(employee.PostId) ??
throw new NullListException();
var salary = post.Salary + sales * 0.1;
_logger.LogDebug("The employee {employeeId} was paid a salary of {salary}", employee.Id, salary);
_salaryStorageContract.AddElement(new SalaryDataModel(employee.Id, finishDate, salary));
}
}
}

View File

@@ -0,0 +1,120 @@
using Microsoft.Extensions.Logging;
using SquirrelContract.BusinessLogicContracts;
using SquirrelContract.DataModels;
using SquirrelContract.Exceptions;
using SquirrelContract.Extensions;
using SquirrelContract.StoragesContracts;
using System.Text.Json;
namespace SquirrelBusinessLogic.Implementations;
internal class SaleBusinessLogicContract(ISaleStorageContract saleStorageContract, IWarehouseStorageContract warehouseStorageContract, ILogger logger) : ISaleBusinessLogicContract
{
private readonly ILogger _logger = logger;
private readonly ISaleStorageContract _saleStorageContract = saleStorageContract;
private readonly IWarehouseStorageContract _warehouseStorageContract = warehouseStorageContract;
public List<SaleDataModel> GetAllSalesByPeriod(DateTime fromDate, DateTime toDate)
{
_logger.LogInformation("GetAllSales params: {fromDate}, {toDate}", fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate);
}
return _saleStorageContract.GetList(fromDate, toDate) ?? throw new NullListException();
}
public List<SaleDataModel> GetAllSalesByEmployeeByPeriod(string employeeId, DateTime fromDate, DateTime toDate)
{
_logger.LogInformation("GetAllSales params: {employeeId}, {fromDate}, {toDate}", employeeId, fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate);
}
if (employeeId.IsEmpty())
{
throw new ArgumentNullException(nameof(employeeId));
}
if (!employeeId.IsGuid())
{
throw new ValidationException("The value in the field employeeId is not a unique identifier.");
}
return _saleStorageContract.GetList(fromDate, toDate, employeeId: employeeId) ?? throw new NullListException();
}
public List<SaleDataModel> GetAllSalesByClientByPeriod(string clientId, DateTime fromDate, DateTime toDate)
{
_logger.LogInformation("GetAllSales params: {buyerId}, {fromDate}, {toDate}", clientId, fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate);
}
if (clientId.IsEmpty())
{
throw new ArgumentNullException(nameof(clientId));
}
if (!clientId.IsGuid())
{
throw new ValidationException("The value in the field clientId is not a unique identifier.");
}
return _saleStorageContract.GetList(fromDate, toDate, clientId: clientId) ?? throw new NullListException();
}
public List<SaleDataModel> GetAllSalesByCocktailByPeriod(string cocktailId, DateTime fromDate, DateTime toDate)
{
_logger.LogInformation("GetAllSales params: {cocktailId}, {fromDate}, {toDate}", cocktailId, fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate);
}
if (cocktailId.IsEmpty())
{
throw new ArgumentNullException(nameof(cocktailId));
}
if (!cocktailId.IsGuid())
{
throw new ValidationException("The value in the field cocktailId is not a unique identifier.");
}
return _saleStorageContract.GetList(fromDate, toDate, cocktailId: cocktailId) ?? throw new NullListException();
}
public SaleDataModel GetSaleByData(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 _saleStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data);
}
public void InsertSale(SaleDataModel saleDataModel)
{
_logger.LogInformation("New data: {json}", JsonSerializer.Serialize(saleDataModel));
ArgumentNullException.ThrowIfNull(saleDataModel);
saleDataModel.Validate();
if (!_warehouseStorageContract.CheckCocktails(saleDataModel))
{
throw new InsufficientStockException("Dont have cocktails in warehouse");
}
_saleStorageContract.AddElement(saleDataModel);
}
public void CancelSale(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");
}
_saleStorageContract.DelElement(id);
}
}

View File

@@ -0,0 +1,103 @@
using Microsoft.Extensions.Logging;
using SquirrelContract.BusinessLogicContracts;
using SquirrelContract.DataModels;
using SquirrelContract.Exceptions;
using SquirrelContract.Extensions;
using SquirrelContract.StoragesContracts;
using System.Text.Json;
namespace SquirrelBusinessLogic.Implementations;
internal class SupplyBusinessLogicContract(ISupplyStorageContract supplyStorageContract, IWarehouseStorageContract warehouseStorageContract, ILogger logger) : ISupplyBusinessLogicContract
{
private readonly ILogger _logger = logger;
private readonly ISupplyStorageContract _supplyStorageContract = supplyStorageContract;
private readonly IWarehouseStorageContract _warehouseStorageContract = warehouseStorageContract;
public List<SupplyDataModel> GetAllSuppliesByPeriod(DateTime fromDate, DateTime toDate)
{
_logger.LogInformation("GetAllSupplies params: {fromDate}, {toDate}", fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate);
}
return _supplyStorageContract.GetList(fromDate, toDate) ?? throw new NullListException();
}
public List<SupplyDataModel> GetAllSuppliesByCocktailByPeriod(string cocktailId, DateTime fromDate, DateTime toDate)
{
_logger.LogInformation("GetAllSupplies params: {cocktailId}, {fromDate}, {toDate}", cocktailId, fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate);
}
if (cocktailId.IsEmpty())
{
throw new ArgumentNullException(nameof(cocktailId));
}
if (!cocktailId.IsGuid())
{
throw new ValidationException("The value in the field cocktailId is not a unique identifier.");
}
return _supplyStorageContract.GetList(fromDate, toDate, cocktailId: cocktailId) ?? throw new NullListException();
}
public SupplyDataModel GetSupplyByData(string data)
{
_logger.LogInformation("Get supply by data: {data}", data);
if (data.IsEmpty())
{
throw new ArgumentNullException(nameof(data));
}
if (!data.IsGuid())
{
throw new ElementNotFoundException(data);
}
return _supplyStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data);
}
public void ProcessSupply(SupplyDataModel supplyDataModel)
{
_logger.LogInformation("Processing supply: {json}", JsonSerializer.Serialize(supplyDataModel));
ArgumentNullException.ThrowIfNull(supplyDataModel);
supplyDataModel.Validate();
foreach (var supplyCocktail in supplyDataModel.Cocktails)
{
var warehouses = _warehouseStorageContract.GetList();
var targetWarehouse = warehouses.FirstOrDefault(w =>
w.Cocktails.Any(c => c.CocktailId == supplyCocktail.CocktailId));
if (targetWarehouse == null)
{
targetWarehouse = warehouses.FirstOrDefault();
if (targetWarehouse == null)
{
throw new ElementNotFoundException("No warehouse found for supply.");
}
}
_warehouseStorageContract.UpdWarehouseOnSupply(targetWarehouse.Id, supplyCocktail.CocktailId, supplyCocktail.Count);
}
}
public void InsertSupply(SupplyDataModel supplyDataModel)
{
_logger.LogInformation("New data: {json}", JsonSerializer.Serialize(supplyDataModel));
ArgumentNullException.ThrowIfNull(supplyDataModel);
supplyDataModel.Validate();
_supplyStorageContract.AddElement(supplyDataModel);
ProcessSupply(supplyDataModel);
}
public void UpdateSupply(SupplyDataModel supplyDataModel)
{
_logger.LogInformation("Update data: {json}", JsonSerializer.Serialize(supplyDataModel));
ArgumentNullException.ThrowIfNull(supplyDataModel);
supplyDataModel.Validate();
_supplyStorageContract.UpdateElement(supplyDataModel);
ProcessSupply(supplyDataModel);
}
}

View File

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

View File

@@ -0,0 +1,22 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<InternalsVisibleTo Include="SquirrelTests" />
<InternalsVisibleTo Include="DynamicProxyGenAssembly2" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="9.0.2" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\SquirrelContract\SquirrelContract.csproj" />
</ItemGroup>
</Project>

View File

@@ -1,10 +1,16 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.12.35707.178 d17.12
VisualStudioVersion = 17.12.35707.178
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SquirrelContract", "SquirrelContract\SquirrelContract.csproj", "{3B0E65D7-E64B-4893-803B-A59D9F2C8836}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SquirrelTests", "SquirrelTests\SquirrelTests.csproj", "{CC02A7DA-AA53-4D19-BB16-4DDA5243EB33}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SquirrelBusinessLogic", "SquirrelBusinessLogic\SquirrelBusinessLogic.csproj", "{C03D0604-CD06-42DA-99CB-23B8306C3714}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SquirrelDatabase", "SquirrelDatabase\SquirrelDatabase.csproj", "{A8A7A434-A278-4362-8D34-C2E3CAA938C1}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@@ -15,6 +21,18 @@ Global
{3B0E65D7-E64B-4893-803B-A59D9F2C8836}.Debug|Any CPU.Build.0 = Debug|Any CPU
{3B0E65D7-E64B-4893-803B-A59D9F2C8836}.Release|Any CPU.ActiveCfg = Release|Any CPU
{3B0E65D7-E64B-4893-803B-A59D9F2C8836}.Release|Any CPU.Build.0 = Release|Any CPU
{CC02A7DA-AA53-4D19-BB16-4DDA5243EB33}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{CC02A7DA-AA53-4D19-BB16-4DDA5243EB33}.Debug|Any CPU.Build.0 = Debug|Any CPU
{CC02A7DA-AA53-4D19-BB16-4DDA5243EB33}.Release|Any CPU.ActiveCfg = Release|Any CPU
{CC02A7DA-AA53-4D19-BB16-4DDA5243EB33}.Release|Any CPU.Build.0 = Release|Any CPU
{C03D0604-CD06-42DA-99CB-23B8306C3714}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C03D0604-CD06-42DA-99CB-23B8306C3714}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C03D0604-CD06-42DA-99CB-23B8306C3714}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C03D0604-CD06-42DA-99CB-23B8306C3714}.Release|Any CPU.Build.0 = Release|Any CPU
{A8A7A434-A278-4362-8D34-C2E3CAA938C1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{A8A7A434-A278-4362-8D34-C2E3CAA938C1}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A8A7A434-A278-4362-8D34-C2E3CAA938C1}.Release|Any CPU.ActiveCfg = Release|Any CPU
{A8A7A434-A278-4362-8D34-C2E3CAA938C1}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE

View File

@@ -0,0 +1,16 @@
using SquirrelContract.DataModels;
namespace SquirrelContract.BusinessLogicContracts;
public interface IClientBusinessLogicContract
{
List<ClientDataModel> GetAllClients();
ClientDataModel GetClientByData(string data);
void InsertClient(ClientDataModel clientDataModel);
void UpdateClient(ClientDataModel clientDataModel);
void DeleteClient(string id);
}

View File

@@ -0,0 +1,18 @@
using SquirrelContract.DataModels;
namespace SquirrelContract.BusinessLogicContracts;
public interface ICocktailBusinessLogicContract
{
List<CocktailDataModel> GetAllCocktails();
List<CocktailHistoryDataModel> GetCocktailHistoryByCocktail(string productId);
CocktailDataModel GetCocktailByData(string data);
void InsertCocktail(CocktailDataModel cocktailDataModel);
void UpdateCocktail(CocktailDataModel cocktailDataModel);
void DeleteCocktail(string id);
}

View File

@@ -0,0 +1,22 @@
using SquirrelContract.DataModels;
namespace SquirrelContract.BusinessLogicContracts;
public interface IEmployeeBusinessLogicContract
{
List<EmployeeDataModel> GetAllEmployees(bool onlyActive = true);
List<EmployeeDataModel> GetAllEmployeesByPost(string employeeId, bool onlyActive = true);
List<EmployeeDataModel> GetAllEmployeesByBirthDate(DateTime fromDate, DateTime toDate, bool onlyActive = true);
List<EmployeeDataModel> GetAllEmployeesByEmploymentDate(DateTime fromDate, DateTime toDate, bool onlyActive = true);
EmployeeDataModel GetEmployeeByData(string data);
void InsertEmployee(EmployeeDataModel employeeDataModel);
void UpdateEmployee(EmployeeDataModel employeeDataModel);
void DeleteEmployee(string id);
}

View File

@@ -0,0 +1,20 @@
using SquirrelContract.DataModels;
namespace SquirrelContract.BusinessLogicContracts;
public interface IPostBusinessLogicContract
{
List<PostDataModel> GetAllPosts(bool onlyActive);
List<PostDataModel> GetAllDataOfPost(string postId);
PostDataModel GetPostByData(string data);
void InsertPost(PostDataModel postDataModel);
void UpdatePost(PostDataModel postDataModel);
void DeletePost(string id);
void RestorePost(string id);
}

View File

@@ -0,0 +1,12 @@
using BarBelochkaContract.DataModels;
namespace SquirrelContract.BusinessLogicContracts;
public interface ISalaryBusinessLogicContract
{
List<SalaryDataModel> GetAllSalariesByPeriod(DateTime fromDate, DateTime toDate);
List<SalaryDataModel> GetAllSalariesByPeriodByEmployee(DateTime fromDate, DateTime toDate, string employeeId);
void CalculateSalaryByMounth(DateTime date);
}

View File

@@ -0,0 +1,20 @@
using SquirrelContract.DataModels;
namespace SquirrelContract.BusinessLogicContracts;
public interface ISaleBusinessLogicContract
{
List<SaleDataModel> GetAllSalesByPeriod(DateTime fromDate, DateTime toDate);
List<SaleDataModel> GetAllSalesByEmployeeByPeriod(string employeeId, DateTime fromDate, DateTime toDate);
List<SaleDataModel> GetAllSalesByClientByPeriod(string clientId, DateTime fromDate, DateTime toDate);
List<SaleDataModel> GetAllSalesByCocktailByPeriod(string cocktailId, DateTime fromDate, DateTime toDate);
SaleDataModel GetSaleByData(string data);
void InsertSale(SaleDataModel saleDataModel);
void CancelSale(string id);
}

View File

@@ -0,0 +1,17 @@
using SquirrelContract.DataModels;
namespace SquirrelContract.BusinessLogicContracts;
public interface ISupplyBusinessLogicContract
{
List<SupplyDataModel> GetAllSuppliesByPeriod(DateTime fromDate, DateTime toDate);
List<SupplyDataModel> GetAllSuppliesByCocktailByPeriod(string cocktailId, DateTime fromDate, DateTime toDate);
SupplyDataModel GetSupplyByData(string data);
void InsertSupply(SupplyDataModel supplyDataModel);
void UpdateSupply(SupplyDataModel supplyDataModel);
}

View File

@@ -0,0 +1,16 @@
using SquirrelContract.DataModels;
namespace SquirrelContract.BusinessLogicContracts;
public interface IWarehouseBusinessLogicContract
{
List<WarehouseDataModel> GetAllWarehouses();
WarehouseDataModel GetWarehouseByData(string data);
void InsertWarehouse(WarehouseDataModel cocktailDataModel);
void UpdateWarehouse(WarehouseDataModel cocktailDataModel);
void DeleteWarehouse(string id);
}

View File

@@ -0,0 +1,32 @@
using SquirrelContract.Exceptions;
using SquirrelContract.Extensions;
using SquirrelContract.Infastructure;
using System.Text.RegularExpressions;
namespace SquirrelContract.DataModels;
public class ClientDataModel(string id, string fio, string phoneNumber, double discountSize) : IValidation
{
public string Id { get; private set; } = id;
public string FIO { get; private set;} = fio;
public string PhoneNumber { get; private set;} = phoneNumber;
public double DiscountSize { get; private set; } = discountSize;
public void Validate()
{
if (Id.IsEmpty())
throw new ValidationException("Field Id is empty");
if (!Id.IsGuid())
throw new ValidationException("The value in the field Id is not a unique identifier");
if (FIO.IsEmpty())
throw new ValidationException("Field FIO is empty");
if (PhoneNumber.IsEmpty())
throw new ValidationException("Field PhoneNumber is empty");
if (!Regex.IsMatch(PhoneNumber, @"^((8|\+7)[\- ]?)?(\(?\d{3}\)?[\- ]?)?[\d\- ]{7,10}$"))
throw new ValidationException("Field PhoneNumber is not a phone number");
}
}

View File

@@ -0,0 +1,32 @@
using SquirrelContract.Enums;
using SquirrelContract.Exceptions;
using SquirrelContract.Extensions;
using SquirrelContract.Infastructure;
namespace SquirrelContract.DataModels;
public class CocktailDataModel(string id, string cocktailName, double price, AlcoholType baseAlcohol) : IValidation
{
public string Id { get; private set; } = id;
public string CocktailName { get; private set; } = cocktailName;
public double Price { get; private set; } = price;
public AlcoholType BaseAlcohol { get; private set; } = baseAlcohol;
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 (CocktailName.IsEmpty())
throw new ValidationException("Field CocktailName is empty");
if (Price <= 0)
throw new ValidationException("Field Price is less than or equal to 0");
if (BaseAlcohol == AlcoholType.None)
throw new ValidationException("Field BaseAlcohol is empty");
}
}

View File

@@ -0,0 +1,26 @@
using SquirrelContract.Exceptions;
using SquirrelContract.Extensions;
using SquirrelContract.Infastructure;
namespace SquirrelContract.DataModels;
public class CocktailHistoryDataModel(string cocktailId, double oldPrice) : IValidation
{
public string CocktailId { get; private set; } = cocktailId;
public double OldPrice { get; private set; } = oldPrice;
public DateTime ChangeDate { get; private set; } = DateTime.UtcNow;
public void Validate()
{
if (CocktailId.IsEmpty())
throw new ValidationException("Field CocktailId is empty");
if (!CocktailId.IsGuid())
throw new ValidationException("The value in the field CocktailId is not a unique identifier");
if (OldPrice <= 0)
throw new ValidationException("Field OldPrice is less than or equal to 0");
}
}

View File

@@ -0,0 +1,56 @@
using SquirrelContract.Exceptions;
using SquirrelContract.Extensions;
using SquirrelContract.Infastructure;
using System.Text.RegularExpressions;
namespace SquirrelContract.DataModels;
public class EmployeeDataModel(string id, string fio, string email, string postId, DateTime birthDate, DateTime employmentDate, bool isDeleted) : IValidation
{
public string Id { get; private set; } = id;
public string FIO { get; private set; } = fio;
public string Email { get; private set; } = email;
public string PostId { get; private set; } = postId;
public DateTime BirthDate { get; private set; } = birthDate;
public DateTime EmploymentDate { get; private set; } = employmentDate;
public bool IsDeleted { get; private set; } = isDeleted;
public void Validate()
{
if (Id.IsEmpty())
throw new ValidationException("Field Id is empty");
if (!Id.IsGuid())
throw new ValidationException("The value in the field Id is not a unique identifier");
if (FIO.IsEmpty())
throw new ValidationException("Field FIO is empty");
if (Email.IsEmpty())
throw new ValidationException("Field Email is empty");
if (!Regex.IsMatch(Email, @"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$"))
throw new ValidationException("Field Email is not a valid email address");
if (PostId.IsEmpty())
throw new ValidationException("Field PostId is empty");
if (!PostId.IsGuid())
throw new ValidationException("The value in the field PostId is not a unique identifier");
if (BirthDate.Date > DateTime.Now.AddYears(-18).Date)
throw new ValidationException($"Only adults can be hired (BirthDate = {BirthDate.ToShortDateString()})");
if (EmploymentDate.Date < BirthDate.Date)
throw new ValidationException("The date of employment cannot be less than the date of birth");
if ((EmploymentDate - BirthDate).TotalDays / 365 < 18) // EmploymentDate.Year - BirthDate.Year
throw new ValidationException($"Only adults can be hired (EmploymentDate - {EmploymentDate.ToShortDateString()}, BirthDate - {BirthDate.ToShortDateString()})");
}
}

View File

@@ -0,0 +1,39 @@
using SquirrelContract.Enums;
using SquirrelContract.Exceptions;
using SquirrelContract.Extensions;
using SquirrelContract.Infastructure;
namespace SquirrelContract.DataModels;
public class PostDataModel(string postId, string postName, PostType postType, double salary, bool isActual, DateTime changeDate) : IValidation
{
public string Id { get; private set; } = postId;
public string PostName { get; private set; } = postName;
public PostType PostType { get; private set; } = postType;
public double Salary { get; private set; } = salary;
public bool IsActual { get; private set; } = isActual;
public DateTime ChangeDate { get; private set; } = changeDate;
public void Validate()
{
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 (PostName.IsEmpty())
throw new ValidationException("Field PostName is empty");
if (PostType == PostType.None)
throw new ValidationException("Field PostType is empty");
if (Salary <= 0)
throw new ValidationException("Field Salary is empty");
}
}

View File

@@ -0,0 +1,26 @@
using SquirrelContract.Exceptions;
using SquirrelContract.Extensions;
using SquirrelContract.Infastructure;
namespace BarBelochkaContract.DataModels;
public class SalaryDataModel(string employeeId, DateTime salaryDate, double employeeSalary) : IValidation
{
public string EmployeeId { get; private set; } = employeeId;
public DateTime SalaryDate { get; private set; } = salaryDate;
public double Salary { get; private set; } = employeeSalary;
public void Validate()
{
if (EmployeeId.IsEmpty())
throw new ValidationException("Field EmployeeId is empty");
if (!EmployeeId.IsGuid())
throw new ValidationException("The value in the field EmployeeId is not a unique identifier");
if (Salary <= 0)
throw new ValidationException("Field Salary is less than or equal to 0");
}
}

View File

@@ -0,0 +1,32 @@
using SquirrelContract.Exceptions;
using SquirrelContract.Extensions;
using SquirrelContract.Infastructure;
namespace SquirrelContract.DataModels;
public class SaleCocktailDataModel(string saleId, string cocktailId, int count) : IValidation
{
public string SaleId { get; private set; } = saleId;
public string CocktailId { get; private set; } = cocktailId;
public int Count { get; private set; } = count;
public void Validate()
{
if (SaleId.IsEmpty())
throw new ValidationException("Field SaleId is empty");
if (!SaleId.IsGuid())
throw new ValidationException("The value in the field SaleId is not a unique identifier");
if (CocktailId.IsEmpty())
throw new ValidationException("Field ProductId is empty");
if (!CocktailId.IsGuid())
throw new ValidationException("The value in the field ProductId is not a unique identifier");
if (Count <= 0)
throw new ValidationException("Field Count is less than or equal to 0");
}
}

View File

@@ -0,0 +1,51 @@
using SquirrelContract.Enums;
using SquirrelContract.Exceptions;
using SquirrelContract.Extensions;
using SquirrelContract.Infastructure;
namespace SquirrelContract.DataModels;
public class SaleDataModel(string id, string employeeId, string? clientId, double sum, DiscountType discountType, double discount, bool isCancel, List<SaleCocktailDataModel> saleCocktails) : IValidation
{
public string Id { get; private set; } = id;
public string EmployeeId { get; private set; } = employeeId;
public string? ClientId { get; private set; } = clientId;
public DateTime SaleDate { get; private set; } = DateTime.UtcNow;
public double Sum { get; private set; } = sum;
public DiscountType DiscountType { get; private set; } = discountType;
public double Discount { get; private set; } = discount;
public bool IsCancel { get; private set; } = isCancel;
public List<SaleCocktailDataModel> Cocktails { get; private set; } = saleCocktails;
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 (EmployeeId.IsEmpty())
throw new ValidationException("Field EmployeeId is empty");
if (!EmployeeId.IsGuid())
throw new ValidationException("The value in the field EmployeeId is not a unique identifier");
if (!ClientId?.IsGuid() ?? !ClientId?.IsEmpty() ?? false)
throw new ValidationException("The value in the field BuyerId is not a unique identifier");
if (Sum <= 0)
throw new ValidationException("Field Sum is less than or equal to 0");
if ((Cocktails?.Count ?? 0) == 0)
throw new ValidationException("The sale must include cocktails");
}
}

View File

@@ -0,0 +1,33 @@
using SquirrelContract.Exceptions;
using SquirrelContract.Extensions;
using SquirrelContract.Infastructure;
using System.ComponentModel;
namespace SquirrelContract.DataModels;
public class SupplyCocktailDataModel(string? supplyId, string? cocktailId, int count) : IValidation
{
public string SupplyId { get; private set; } = supplyId;
public string CocktailId { get; private set; } = cocktailId;
public int Count { get; private set; } = count;
public void Validate()
{
if (SupplyId.IsEmpty())
throw new ValidationException("Field SupplyId is empty");
if (!SupplyId.IsGuid())
throw new ValidationException("The value in the field SupplyId is not a unique identifier");
if (CocktailId.IsEmpty())
throw new ValidationException("Field CocktailId is empty");
if (!CocktailId.IsGuid())
throw new ValidationException("The value in the field CocktailId is not a unique identifier");
if (Count <= 0)
throw new ValidationException("Field Count is less than or equal to 0");
}
}

View File

@@ -0,0 +1,29 @@
using SquirrelContract.Exceptions;
using SquirrelContract.Extensions;
using SquirrelContract.Infastructure;
namespace SquirrelContract.DataModels;
public class SupplyDataModel(string? id, DateTime supplyDate, List<SupplyCocktailDataModel> cocktails) : IValidation
{
public string Id { get; private set; } = id;
public DateTime SupplyDate { get; private set; } = supplyDate;
public List<SupplyCocktailDataModel> Cocktails { get; private set; } = cocktails;
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 (SupplyDate.Date > DateTime.Now)
throw new ValidationException($"It is impossible to supply things in the future");
if ((Cocktails?.Count ?? 0) == 0)
throw new ValidationException("The components must include products");
}
}

View File

@@ -0,0 +1,32 @@
using SquirrelContract.Exceptions;
using SquirrelContract.Extensions;
using SquirrelContract.Infastructure;
namespace SquirrelContract.DataModels;
public class WarehouseCocktailDataModel(string? warehouseId, string? cocktailId, int count) : IValidation
{
public string WarehouseId { get; private set; } = warehouseId;
public string CocktailId { get; private set; } = cocktailId;
public int Count { get; private set; } = count;
public void Validate()
{
if (WarehouseId.IsEmpty())
throw new ValidationException("Field WarehouseId is empty");
if (!WarehouseId.IsGuid())
throw new ValidationException("The value in the field WarehouseId is not a unique identifier");
if (CocktailId.IsEmpty())
throw new ValidationException("Field CocktailId is empty");
if (!CocktailId.IsGuid())
throw new ValidationException("The value in the field CocktailId is not a unique identifier");
if (Count <= 0)
throw new ValidationException("Field Count is less than or equal to 0");
}
}

View File

@@ -0,0 +1,30 @@
using SquirrelContract.Exceptions;
using SquirrelContract.Extensions;
using SquirrelContract.Infastructure;
using System.Xml.Linq;
namespace SquirrelContract.DataModels;
public class WarehouseDataModel(string? id, string name, List<WarehouseCocktailDataModel> cocktails) : IValidation
{
public string Id { get; private set; } = id;
public string Name { get; private set; } = name;
public List<WarehouseCocktailDataModel> Cocktails { get; private set; } = cocktails;
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 (Name.IsEmpty())
throw new ValidationException("Field Name is empty");
if ((Cocktails?.Count ?? 0) == 0)
throw new ValidationException("The cocktails must include drinks");
}
}

View File

@@ -0,0 +1,10 @@
namespace SquirrelContract.Enums;
public enum AlcoholType
{
None = 0,
Vodka = 1,
Whiskey = 2,
Wine = 3,
Beer = 4
}

View File

@@ -0,0 +1,10 @@
namespace SquirrelContract.Enums;
[Flags]
public enum DiscountType
{
None = 0,
OnSale = 1,
RegularCustomer = 2,
Certificate = 4
}

View File

@@ -0,0 +1,9 @@
namespace SquirrelContract.Enums;
public enum PostType
{
None = 0,
Bartender = 1,
Manager = 2,
PurchasingSpecialist = 3
}

View File

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

View File

@@ -0,0 +1,11 @@
namespace SquirrelContract.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,14 @@
namespace SquirrelContract.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,6 @@
namespace SquirrelContract.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.YYYY}. EndDate: {end:dd.MM.YYYY}") { }
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,14 @@
namespace SquirrelContract.Extensions;
public static class StringExtensions
{
public static bool IsEmpty(this string str)
{
return string.IsNullOrWhiteSpace(str);
}
public static bool IsGuid(this string str)
{
return Guid.TryParse(str, out _);
}
}

View File

@@ -0,0 +1,6 @@
namespace SquirrelContract.Infastructure;
public interface IConfigurationDatabase
{
string ConnectionString { get; }
}

View File

@@ -0,0 +1,6 @@
namespace SquirrelContract.Infastructure;
public interface IValidation
{
void Validate();
}

View File

@@ -0,0 +1,20 @@
using SquirrelContract.DataModels;
namespace SquirrelContract.StoragesContracts;
public interface IClientStorageContract
{
List<ClientDataModel> GetList();
ClientDataModel? GetElementById(string id);
ClientDataModel? GetElementByPhoneNumber(string phoneNumber);
ClientDataModel? GetElementByFIO(string fio);
void AddElement(ClientDataModel clientDataModel);
void UpdElement(ClientDataModel clientDataModel);
void DelElement(string id);
}

View File

@@ -0,0 +1,15 @@
using SquirrelContract.DataModels;
namespace SquirrelContract.StoragesContracts;
public interface ICocktailStorageContract
{
List<CocktailDataModel> GetList();
List<CocktailHistoryDataModel> GetHistoryByCocktailId(string cocktailId);
CocktailDataModel? GetElementById(string id);
CocktailDataModel? GetElementByName(string name);
void AddElement(CocktailDataModel cocktailDataModel);
void UpdElement(CocktailDataModel cocktailDataModel);
void DelElement(string id);
void ResElement(string id);
}

View File

@@ -0,0 +1,20 @@
using SquirrelContract.DataModels;
namespace SquirrelContract.StoragesContracts;
public interface IEmployeeStorageContract
{
List<EmployeeDataModel> GetList(bool onlyActive = true, string? postId = null, DateTime? fromBirthDate = null, DateTime? toBirthDate = null, DateTime? fromEmploymentDate = null, DateTime? toEmploymentDate = null);
EmployeeDataModel? GetElementById(string id);
EmployeeDataModel? GetElementByFIO(string fio);
EmployeeDataModel? GetElementByEmail(string email);
void AddElement(EmployeeDataModel employeeDataModel);
void UpdElement(EmployeeDataModel employeeDataModel);
void DelElement(string id);
}

View File

@@ -0,0 +1,15 @@
using SquirrelContract.DataModels;
namespace SquirrelContract.StoragesContracts;
public interface IPostStorageContract
{
List<PostDataModel> GetList(bool onlyActual = true);
List<PostDataModel> GetPostWithHistory(string postId);
PostDataModel? GetElementById(string id);
PostDataModel? GetElementByName(string name);
void AddElement(PostDataModel postDataModel);
void UpdElement(PostDataModel postDataModel);
void DelElement(string id);
void ResElement(string id);
}

View File

@@ -0,0 +1,10 @@
using BarBelochkaContract.DataModels;
namespace SquirrelContract.StoragesContracts;
public interface ISalaryStorageContract
{
List<SalaryDataModel> GetList(DateTime startDate, DateTime endDate, string? employeeId = null);
void AddElement(SalaryDataModel salaryDataModel);
}

View File

@@ -0,0 +1,14 @@
using SquirrelContract.DataModels;
namespace SquirrelContract.StoragesContracts;
public interface ISaleStorageContract
{
List<SaleDataModel> GetList(DateTime? startDate = null, DateTime? endDate = null, string? employeeId = null, string? clientId = null, string? cocktailId = null);
SaleDataModel? GetElementById(string id);
void AddElement(SaleDataModel saleDataModel);
void DelElement(string id);
}

View File

@@ -0,0 +1,11 @@
using SquirrelContract.DataModels;
namespace SquirrelContract.StoragesContracts;
public interface ISupplyStorageContract
{
List<SupplyDataModel> GetList(DateTime? startDate = null, DateTime? endDate = null, string? cocktailId = null);
SupplyDataModel? GetElementById(string id);
void AddElement(SupplyDataModel warehouseDataModel);
void UpdateElement(SupplyDataModel warehouseDataModel);
}

View File

@@ -0,0 +1,15 @@
using SquirrelContract.DataModels;
namespace SquirrelContract.StoragesContracts;
public interface IWarehouseStorageContract
{
List<WarehouseDataModel> GetList();
WarehouseDataModel? GetElementByName(string name);
WarehouseDataModel? GetElementById(string id);
void AddElement(WarehouseDataModel warehouseDataModel);
void UpdElement(WarehouseDataModel warehouseDataModel);
void UpdWarehouseOnSupply(string warehouseId, string cocktailId, int count);
void DelElement(string id);
bool CheckCocktails(SaleDataModel saleDataModel);
}

View File

@@ -0,0 +1,149 @@
using AutoMapper;
using Microsoft.EntityFrameworkCore;
using Npgsql;
using SquirrelContract.DataModels;
using SquirrelContract.Exceptions;
using SquirrelContract.StoragesContracts;
using SquirrelDatabase.Models;
using System;
namespace SquirrelDatabase.Implementations;
public class ClientStorageContract : IClientStorageContract
{
private readonly SquirrelDbContext _dbContext;
private readonly Mapper _mapper;
public ClientStorageContract(SquirrelDbContext squirrelDbContext)
{
_dbContext = squirrelDbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.AddMaps(typeof(SquirrelDbContext).Assembly);
});
_mapper = new Mapper(config);
}
public List<ClientDataModel> GetList()
{
try
{
return [.. _dbContext.Clients.Select(x => _mapper.Map<ClientDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public ClientDataModel? GetElementById(string id)
{
try
{
return _mapper.Map<ClientDataModel>(GetClientById(id));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public ClientDataModel? GetElementByFIO(string fio)
{
try
{
return _mapper.Map<ClientDataModel>(_dbContext.Clients.FirstOrDefault(x => x.FIO == fio));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public ClientDataModel? GetElementByPhoneNumber(string phoneNumber)
{
try
{
return _mapper.Map<ClientDataModel>(_dbContext.Clients.FirstOrDefault(x => x.PhoneNumber == phoneNumber));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void AddElement(ClientDataModel clientDataModel)
{
try
{
_dbContext.Clients.Add(_mapper.Map<Client>(clientDataModel));
_dbContext.SaveChanges();
}
catch (InvalidOperationException ex) when (ex.TargetSite?.Name == "ThrowIdentityConflict")
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("Id", clientDataModel.Id);
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Clients_PhoneNumber" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("PhoneNumber", clientDataModel.PhoneNumber);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void UpdElement(ClientDataModel clientDataModel)
{
try
{
var element = GetClientById(clientDataModel.Id) ?? throw new ElementNotFoundException(clientDataModel.Id);
_dbContext.Clients.Update(_mapper.Map(clientDataModel, element));
_dbContext.SaveChanges();
}
catch (ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Clients_PhoneNumber" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("PhoneNumber", clientDataModel.PhoneNumber);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void DelElement(string id)
{
try
{
var element = GetClientById(id) ?? throw new ElementNotFoundException(id);
_dbContext.Clients.Remove(element);
_dbContext.SaveChanges();
}
catch (ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
private Client? GetClientById(string id) => _dbContext.Clients.FirstOrDefault(x => x.Id == id);
}

View File

@@ -0,0 +1,164 @@
using AutoMapper;
using Microsoft.EntityFrameworkCore;
using Npgsql;
using SquirrelContract.DataModels;
using SquirrelContract.Exceptions;
using SquirrelContract.StoragesContracts;
using SquirrelDatabase.Models;
namespace SquirrelDatabase.Implementations;
public class CocktailStorageContract : ICocktailStorageContract
{
private readonly SquirrelDbContext _dbContext;
private readonly Mapper _mapper;
public CocktailStorageContract(SquirrelDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Cocktail, CocktailDataModel>();
cfg.CreateMap<CocktailDataModel, Cocktail>();
cfg.CreateMap<CocktailHistory, CocktailHistoryDataModel>();
});
_mapper = new Mapper(config);
}
public List<CocktailDataModel> GetList()
{
try
{
return [.. _dbContext.Cocktails.Select(x => _mapper.Map<CocktailDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public List<CocktailHistoryDataModel> GetHistoryByCocktailId(string cocktailId)
{
try
{
return [.. _dbContext.CocktailHistories.Where(x => x.CocktailId == cocktailId).OrderByDescending(x => x.ChangeDate).Select(x => _mapper.Map<CocktailHistoryDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public CocktailDataModel? GetElementById(string id)
{
try
{
return _mapper.Map<CocktailDataModel>(GetCocktailById(id));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public CocktailDataModel? GetElementByName(string name)
{
try
{
return _mapper.Map<CocktailDataModel>(_dbContext.Cocktails.FirstOrDefault(x => x.CocktailName == name));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void AddElement(CocktailDataModel cocktailDataModel)
{
try
{
_dbContext.Cocktails.Add(_mapper.Map<Cocktail>(cocktailDataModel));
_dbContext.SaveChanges();
}
catch (InvalidOperationException ex) when (ex.TargetSite?.Name == "ThrowIdentityConflict")
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("Id", cocktailDataModel.Id);
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Cocktails_CocktailName" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("CocktailName", cocktailDataModel.CocktailName);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void UpdElement(CocktailDataModel cocktailDataModel)
{
try
{
var element = GetCocktailById(cocktailDataModel.Id) ?? throw new ElementNotFoundException(cocktailDataModel.Id);
_dbContext.Cocktails.Update(_mapper.Map(cocktailDataModel, element));
_dbContext.SaveChanges();
}
catch (ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Cocktails_CocktailName" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("CocktailName", cocktailDataModel.CocktailName);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void DelElement(string id)
{
try
{
var element = GetCocktailById(id) ?? throw new ElementNotFoundException(id);
_dbContext.Cocktails.Remove(element);
_dbContext.SaveChanges();
}
catch (ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void ResElement(string id)
{
try
{
var element = GetCocktailById(id) ?? throw new ElementNotFoundException(id);
_dbContext.SaveChanges();
}
catch
{
_dbContext.ChangeTracker.Clear();
throw;
}
}
private Cocktail? GetCocktailById(string id) => _dbContext.Cocktails.FirstOrDefault(x => x.Id == id);
}

View File

@@ -0,0 +1,153 @@
using AutoMapper;
using SquirrelContract.DataModels;
using SquirrelContract.Exceptions;
using SquirrelContract.StoragesContracts;
using SquirrelDatabase.Models;
namespace SquirrelDatabase.Implementations;
public class EmployeeStorageContract : IEmployeeStorageContract
{
private readonly SquirrelDbContext _dbContext;
private readonly Mapper _mapper;
public EmployeeStorageContract(SquirrelDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.AddMaps(typeof(SquirrelDbContext).Assembly);
});
_mapper = new Mapper(config);
}
public List<EmployeeDataModel> GetList(bool onlyActive = true, string? postId = null, DateTime? fromBirthDate = null, DateTime? toBirthDate = null, DateTime? fromEmploymentDate = null, DateTime? toEmploymentDate = null)
{
try
{
var query = _dbContext.Employees.AsQueryable();
if (onlyActive)
{
query = query.Where(x => !x.IsDeleted);
}
if (postId is not null)
{
query = query.Where(x => x.PostId == postId);
}
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 [.. query.Select(x => _mapper.Map<EmployeeDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public EmployeeDataModel? GetElementById(string id)
{
try
{
return _mapper.Map<EmployeeDataModel>(GetEmployeeById(id));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public EmployeeDataModel? GetElementByFIO(string fio)
{
try
{
return _mapper.Map<EmployeeDataModel>(_dbContext.Employees.FirstOrDefault(x => x.FIO == fio));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public EmployeeDataModel? GetElementByEmail(string email)
{
try
{
return _mapper.Map<EmployeeDataModel>(_dbContext.Employees.FirstOrDefault(x => x.Email == email));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void AddElement(EmployeeDataModel employeeDataModel)
{
try
{
_dbContext.Employees.Add(_mapper.Map<Employee>(employeeDataModel));
_dbContext.SaveChanges();
}
catch (InvalidOperationException ex) when (ex.TargetSite?.Name == "ThrowIdentityConflict")
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("Id", employeeDataModel.Id);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void UpdElement(EmployeeDataModel employeeDataModel)
{
try
{
var element = GetEmployeeById(employeeDataModel.Id) ?? throw new ElementNotFoundException(employeeDataModel.Id);
_dbContext.Employees.Update(_mapper.Map(employeeDataModel, 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 = GetEmployeeById(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 Employee? GetEmployeeById(string id) => _dbContext.Employees.FirstOrDefault(x => x.Id == id && !x.IsDeleted);
}

View File

@@ -0,0 +1,190 @@
using AutoMapper;
using Microsoft.EntityFrameworkCore;
using Npgsql;
using SquirrelContract.DataModels;
using SquirrelContract.Exceptions;
using SquirrelContract.StoragesContracts;
using SquirrelDatabase.Models;
namespace SquirrelDatabase.Implementations;
public class PostStorageContract : IPostStorageContract
{
private readonly SquirrelDbContext _dbContext;
private readonly Mapper _mapper;
public PostStorageContract(SquirrelDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Post, PostDataModel>()
.ForMember(x => x.Id, x => x.MapFrom(src => src.PostId));
cfg.CreateMap<PostDataModel, Post>()
.ForMember(x => x.Id, x => x.Ignore())
.ForMember(x => x.PostId, x => x.MapFrom(src => src.Id))
.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<PostDataModel> GetList(bool onlyActual = true)
{
try
{
var query = _dbContext.Posts.AsQueryable();
if (onlyActual)
{
query = query.Where(x => x.IsActual);
}
return [.. query.Select(x => _mapper.Map<PostDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public List<PostDataModel> GetPostWithHistory(string postId)
{
try
{
return [.. _dbContext.Posts.Where(x => x.PostId == postId).Select(x => _mapper.Map<PostDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public PostDataModel? GetElementById(string id)
{
try
{
return _mapper.Map<PostDataModel>(_dbContext.Posts.FirstOrDefault(x => x.PostId == id && x.IsActual));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public PostDataModel? GetElementByName(string name)
{
try
{
return _mapper.Map<PostDataModel>(_dbContext.Posts.FirstOrDefault(x => x.PostName == name && x.IsActual));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void AddElement(PostDataModel postDataModel)
{
try
{
_dbContext.Posts.Add(_mapper.Map<Post>(postDataModel));
_dbContext.SaveChanges();
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Posts_PostName_IsActual" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("PostName", postDataModel.PostName);
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Posts_PostId_IsActual" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("PostId", postDataModel.Id);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void UpdElement(PostDataModel postDataModel)
{
try
{
var transaction = _dbContext.Database.BeginTransaction();
try
{
var element = GetPostById(postDataModel.Id) ?? throw new ElementNotFoundException(postDataModel.Id);
if (!element.IsActual)
{
throw new ElementDeletedException(postDataModel.Id);
}
element.IsActual = false;
_dbContext.SaveChanges();
var newElement = _mapper.Map<Post>(postDataModel);
_dbContext.Posts.Add(newElement);
_dbContext.SaveChanges();
transaction.Commit();
}
catch
{
transaction.Rollback();
throw;
}
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Posts_PostName_IsActual" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("PostName", postDataModel.PostName);
}
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 = GetPostById(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 = GetPostById(id) ?? throw new ElementNotFoundException(id);
element.IsActual = true;
_dbContext.SaveChanges();
}
catch
{
_dbContext.ChangeTracker.Clear();
throw;
}
}
private Post? GetPostById(string id) => _dbContext.Posts.Where(x => x.PostId == id).OrderByDescending(x => x.ChangeDate).FirstOrDefault();
}

View File

@@ -0,0 +1,57 @@
using AutoMapper;
using BarBelochkaContract.DataModels;
using SquirrelContract.Exceptions;
using SquirrelContract.StoragesContracts;
using SquirrelDatabase.Models;
namespace SquirrelDatabase.Implementations;
public class SalaryStorageContract : ISalaryStorageContract
{
private readonly SquirrelDbContext _dbContext;
private readonly Mapper _mapper;
public SalaryStorageContract(SquirrelDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Salary, SalaryDataModel>();
cfg.CreateMap<SalaryDataModel, Salary>()
.ForMember(dest => dest.EmployeeSalary, opt => opt.MapFrom(src => src.Salary));
});
_mapper = new Mapper(config);
}
public List<SalaryDataModel> GetList(DateTime startDate, DateTime endDate, string? employeeId = null)
{
try
{
var query = _dbContext.Salaries.Where(x => x.SalaryDate >= startDate && x.SalaryDate <= endDate);
if (employeeId is not null)
{
query = query.Where(x => x.EmployeeId == employeeId);
}
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,112 @@
using AutoMapper;
using Microsoft.EntityFrameworkCore;
using SquirrelContract.DataModels;
using SquirrelContract.Exceptions;
using SquirrelContract.StoragesContracts;
using SquirrelDatabase.Models;
namespace SquirrelDatabase.Implementations;
public class SaleStorageContract : ISaleStorageContract
{
private readonly SquirrelDbContext _dbContext;
private readonly Mapper _mapper;
public SaleStorageContract(SquirrelDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<SaleCocktail, SaleCocktailDataModel>();
cfg.CreateMap<SaleCocktailDataModel, SaleCocktail>();
cfg.CreateMap<Sale, SaleDataModel>();
cfg.CreateMap<SaleDataModel, Sale>()
.ForMember(x => x.IsCancel, x => x.MapFrom(src => false))
.ForMember(x => x.SaleCocktails, x => x.MapFrom(src => src.Cocktails));
});
_mapper = new Mapper(config);
}
public List<SaleDataModel> GetList(DateTime? startDate = null, DateTime? endDate = null, string? employeeId = null, string? clientId = null, string? cocktailId = null)
{
try
{
var query = _dbContext.Sales.Include(x => x.SaleCocktails).AsQueryable();
if (startDate is not null && endDate is not null)
{
query = query.Where(x => x.SaleDate >= startDate && x.SaleDate < endDate);
}
if (employeeId is not null)
{
query = query.Where(x => x.EmployeeId == employeeId);
}
if (clientId is not null)
{
query = query.Where(x => x.ClientId == clientId);
}
if (cocktailId is not null)
{
query = query.Where(x => x.SaleCocktails!.Any(y => y.CocktailId == cocktailId));
}
return [.. query.Select(x => _mapper.Map<SaleDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public SaleDataModel? GetElementById(string id)
{
try
{
return _mapper.Map<SaleDataModel>(GetSaleById(id));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void AddElement(SaleDataModel saleDataModel)
{
try
{
_dbContext.Sales.Add(_mapper.Map<Sale>(saleDataModel));
_dbContext.SaveChanges();
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void DelElement(string id)
{
try
{
var element = GetSaleById(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 Sale? GetSaleById(string id) => _dbContext.Sales.FirstOrDefault(x => x.Id == id);
}

View File

@@ -0,0 +1,100 @@
using AutoMapper;
using Microsoft.EntityFrameworkCore;
using SquirrelContract.DataModels;
using SquirrelContract.Exceptions;
using SquirrelContract.StoragesContracts;
using SquirrelDatabase.Models;
using System;
namespace SquirrelDatabase.Implementations;
public class SupplyStorageContract : ISupplyStorageContract
{
private readonly SquirrelDbContext _dbContext;
private readonly IMapper _mapper;
public SupplyStorageContract(SquirrelDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<SupplyCocktail, SupplyCocktailDataModel>();
cfg.CreateMap<SupplyCocktailDataModel, SupplyCocktail>();
cfg.CreateMap<Supply, SupplyDataModel>();
cfg.CreateMap<SupplyDataModel, Supply>()
.ForMember(x => x.Cocktails, x => x.MapFrom(src => src.Cocktails));
});
_mapper = new Mapper(config);
}
public List<SupplyDataModel> GetList(DateTime? startDate = null, DateTime? endDate = null, string? cocktailId = null)
{
try
{
var query = _dbContext.Supplies.Include(x => x.Cocktails).AsQueryable();
if (startDate is not null && endDate is not null)
{
query = query.Where(x => x.SupplyDate >= startDate && x.SupplyDate < endDate);
}
if (cocktailId is not null)
{
query = query.Where(x => x.Cocktails!.Any(y => y.CocktailId == cocktailId));
}
return [.. query.Select(x => _mapper.Map<SupplyDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public SupplyDataModel GetElementById(string id)
{
try
{
return _mapper.Map<SupplyDataModel>(GetSuppliesById(id));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void AddElement(SupplyDataModel suppliesDataModel)
{
try
{
_dbContext.Supplies.Add(_mapper.Map<Supply>(suppliesDataModel));
_dbContext.SaveChanges();
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void UpdateElement(SupplyDataModel suppliesDataModel)
{
try
{
var element = GetSuppliesById(suppliesDataModel.Id) ?? throw new ElementNotFoundException(suppliesDataModel.Id);
_dbContext.Supplies.Update(_mapper.Map(suppliesDataModel, element));
_dbContext.SaveChanges();
}
catch (ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
private Supply? GetSuppliesById(string id) => _dbContext.Supplies.FirstOrDefault(x => x.Id == id);
}

View File

@@ -0,0 +1,208 @@
using AutoMapper;
using SquirrelContract.DataModels;
using SquirrelContract.Exceptions;
using SquirrelContract.StoragesContracts;
using SquirrelDatabase.Models;
namespace SquirrelDatabase.Implementations;
public class WarehouseStorageContract : IWarehouseStorageContract
{
private readonly SquirrelDbContext _dbContext;
private readonly Mapper _mapper;
public WarehouseStorageContract(SquirrelDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<WarehouseCocktail, WarehouseCocktailDataModel>();
cfg.CreateMap<WarehouseCocktailDataModel, WarehouseCocktail>();
cfg.CreateMap<Warehouse, WarehouseDataModel>();
cfg.CreateMap<WarehouseDataModel, Warehouse>()
.ForMember(x => x.Cocktails, x => x.MapFrom(src => src.Cocktails));
});
_mapper = new Mapper(config);
}
public List<WarehouseDataModel> GetList()
{
try
{
return [.. _dbContext.Warehouses.Select(x => _mapper.Map<WarehouseDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public WarehouseDataModel GetElementById(string id)
{
try
{
return _mapper.Map<WarehouseDataModel>(GetWarehouseById(id));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public WarehouseDataModel GetElementByName(string name)
{
try
{
return _mapper.Map<WarehouseDataModel>(_dbContext.Warehouses.FirstOrDefault(x => x.Name == name));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void AddElement(WarehouseDataModel warehouseDataModel)
{
try
{
_dbContext.Warehouses.Add(_mapper.Map<Warehouse>(warehouseDataModel));
_dbContext.SaveChanges();
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void UpdElement(WarehouseDataModel warehouseDataModel)
{
try
{
var element = GetWarehouseById(warehouseDataModel.Id) ?? throw new ElementNotFoundException(warehouseDataModel.Id);
_dbContext.Warehouses.Update(_mapper.Map(warehouseDataModel, element));
_dbContext.SaveChanges();
}
catch (ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void DelElement(string id)
{
try
{
var element = GetWarehouseById(id) ?? throw new ElementNotFoundException(id);
_dbContext.Warehouses.Remove(element);
_dbContext.SaveChanges();
}
catch (ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void UpdWarehouseOnSupply(string warehouseId, string cocktailId, int count)
{
using var transaction = _dbContext.Database.BeginTransaction();
try
{
var warehouse = _dbContext.Warehouses.FirstOrDefault(w => w.Id == warehouseId);
if (warehouse == null)
{
throw new ElementNotFoundException($"Warehouse with id {warehouseId} not found.");
}
var warehouseCocktail = warehouse.Cocktails.FirstOrDefault(c => c.CocktailId == cocktailId);
if (warehouseCocktail != null)
{
warehouseCocktail.Count += count;
}
else
{
warehouse.Cocktails.Add(new WarehouseCocktail
{
WarehouseId = warehouseId,
CocktailId = cocktailId,
Count = count
});
}
_dbContext.SaveChanges();
transaction.Commit();
}
catch (Exception ex)
{
transaction.Rollback();
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public bool CheckCocktails(SaleDataModel saleDataModel)
{
using var transaction = _dbContext.Database.BeginTransaction();
try
{
foreach (var saleCocktail in saleDataModel.Cocktails)
{
int requiredCount = saleCocktail.Count;
var warehousesWithCocktail = _dbContext.Warehouses
.Where(w => w.Cocktails.Any(c => c.CocktailId == saleCocktail.CocktailId && c.Count > 0))
.ToList();
foreach (var warehouse in warehousesWithCocktail)
{
var warehouseCocktail = warehouse.Cocktails
.FirstOrDefault(c => c.CocktailId == saleCocktail.CocktailId);
if (warehouseCocktail == null || warehouseCocktail.Count == 0)
continue;
int toWithdraw = Math.Min(warehouseCocktail.Count, requiredCount);
warehouseCocktail.Count -= toWithdraw;
requiredCount -= toWithdraw;
_dbContext.SaveChanges();
if (requiredCount == 0)
break;
}
if (requiredCount > 0)
{
transaction.Rollback();
return false;
}
}
_dbContext.SaveChanges();
transaction.Commit();
return true;
}
catch (Exception ex)
{
transaction.Rollback();
throw new StorageException(ex);
}
}
private Warehouse? GetWarehouseById(string id) => _dbContext.Warehouses.FirstOrDefault(x => x.Id == id);
}

View File

@@ -0,0 +1,18 @@
using AutoMapper;
using SquirrelContract.DataModels;
using System.ComponentModel.DataAnnotations.Schema;
namespace SquirrelDatabase.Models;
[AutoMap(typeof(ClientDataModel), ReverseMap = true)]
public class Client
{
public required string Id { get; set; } = Guid.NewGuid().ToString();
public required string FIO { get; set; }
public required string PhoneNumber { get; set; }
public double DiscountSize { get; set; }
[ForeignKey("ClientId")]
public List<Sale>? Sales { get; set; }
}

View File

@@ -0,0 +1,18 @@
using SquirrelContract.Enums;
using System.ComponentModel.DataAnnotations.Schema;
namespace SquirrelDatabase.Models;
public class Cocktail
{
public required string Id { get; set; }
public required string CocktailName { get; set; }
public double Price { get; set; }
public required AlcoholType BaseAlcohol { get; set; }
[ForeignKey("CocktailId")]
public List<CocktailHistory>? CocktailHistories { get; set; }
[ForeignKey("CocktailId")]
public List<SaleCocktail>? SaleCocktails { get; set; }
}

View File

@@ -0,0 +1,14 @@
namespace SquirrelDatabase.Models;
public class CocktailHistory
{
public string Id { get; set; } = Guid.NewGuid().ToString();
public required string CocktailId { get; set; }
public double OldPrice { get; set; }
public DateTime ChangeDate { get; set; }
public Cocktail? Cocktail { get; set; }
}

View File

@@ -0,0 +1,29 @@
using AutoMapper;
using SquirrelContract.DataModels;
using System.ComponentModel.DataAnnotations.Schema;
namespace SquirrelDatabase.Models;
[AutoMap(typeof(EmployeeDataModel), ReverseMap = true)]
public class Employee
{
public required string Id { get; set; }
public required string FIO { get; set; }
public string Email { get; set; }
public string PostId { get; set; }
public DateTime BirthDate { get; set; }
public DateTime EmploymentDate { get; set; }
public bool IsDeleted { get; set; }
[ForeignKey("EmployeeId")]
public List<Salary>? Salaries { get; set; }
[ForeignKey("EmployeeId")]
public List<Sale>? Sales { get; set; }
}

View File

@@ -0,0 +1,22 @@
using AutoMapper;
using SquirrelContract.DataModels;
using SquirrelContract.Enums;
namespace SquirrelDatabase.Models;
public class Post
{
public required string Id { get; set; } = Guid.NewGuid().ToString();
public required string PostId { get; set; }
public required string PostName { get; set; }
public PostType PostType { get; set; }
public double Salary { get; set; }
public bool IsActual { get; set; }
public DateTime ChangeDate { get; set; }
}

View File

@@ -0,0 +1,18 @@
using AutoMapper;
using BarBelochkaContract.DataModels;
namespace SquirrelDatabase.Models;
public class Salary
{
public string Id { get; set; } = Guid.NewGuid().ToString();
public required string EmployeeId { get; set; }
public DateTime SalaryDate { get; set; }
public double EmployeeSalary { get; set; }
public Employee? Employee { get; set; }
}

View File

@@ -0,0 +1,33 @@
using AutoMapper;
using BarBelochkaContract.DataModels;
using SquirrelContract.DataModels;
using SquirrelContract.Enums;
using System.ComponentModel.DataAnnotations.Schema;
namespace SquirrelDatabase.Models;
public class Sale
{
public string Id { get; set; } = Guid.NewGuid().ToString();
public required string EmployeeId { get; set; }
public string? ClientId { get; set; }
public DateTime SaleDate { get; set; }
public double Sum { get; set; }
public DiscountType DiscountType { get; set; }
public double Discount { get; set; }
public bool IsCancel { get; set; }
public Employee? Employee { get; set; }
public Client? Client { get; set; }
[ForeignKey("SaleId")]
public List<SaleCocktail>? SaleCocktails { get; set; }
}

View File

@@ -0,0 +1,10 @@
namespace SquirrelDatabase.Models;
public class SaleCocktail
{
public required string SaleId { get; set; }
public required string CocktailId { get; set; }
public int Count { get; set; }
}

View File

@@ -0,0 +1,14 @@
using AutoMapper;
using SquirrelContract.DataModels;
using System.ComponentModel.DataAnnotations.Schema;
namespace SquirrelDatabase.Models;
public class Supply
{
public required string Id { get; set; }
public DateTime SupplyDate { get; set; }
[ForeignKey("SupplyId")]
public List<SupplyCocktail>? Cocktails { get; set; }
}

View File

@@ -0,0 +1,13 @@
using AutoMapper;
using SquirrelContract.DataModels;
namespace SquirrelDatabase.Models;
public class SupplyCocktail
{
public required string SupplyId { get; set; }
public required string CocktailId { get; set; }
public int Count { get; set; }
public Supply? Supply { get; set; }
public Cocktail? Cocktails { get; set; }
}

View File

@@ -0,0 +1,14 @@
using AutoMapper;
using SquirrelContract.DataModels;
using System.ComponentModel.DataAnnotations.Schema;
namespace SquirrelDatabase.Models;
public class Warehouse
{
public required string Id { get; set; }
public required string Name { get; set; }
[ForeignKey("WarehouseId")]
public List<WarehouseCocktail> Cocktails { get; set; }
}

View File

@@ -0,0 +1,10 @@
namespace SquirrelDatabase.Models;
public class WarehouseCocktail
{
public required string WarehouseId { get; set; }
public required string CocktailId { get; set; }
public int Count { get; set; }
public Warehouse? Warehouse { get; set; }
public Cocktail? Cocktails { get; set; }
}

View File

@@ -0,0 +1,20 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Library</OutputType>
<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.2" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="9.0.3" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\SquirrelContract\SquirrelContract.csproj" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,67 @@
using Microsoft.EntityFrameworkCore;
using SquirrelContract.Infastructure;
using SquirrelDatabase.Models;
namespace SquirrelDatabase;
public class SquirrelDbContext(IConfigurationDatabase configurationDatabase) : DbContext
{
private readonly IConfigurationDatabase? _configurationDatabase = configurationDatabase;
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseNpgsql(_configurationDatabase?.ConnectionString, o => o.SetPostgresVersion(12, 2));
base.OnConfiguring(optionsBuilder);
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Client>().HasIndex(x => x.PhoneNumber).IsUnique();
modelBuilder.Entity<Cocktail>().HasIndex(x => x.CocktailName).IsUnique();
modelBuilder.Entity<Post>()
.HasIndex(e => new { e.PostName, e.IsActual })
.IsUnique()
.HasFilter($"\"{nameof(Post.IsActual)}\" = TRUE");
modelBuilder.Entity<Post>()
.HasIndex(e => new { e.PostId, e.IsActual })
.IsUnique()
.HasFilter($"\"{nameof(Post.IsActual)}\" = TRUE");
modelBuilder.Entity<Warehouse>().HasIndex(x => x.Name).IsUnique();
modelBuilder.Entity<SupplyCocktail>().HasKey(x => new { x.SupplyId, x.CocktailId });
modelBuilder.Entity<WarehouseCocktail>().HasKey(x => new { x.WarehouseId, x.CocktailId });
modelBuilder.Entity<SaleCocktail>().HasKey(x => new { x.SaleId, x.CocktailId });
}
public DbSet<Client> Clients { get; set; }
public DbSet<Post> Posts { get; set; }
public DbSet<Cocktail> Cocktails { get; set; }
public DbSet<CocktailHistory> CocktailHistories { get; set; }
public DbSet<Salary> Salaries { get; set; }
public DbSet<Sale> Sales { get; set; }
public DbSet<SaleCocktail> SaleCocktails { get; set; }
public DbSet<Employee> Employees { get; set; }
public DbSet<Supply> Supplies { get; set; }
public DbSet<Warehouse> Warehouses { get; set; }
public DbSet<SupplyCocktail> SupplyCocktails { get; set; }
public DbSet<WarehouseCocktail> WarehouseCocktails { get; set; }
}

View File

@@ -0,0 +1,351 @@
using SquirrelBusinessLogic.Implementations;
using SquirrelContract.DataModels;
using Moq;
using SquirrelContract.Exceptions;
using SquirrelContract.StoragesContracts;
using Microsoft.Extensions.Logging;
using SquirrelContract.BusinessLogicContracts;
namespace SquirrelTests.BusinessLogicContractsTests;
[TestFixture]
internal class ClientBusinessLogicContractTests
{
private IClientBusinessLogicContract _clientBusinessLogicContract;
private Mock<IClientStorageContract> _clientStorageContract;
[OneTimeSetUp]
public void OneTimeSetUp()
{
_clientStorageContract = new Mock<IClientStorageContract>();
_clientBusinessLogicContract = new ClientBusinessLogicContract(_clientStorageContract.Object, new Mock<ILogger>().Object);
}
[TearDown]
public void TearDown()
{
_clientStorageContract.Reset();
}
[Test]
public void GetAllCLients_ReturnListOfRecords_Test()
{
//Arrange
var listOriginal = new List<ClientDataModel>()
{
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),
};
_clientStorageContract.Setup(x => x.GetList()).Returns(listOriginal);
//Act
var list = _clientBusinessLogicContract.GetAllClients();
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.EquivalentTo(listOriginal));
}
[Test]
public void GetAllClients_ReturnEmptyList_Test()
{
//Arrange
_clientStorageContract.Setup(x => x.GetList()).Returns([]);
//Act
var list = _clientBusinessLogicContract.GetAllClients();
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
_clientStorageContract.Verify(x => x.GetList(), Times.Once);
}
[Test]
public void GetAllClients_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _clientBusinessLogicContract.GetAllClients(), Throws.TypeOf<NullListException>());
_clientStorageContract.Verify(x => x.GetList(), Times.Once);
}
[Test]
public void GetAllClients_StorageThrowError_ThrowException_Test()
{
//Arrange
_clientStorageContract.Setup(x => x.GetList()).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _clientBusinessLogicContract.GetAllClients(), Throws.TypeOf<StorageException>());
_clientStorageContract.Verify(x => x.GetList(), Times.Once);
}
[Test]
public void GetClientByData_GetById_ReturnRecord_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
var record = new ClientDataModel(id, "fio", "+7-111-111-11-11", 0);
_clientStorageContract.Setup(x => x.GetElementById(id)).Returns(record);
//Act
var element = _clientBusinessLogicContract.GetClientByData(id);
//Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.Id, Is.EqualTo(id));
_clientStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetClientByData_GetByFio_ReturnRecord_Test()
{
//Arrange
var fio = "fio";
var record = new ClientDataModel(Guid.NewGuid().ToString(), fio, "+7-111-111-11-11", 0);
_clientStorageContract.Setup(x => x.GetElementByFIO(fio)).Returns(record);
//Act
var element = _clientBusinessLogicContract.GetClientByData(fio);
//Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.FIO, Is.EqualTo(fio));
_clientStorageContract.Verify(x => x.GetElementByFIO(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetClientByData_GetByPhoneNumber_ReturnRecord_Test()
{
//Arrange
var phoneNumber = "+7-111-111-11-11";
var record = new ClientDataModel(Guid.NewGuid().ToString(), "fio", phoneNumber, 0);
_clientStorageContract.Setup(x => x.GetElementByPhoneNumber(phoneNumber)).Returns(record);
//Act
var element = _clientBusinessLogicContract.GetClientByData(phoneNumber);
//Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.PhoneNumber, Is.EqualTo(phoneNumber));
_clientStorageContract.Verify(x => x.GetElementByPhoneNumber(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetClientByData_EmptyData_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _clientBusinessLogicContract.GetClientByData(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _clientBusinessLogicContract.GetClientByData(string.Empty), Throws.TypeOf<ArgumentNullException>());
_clientStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Never);
_clientStorageContract.Verify(x => x.GetElementByPhoneNumber(It.IsAny<string>()), Times.Never);
_clientStorageContract.Verify(x => x.GetElementByFIO(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetClientByData_GetById_NotFoundRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _clientBusinessLogicContract.GetClientByData(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_clientStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
_clientStorageContract.Verify(x => x.GetElementByPhoneNumber(It.IsAny<string>()), Times.Never);
_clientStorageContract.Verify(x => x.GetElementByFIO(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetClientByData_GetByFio_NotFoundRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _clientBusinessLogicContract.GetClientByData("fio"), Throws.TypeOf<ElementNotFoundException>());
_clientStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Never);
_clientStorageContract.Verify(x => x.GetElementByFIO(It.IsAny<string>()), Times.Once);
_clientStorageContract.Verify(x => x.GetElementByPhoneNumber(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetClientByData_GetByPhoneNumber_NotFoundRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _clientBusinessLogicContract.GetClientByData("+7-111-111-11-12"), Throws.TypeOf<ElementNotFoundException>());
_clientStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Never);
_clientStorageContract.Verify(x => x.GetElementByFIO(It.IsAny<string>()), Times.Never);
_clientStorageContract.Verify(x => x.GetElementByPhoneNumber(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetClientByData_StorageThrowError_ThrowException_Test()
{
//Arrange
_clientStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
_clientStorageContract.Setup(x => x.GetElementByFIO(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
_clientStorageContract.Setup(x => x.GetElementByPhoneNumber(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _clientBusinessLogicContract.GetClientByData(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
Assert.That(() => _clientBusinessLogicContract.GetClientByData("fio"), Throws.TypeOf<StorageException>());
Assert.That(() => _clientBusinessLogicContract.GetClientByData("+7-111-111-11-12"), Throws.TypeOf<StorageException>());
_clientStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
_clientStorageContract.Verify(x => x.GetElementByFIO(It.IsAny<string>()), Times.Once);
_clientStorageContract.Verify(x => x.GetElementByPhoneNumber(It.IsAny<string>()), Times.Once);
}
[Test]
public void InsertClient_CorrectRecord_Test()
{
//Arrange
var flag = false;
var record = new ClientDataModel(Guid.NewGuid().ToString(), "fio", "+7-111-111-11-11", 10);
_clientStorageContract.Setup(x => x.AddElement(It.IsAny<ClientDataModel>()))
.Callback((ClientDataModel x) =>
{
flag = x.Id == record.Id && x.FIO == record.FIO &&
x.PhoneNumber == record.PhoneNumber && x.DiscountSize == record.DiscountSize;
});
//Act
_clientBusinessLogicContract.InsertClient(record);
//Assert
_clientStorageContract.Verify(x => x.AddElement(It.IsAny<ClientDataModel>()), Times.Once);
Assert.That(flag);
}
[Test]
public void InsertClient_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_clientStorageContract.Setup(x => x.AddElement(It.IsAny<ClientDataModel>())).Throws(new ElementExistsException("Data", "Data"));
//Act&Assert
Assert.That(() => _clientBusinessLogicContract.InsertClient(new(Guid.NewGuid().ToString(), "fio", "+7-111-111-11-11", 0)), Throws.TypeOf<ElementExistsException>());
_clientStorageContract.Verify(x => x.AddElement(It.IsAny<ClientDataModel>()), Times.Once);
}
[Test]
public void InsertClient_NullRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _clientBusinessLogicContract.InsertClient(null), Throws.TypeOf<ArgumentNullException>());
_clientStorageContract.Verify(x => x.AddElement(It.IsAny<ClientDataModel>()), Times.Never);
}
[Test]
public void InsertClient_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _clientBusinessLogicContract.InsertClient(new ClientDataModel("id", "fio", "+7-111-111-11-11", 10)), Throws.TypeOf<ValidationException>());
_clientStorageContract.Verify(x => x.AddElement(It.IsAny<ClientDataModel>()), Times.Never);
}
[Test]
public void InsertClient_StorageThrowError_ThrowException_Test()
{
//Arrange
_clientStorageContract.Setup(x => x.AddElement(It.IsAny<ClientDataModel>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _clientBusinessLogicContract.InsertClient(new(Guid.NewGuid().ToString(), "fio", "+7-111-111-11-11", 0)), Throws.TypeOf<StorageException>());
_clientStorageContract.Verify(x => x.AddElement(It.IsAny<ClientDataModel>()), Times.Once);
}
[Test]
public void UpdateClient_CorrectRecord_Test()
{
//Arrange
var flag = false;
var record = new ClientDataModel(Guid.NewGuid().ToString(), "fio", "+7-111-111-11-11", 0);
_clientStorageContract.Setup(x => x.UpdElement(It.IsAny<ClientDataModel>()))
.Callback((ClientDataModel x) =>
{
flag = x.Id == record.Id && x.FIO == record.FIO &&
x.PhoneNumber == record.PhoneNumber && x.DiscountSize == record.DiscountSize;
});
//Act
_clientBusinessLogicContract.UpdateClient(record);
//Assert
_clientStorageContract.Verify(x => x.UpdElement(It.IsAny<ClientDataModel>()), Times.Once);
Assert.That(flag);
}
[Test]
public void UpdateClient_RecordWithIncorrectData_ThrowException_Test()
{
//Arrange
_clientStorageContract.Setup(x => x.UpdElement(It.IsAny<ClientDataModel>())).Throws(new ElementNotFoundException(""));
//Act&Assert
Assert.That(() => _clientBusinessLogicContract.UpdateClient(new(Guid.NewGuid().ToString(), "fio", "+7-111-111-11-11", 0)), Throws.TypeOf<ElementNotFoundException>());
_clientStorageContract.Verify(x => x.UpdElement(It.IsAny<ClientDataModel>()), Times.Once);
}
[Test]
public void UpdateClient_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_clientStorageContract.Setup(x => x.UpdElement(It.IsAny<ClientDataModel>())).Throws(new ElementExistsException("Data", "Data"));
//Act&Assert
Assert.That(() => _clientBusinessLogicContract.UpdateClient(new(Guid.NewGuid().ToString(), "fio", "+7-111-111-11-11", 0)), Throws.TypeOf<ElementExistsException>());
_clientStorageContract.Verify(x => x.UpdElement(It.IsAny<ClientDataModel>()), Times.Once);
}
[Test]
public void UpdateClient_NullRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _clientBusinessLogicContract.UpdateClient(null), Throws.TypeOf<ArgumentNullException>());
_clientStorageContract.Verify(x => x.UpdElement(It.IsAny<ClientDataModel>()), Times.Never);
}
[Test]
public void UpdateClient_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _clientBusinessLogicContract.UpdateClient(new ClientDataModel("id", "fio", "+7-111-111-11-11", 10)), Throws.TypeOf<ValidationException>());
_clientStorageContract.Verify(x => x.UpdElement(It.IsAny<ClientDataModel>()), Times.Never);
}
[Test]
public void UpdateClient_StorageThrowError_ThrowException_Test()
{
//Arrange
_clientStorageContract.Setup(x => x.UpdElement(It.IsAny<ClientDataModel>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _clientBusinessLogicContract.UpdateClient(new(Guid.NewGuid().ToString(), "fio", "+7-111-111-11-11", 0)), Throws.TypeOf<StorageException>());
_clientStorageContract.Verify(x => x.UpdElement(It.IsAny<ClientDataModel>()), Times.Once);
}
[Test]
public void DeleteClient_CorrectRecord_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
var flag = false;
_clientStorageContract.Setup(x => x.DelElement(It.Is((string x) => x == id))).Callback(() => { flag = true; });
//Act
_clientBusinessLogicContract.DeleteClient(id);
//Assert
_clientStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
Assert.That(flag);
}
[Test]
public void DeleteClient_RecordWithIncorrectId_ThrowException_Test()
{
//Arrange
_clientStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new ElementNotFoundException(""));
//Act&Assert
Assert.That(() => _clientBusinessLogicContract.DeleteClient(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_clientStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
}
[Test]
public void DeleteClient_IdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _clientBusinessLogicContract.DeleteClient(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _clientBusinessLogicContract.DeleteClient(string.Empty), Throws.TypeOf<ArgumentNullException>());
_clientStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Never);
}
[Test]
public void DeleteClient_IdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _clientBusinessLogicContract.DeleteClient("id"), Throws.TypeOf<ValidationException>());
_clientStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Never);
}
[Test]
public void DeleteClient_StorageThrowError_ThrowException_Test()
{
//Arrange
_clientStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _clientBusinessLogicContract.DeleteClient(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_clientStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
}
}

View File

@@ -0,0 +1,390 @@
using Microsoft.Extensions.Logging;
using Moq;
using SquirrelBusinessLogic.Implementations;
using SquirrelContract.BusinessLogicContracts;
using SquirrelContract.DataModels;
using SquirrelContract.Enums;
using SquirrelContract.Exceptions;
using SquirrelContract.StoragesContracts;
using System.Xml.Linq;
using static NUnit.Framework.Internal.OSPlatform;
namespace SquirrelTests.BusinessLogicContractsTests;
[TestFixture]
internal class CocktailBusinessLogicContractTests
{
private CocktailBusinessLogicContract _cocktailBusinessLogicContract;
private Mock<ICocktailStorageContract> _cocktailStorageContract;
[OneTimeSetUp]
public void OneTimeSetUp()
{
_cocktailStorageContract = new Mock<ICocktailStorageContract>();
_cocktailBusinessLogicContract = new CocktailBusinessLogicContract(_cocktailStorageContract.Object, new Mock<ILogger>().Object);
}
[TearDown]
public void TearDown()
{
_cocktailStorageContract.Reset();
}
[Test]
public void GetAllCocktails_ReturnListOfRecords_Test()
{
//Arrange
var listOriginal = new List<CocktailDataModel>()
{
new(Guid.NewGuid().ToString(), "name 1", 15.5, AlcoholType.Wine),
new(Guid.NewGuid().ToString(), "name 2", 15.5, AlcoholType.Wine),
new(Guid.NewGuid().ToString(), "name 3", 15.5, AlcoholType.Wine),
};
_cocktailStorageContract.Setup(x => x.GetList()).Returns(listOriginal);
//Act
var list = _cocktailBusinessLogicContract.GetAllCocktails();
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.EquivalentTo(listOriginal));
}
[Test]
public void GetAllCocktails_ReturnEmptyList_Test()
{
//Arrange
_cocktailStorageContract.Setup(x => x.GetList()).Returns([]);
//Act
var list = _cocktailBusinessLogicContract.GetAllCocktails();
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
_cocktailStorageContract.Verify(x => x.GetList(), Times.Once);
}
[Test]
public void GetAllCocktails_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _cocktailBusinessLogicContract.GetAllCocktails(), Throws.TypeOf<NullListException>());
_cocktailStorageContract.Verify(x => x.GetList(), Times.Once);
}
[Test]
public void GetAllCocktails_StorageThrowError_ThrowException_Test()
{
//Arrange
_cocktailStorageContract.Setup(x => x.GetList()).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _cocktailBusinessLogicContract.GetAllCocktails(), Throws.TypeOf<StorageException>());
_cocktailStorageContract.Verify(x => x.GetList(), Times.Once);
}
[Test]
public void GetCocktailHistoryByCocktail_ReturnListOfRecords_Test()
{
//Arrange
var cocktailId = Guid.NewGuid().ToString();
var listOriginal = new List<CocktailHistoryDataModel>()
{
new(Guid.NewGuid().ToString(), 10),
new(Guid.NewGuid().ToString(), 15),
new(Guid.NewGuid().ToString(), 10),
};
_cocktailStorageContract.Setup(x => x.GetHistoryByCocktailId(It.IsAny<string>())).Returns(listOriginal);
//Act
var list = _cocktailBusinessLogicContract.GetCocktailHistoryByCocktail(cocktailId);
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.EquivalentTo(listOriginal));
_cocktailStorageContract.Verify(x => x.GetHistoryByCocktailId(cocktailId), Times.Once);
}
[Test]
public void GetCocktailHistoryByCocktail_ReturnEmptyList_Test()
{
//Arrange
_cocktailStorageContract.Setup(x => x.GetHistoryByCocktailId(It.IsAny<string>())).Returns([]);
//Act
var list = _cocktailBusinessLogicContract.GetCocktailHistoryByCocktail(Guid.NewGuid().ToString());
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
_cocktailStorageContract.Verify(x => x.GetHistoryByCocktailId(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetCocktailHistoryByCocktail_CocktailIdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _cocktailBusinessLogicContract.GetCocktailHistoryByCocktail(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _cocktailBusinessLogicContract.GetCocktailHistoryByCocktail(string.Empty), Throws.TypeOf<ArgumentNullException>());
_cocktailStorageContract.Verify(x => x.GetHistoryByCocktailId(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetCocktailHistoryByCocktail_CocktailIdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _cocktailBusinessLogicContract.GetCocktailHistoryByCocktail("cocktailId"), Throws.TypeOf<ValidationException>());
_cocktailStorageContract.Verify(x => x.GetHistoryByCocktailId(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetCocktailHistoryByCocktail_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _cocktailBusinessLogicContract.GetCocktailHistoryByCocktail(Guid.NewGuid().ToString()), Throws.TypeOf<NullListException>());
_cocktailStorageContract.Verify(x => x.GetHistoryByCocktailId(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetCocktailHistoryByCocktail_StorageThrowError_ThrowException_Test()
{
//Arrange
_cocktailStorageContract.Setup(x => x.GetHistoryByCocktailId(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _cocktailBusinessLogicContract.GetCocktailHistoryByCocktail(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_cocktailStorageContract.Verify(x => x.GetHistoryByCocktailId(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetCocktailByData_GetById_ReturnRecord_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
var record = new CocktailDataModel(id, "name", 10, AlcoholType.Wine);
_cocktailStorageContract.Setup(x => x.GetElementById(id)).Returns(record);
//Act
var element = _cocktailBusinessLogicContract.GetCocktailByData(id);
//Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.Id, Is.EqualTo(id));
_cocktailStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetCocktailByData_GetByName_ReturnRecord_Test()
{
//Arrange
var name = "name";
var record = new CocktailDataModel(Guid.NewGuid().ToString(), name, 10, AlcoholType.Wine);
_cocktailStorageContract.Setup(x => x.GetElementByName(name)).Returns(record);
//Act
var element = _cocktailBusinessLogicContract.GetCocktailByData(name);
//Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.CocktailName, Is.EqualTo(name));
_cocktailStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetCocktailByData_EmptyData_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _cocktailBusinessLogicContract.GetCocktailByData(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _cocktailBusinessLogicContract.GetCocktailByData(string.Empty), Throws.TypeOf<ArgumentNullException>());
_cocktailStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Never);
_cocktailStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetCocktailByData_GetById_NotFoundRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _cocktailBusinessLogicContract.GetCocktailByData(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_cocktailStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetCocktailByData_GetByName_NotFoundRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _cocktailBusinessLogicContract.GetCocktailByData("name"), Throws.TypeOf<ElementNotFoundException>());
_cocktailStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetCocktailByData_StorageThrowError_ThrowException_Test()
{
//Arrange
_cocktailStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
_cocktailStorageContract.Setup(x => x.GetElementByName(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _cocktailBusinessLogicContract.GetCocktailByData(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
Assert.That(() => _cocktailBusinessLogicContract.GetCocktailByData("name"), Throws.TypeOf<StorageException>());
_cocktailStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
_cocktailStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Once);
}
[Test]
public void InsertCocktail_CorrectRecord_Test()
{
//Arrange
var flag = false;
var record = new CocktailDataModel(Guid.NewGuid().ToString(), "name", 10, AlcoholType.Wine);
_cocktailStorageContract.Setup(x => x.AddElement(It.IsAny<CocktailDataModel>()))
.Callback((CocktailDataModel x) =>
{
flag = x.Id == record.Id && x.CocktailName == record.CocktailName &&
x.Price == record.Price && x.BaseAlcohol == record.BaseAlcohol;
});
//Act
_cocktailBusinessLogicContract.InsertCocktail(record);
//Assert
_cocktailStorageContract.Verify(x => x.AddElement(It.IsAny<CocktailDataModel>()), Times.Once);
Assert.That(flag);
}
[Test]
public void InsertCocktail_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_cocktailStorageContract.Setup(x => x.AddElement(It.IsAny<CocktailDataModel>())).Throws(new ElementExistsException("Data", "Data"));
//Act&Assert
Assert.That(() => _cocktailBusinessLogicContract.InsertCocktail(new(Guid.NewGuid().ToString(), "name", 10, AlcoholType.Wine)), Throws.TypeOf<ElementExistsException>());
_cocktailStorageContract.Verify(x => x.AddElement(It.IsAny<CocktailDataModel>()), Times.Once);
}
[Test]
public void InsertCocktail_NullRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _cocktailBusinessLogicContract.InsertCocktail(null), Throws.TypeOf<ArgumentNullException>());
_cocktailStorageContract.Verify(x => x.AddElement(It.IsAny<CocktailDataModel>()), Times.Never);
}
[Test]
public void InsertCocktail_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _cocktailBusinessLogicContract.InsertCocktail(new CocktailDataModel("id", "name", 10, AlcoholType.Wine)), Throws.TypeOf<ValidationException>());
_cocktailStorageContract.Verify(x => x.AddElement(It.IsAny<CocktailDataModel>()), Times.Never);
}
[Test]
public void InsertCocktail_StorageThrowError_ThrowException_Test()
{
//Arrange
_cocktailStorageContract.Setup(x => x.AddElement(It.IsAny<CocktailDataModel>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _cocktailBusinessLogicContract.InsertCocktail(new(Guid.NewGuid().ToString(), "name", 10, AlcoholType.Wine)), Throws.TypeOf<StorageException>());
_cocktailStorageContract.Verify(x => x.AddElement(It.IsAny<CocktailDataModel>()), Times.Once);
}
[Test]
public void UpdateCocktail_CorrectRecord_Test()
{
//Arrange
var flag = false;
var record = new CocktailDataModel(Guid.NewGuid().ToString(), "name", 10, AlcoholType.Wine);
_cocktailStorageContract.Setup(x => x.UpdElement(It.IsAny<CocktailDataModel>()))
.Callback((CocktailDataModel x) =>
{
flag = x.Id == record.Id && x.CocktailName == record.CocktailName &&
x.Price == record.Price && x.BaseAlcohol == record.BaseAlcohol;
});
//Act
_cocktailBusinessLogicContract.UpdateCocktail(record);
//Assert
_cocktailStorageContract.Verify(x => x.UpdElement(It.IsAny<CocktailDataModel>()), Times.Once);
Assert.That(flag);
}
[Test]
public void UpdateCocktail_RecordWithIncorrectData_ThrowException_Test()
{
//Arrange
_cocktailStorageContract.Setup(x => x.UpdElement(It.IsAny<CocktailDataModel>())).Throws(new ElementNotFoundException(""));
//Act&Assert
Assert.That(() => _cocktailBusinessLogicContract.UpdateCocktail(new(Guid.NewGuid().ToString(), "name", 10, AlcoholType.Wine)), Throws.TypeOf<ElementNotFoundException>());
_cocktailStorageContract.Verify(x => x.UpdElement(It.IsAny<CocktailDataModel>()), Times.Once);
}
[Test]
public void UpdateCocktail_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_cocktailStorageContract.Setup(x => x.UpdElement(It.IsAny<CocktailDataModel>())).Throws(new ElementExistsException("Data", "Data"));
//Act&Assert
Assert.That(() => _cocktailBusinessLogicContract.UpdateCocktail(new(Guid.NewGuid().ToString(), "name", 10, AlcoholType.Wine)), Throws.TypeOf<ElementExistsException>());
_cocktailStorageContract.Verify(x => x.UpdElement(It.IsAny<CocktailDataModel>()), Times.Once);
}
[Test]
public void UpdateCocktail_NullRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _cocktailBusinessLogicContract.UpdateCocktail(null), Throws.TypeOf<ArgumentNullException>());
_cocktailStorageContract.Verify(x => x.UpdElement(It.IsAny<CocktailDataModel>()), Times.Never);
}
[Test]
public void UpdateCocktail_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _cocktailBusinessLogicContract.UpdateCocktail(new CocktailDataModel("id", "name", 10, AlcoholType.Wine)), Throws.TypeOf<ValidationException>());
_cocktailStorageContract.Verify(x => x.UpdElement(It.IsAny<CocktailDataModel>()), Times.Never);
}
[Test]
public void UpdateCocktail_StorageThrowError_ThrowException_Test()
{
//Arrange
_cocktailStorageContract.Setup(x => x.UpdElement(It.IsAny<CocktailDataModel>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _cocktailBusinessLogicContract.UpdateCocktail(new(Guid.NewGuid().ToString(), "name", 10, AlcoholType.Wine)), Throws.TypeOf<StorageException>());
_cocktailStorageContract.Verify(x => x.UpdElement(It.IsAny<CocktailDataModel>()), Times.Once);
}
[Test]
public void DeleteCocktail_CorrectRecord_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
var flag = false;
_cocktailStorageContract.Setup(x => x.DelElement(It.Is((string x) => x == id))).Callback(() => { flag = true; });
//Act
_cocktailBusinessLogicContract.DeleteCocktail(id);
//Assert
_cocktailStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
Assert.That(flag);
}
[Test]
public void DeleteCocktail_RecordWithIncorrectId_ThrowException_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
_cocktailStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new ElementNotFoundException(id));
//Act&Assert
Assert.That(() => _cocktailBusinessLogicContract.DeleteCocktail(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_cocktailStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
}
[Test]
public void DeleteCocktail_IdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _cocktailBusinessLogicContract.DeleteCocktail(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _cocktailBusinessLogicContract.DeleteCocktail(string.Empty), Throws.TypeOf<ArgumentNullException>());
_cocktailStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Never);
}
[Test]
public void DeleteCocktail_IdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _cocktailBusinessLogicContract.DeleteCocktail("id"), Throws.TypeOf<ValidationException>());
_cocktailStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Never);
}
[Test]
public void DeleteCocktail_StorageThrowError_ThrowException_Test()
{
//Arrange
_cocktailStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _cocktailBusinessLogicContract.DeleteCocktail(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_cocktailStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
}
}

View File

@@ -0,0 +1,582 @@
using Microsoft.Extensions.Logging;
using Moq;
using SquirrelBusinessLogic.Implementations;
using SquirrelContract.BusinessLogicContracts;
using SquirrelContract.DataModels;
using SquirrelContract.Exceptions;
using SquirrelContract.StoragesContracts;
namespace SquirrelTests.BusinessLogicContractsTests;
[TestFixture]
internal class EmployeeBusinessLogicContractTests
{
private EmployeeBusinessLogicContract _employeeBusinessLogicContract;
private Mock<IEmployeeStorageContract> _employeeStorageContract;
[OneTimeSetUp]
public void OneTimeSetUp()
{
_employeeStorageContract = new Mock<IEmployeeStorageContract>();
_employeeBusinessLogicContract = new EmployeeBusinessLogicContract(_employeeStorageContract.Object, new Mock<ILogger>().Object);
}
[TearDown]
public void TearDown()
{
_employeeStorageContract.Reset();
}
[Test]
public void GetAllEmployees_ReturnListOfRecords_Test()
{
//Arrange
var listOriginal = new List<EmployeeDataModel>()
{
new(Guid.NewGuid().ToString(), "fio 1", "gg@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, false),
new(Guid.NewGuid().ToString(), "fio 2", "gg@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, true),
new(Guid.NewGuid().ToString(), "fio 3", "gg@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, false),
};
_employeeStorageContract.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 = _employeeBusinessLogicContract.GetAllEmployees(true);
var list = _employeeBusinessLogicContract.GetAllEmployees(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));
});
_employeeStorageContract.Verify(x => x.GetList(true, null, null, null, null, null), Times.Once);
_employeeStorageContract.Verify(x => x.GetList(false, null, null, null, null, null), Times.Once);
}
[Test]
public void GetAllEmployees_ReturnEmptyList_Test()
{
//Arrange
_employeeStorageContract.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 = _employeeBusinessLogicContract.GetAllEmployees(true);
var list = _employeeBusinessLogicContract.GetAllEmployees(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));
});
_employeeStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), null, null, null, null, null), Times.Exactly(2));
}
[Test]
public void GetAllEmployees_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _employeeBusinessLogicContract.GetAllEmployees(It.IsAny<bool>()), Throws.TypeOf<NullListException>());
_employeeStorageContract.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 GetAllEmployees_StorageThrowError_ThrowException_Test()
{
//Arrange
_employeeStorageContract.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(() => _employeeBusinessLogicContract.GetAllEmployees(It.IsAny<bool>()), Throws.TypeOf<StorageException>());
_employeeStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), null, null, null, null, null), Times.Once);
}
[Test]
public void GetAllEmployeesByPost_ReturnListOfRecords_Test()
{
//Arrange
var postId = Guid.NewGuid().ToString();
var listOriginal = new List<EmployeeDataModel>()
{
new(Guid.NewGuid().ToString(), "fio 1", "gg@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, false),
new(Guid.NewGuid().ToString(), "fio 2", "gg@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, true),
new(Guid.NewGuid().ToString(), "fio 3", "gg@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, false),
};
_employeeStorageContract.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 = _employeeBusinessLogicContract.GetAllEmployeesByPost(postId, true);
var list = _employeeBusinessLogicContract.GetAllEmployeesByPost(postId, 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));
});
_employeeStorageContract.Verify(x => x.GetList(true, postId, null, null, null, null), Times.Once);
_employeeStorageContract.Verify(x => x.GetList(false, postId, null, null, null, null), Times.Once);
}
[Test]
public void GetAllEmployeesByPost_ReturnEmptyList_Test()
{
//Arrange
_employeeStorageContract.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 = _employeeBusinessLogicContract.GetAllEmployeesByPost(Guid.NewGuid().ToString(), true);
var list = _employeeBusinessLogicContract.GetAllEmployeesByPost(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));
});
_employeeStorageContract.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 GetAllEmployeesByPost_PostIdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _employeeBusinessLogicContract.GetAllEmployeesByPost(null, It.IsAny<bool>()), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _employeeBusinessLogicContract.GetAllEmployeesByPost(string.Empty, It.IsAny<bool>()), Throws.TypeOf<ArgumentNullException>());
_employeeStorageContract.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 GetAllEmployeesByPost_PostIdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _employeeBusinessLogicContract.GetAllEmployeesByPost("postId", It.IsAny<bool>()), Throws.TypeOf<ValidationException>());
_employeeStorageContract.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 GetAllEmployeesByPost_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _employeeBusinessLogicContract.GetAllEmployeesByPost(Guid.NewGuid().ToString(), It.IsAny<bool>()), Throws.TypeOf<NullListException>());
_employeeStorageContract.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 GetAllEmployeesByPost_StorageThrowError_ThrowException_Test()
{
//Arrange
_employeeStorageContract.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(() => _employeeBusinessLogicContract.GetAllEmployeesByPost(Guid.NewGuid().ToString(), It.IsAny<bool>()), Throws.TypeOf<StorageException>());
_employeeStorageContract.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 GetAllEmployeesByBirthDate_ReturnListOfRecords_Test()
{
//Arrange
var date = DateTime.UtcNow;
var listOriginal = new List<EmployeeDataModel>()
{
new(Guid.NewGuid().ToString(), "fio 1", "gg@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, false),
new(Guid.NewGuid().ToString(), "fio 2", "gg@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, true),
new(Guid.NewGuid().ToString(), "fio 3", "gg@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, false),
};
_employeeStorageContract.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 = _employeeBusinessLogicContract.GetAllEmployeesByBirthDate(date, date.AddDays(1), true);
var list = _employeeBusinessLogicContract.GetAllEmployeesByBirthDate(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));
});
_employeeStorageContract.Verify(x => x.GetList(true, null, date, date.AddDays(1), null, null), Times.Once);
_employeeStorageContract.Verify(x => x.GetList(false, null, date, date.AddDays(1), null, null), Times.Once);
}
[Test]
public void GetAllEmployeesByBirthDate_ReturnEmptyList_Test()
{
//Arrange
_employeeStorageContract.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 = _employeeBusinessLogicContract.GetAllEmployeesByBirthDate(DateTime.UtcNow, DateTime.UtcNow.AddDays(1), true);
var list = _employeeBusinessLogicContract.GetAllEmployees(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));
});
_employeeStorageContract.Verify(x => x.GetList(true, null, It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), null, null), Times.Once);
_employeeStorageContract.Verify(x => x.GetList(false, null, It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), null, null), Times.Once);
}
[Test]
public void GetAllEmployeesByBirthDate_IncorrectDates_ThrowException_Test()
{
//Arrange
var date = DateTime.UtcNow;
//Act&Assert
Assert.That(() => _employeeBusinessLogicContract.GetAllEmployeesByBirthDate(date, date, It.IsAny<bool>()), Throws.TypeOf<IncorrectDatesException>());
Assert.That(() => _employeeBusinessLogicContract.GetAllEmployeesByBirthDate(date, date.AddSeconds(-1), It.IsAny<bool>()), Throws.TypeOf<IncorrectDatesException>());
_employeeStorageContract.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 GetAllEmployeesByBirthDate_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _employeeBusinessLogicContract.GetAllEmployeesByBirthDate(DateTime.UtcNow, DateTime.UtcNow.AddDays(1), It.IsAny<bool>()), Throws.TypeOf<NullListException>());
_employeeStorageContract.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 GetAllEmployeesByBirthDate_StorageThrowError_ThrowException_Test()
{
//Arrange
_employeeStorageContract.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(() => _employeeBusinessLogicContract.GetAllEmployeesByBirthDate(DateTime.UtcNow, DateTime.UtcNow.AddDays(1), It.IsAny<bool>()), Throws.TypeOf<StorageException>());
_employeeStorageContract.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 GetAllEmployeesByEmploymentDate_ReturnListOfRecords_Test()
{
//Arrange
var date = DateTime.UtcNow;
var listOriginal = new List<EmployeeDataModel>()
{
new(Guid.NewGuid().ToString(), "fio 1", "gg@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, false),
new(Guid.NewGuid().ToString(), "fio 2", "gg@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, true),
new(Guid.NewGuid().ToString(), "fio 3", "gg@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, false),
};
_employeeStorageContract.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 = _employeeBusinessLogicContract.GetAllEmployeesByEmploymentDate(date, date.AddDays(1), true);
var list = _employeeBusinessLogicContract.GetAllEmployeesByEmploymentDate(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));
});
_employeeStorageContract.Verify(x => x.GetList(true, null, null, null, date, date.AddDays(1)), Times.Once);
_employeeStorageContract.Verify(x => x.GetList(false, null, null, null, date, date.AddDays(1)), Times.Once);
}
[Test]
public void GetAllEmployeesByEmploymentDate_ReturnEmptyList_Test()
{
//Arrange
_employeeStorageContract.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 = _employeeBusinessLogicContract.GetAllEmployeesByEmploymentDate(DateTime.UtcNow, DateTime.UtcNow.AddDays(1), true);
var list = _employeeBusinessLogicContract.GetAllEmployeesByEmploymentDate(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));
});
_employeeStorageContract.Verify(x => x.GetList(true, null, null, null, It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Once);
_employeeStorageContract.Verify(x => x.GetList(false, null, null, null, It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Once);
}
[Test]
public void GetAllEmployeesByEmploymentDate_IncorrectDates_ThrowException_Test()
{
//Arrange
var date = DateTime.UtcNow;
//Act&Assert
Assert.That(() => _employeeBusinessLogicContract.GetAllEmployeesByEmploymentDate(date, date, It.IsAny<bool>()), Throws.TypeOf<IncorrectDatesException>());
Assert.That(() => _employeeBusinessLogicContract.GetAllEmployeesByEmploymentDate(date, date.AddSeconds(-1), It.IsAny<bool>()), Throws.TypeOf<IncorrectDatesException>());
_employeeStorageContract.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 GetAllEmployeesByEmploymentDate_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _employeeBusinessLogicContract.GetAllEmployeesByEmploymentDate(DateTime.UtcNow, DateTime.UtcNow.AddDays(1), It.IsAny<bool>()), Throws.TypeOf<NullListException>());
_employeeStorageContract.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 GetAllEmployeesByEmploymentDate_StorageThrowError_ThrowException_Test()
{
//Arrange
_employeeStorageContract.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(() => _employeeBusinessLogicContract.GetAllEmployeesByEmploymentDate(DateTime.UtcNow, DateTime.UtcNow.AddDays(1), It.IsAny<bool>()), Throws.TypeOf<StorageException>());
_employeeStorageContract.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 GetEmployeeByData_GetById_ReturnRecord_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
var record = new EmployeeDataModel(id, "fio", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, false);
_employeeStorageContract.Setup(x => x.GetElementById(id)).Returns(record);
//Act
var element = _employeeBusinessLogicContract.GetEmployeeByData(id);
//Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.Id, Is.EqualTo(id));
_employeeStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetEmployeeByData_GetByFio_ReturnRecord_Test()
{
//Arrange
var fio = "fio";
var record = new EmployeeDataModel(Guid.NewGuid().ToString(), fio, "123@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, false);
_employeeStorageContract.Setup(x => x.GetElementByFIO(fio)).Returns(record);
//Act
var element = _employeeBusinessLogicContract.GetEmployeeByData(fio);
//Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.FIO, Is.EqualTo(fio));
_employeeStorageContract.Verify(x => x.GetElementByFIO(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetEmployeeByData_GetByEmail_ReturnRecord_Test()
{
//Arrange
var email = "123@gmail.com";
var record = new EmployeeDataModel(Guid.NewGuid().ToString(), "fio", email, Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, false);
_employeeStorageContract.Setup(x => x.GetElementByEmail(email)).Returns(record);
//Act
var element = _employeeBusinessLogicContract.GetEmployeeByData(email);
//Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.Email, Is.EqualTo(email));
_employeeStorageContract.Verify(x => x.GetElementByEmail(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetEmployeeByData_EmptyData_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _employeeBusinessLogicContract.GetEmployeeByData(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _employeeBusinessLogicContract.GetEmployeeByData(string.Empty), Throws.TypeOf<ArgumentNullException>());
_employeeStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Never);
_employeeStorageContract.Verify(x => x.GetElementByFIO(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetEmployeeByData_GetById_NotFoundRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _employeeBusinessLogicContract.GetEmployeeByData(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_employeeStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
_employeeStorageContract.Verify(x => x.GetElementByFIO(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetEmployeeByData_GetByFio_NotFoundRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _employeeBusinessLogicContract.GetEmployeeByData("fio"), Throws.TypeOf<ElementNotFoundException>());
_employeeStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Never);
_employeeStorageContract.Verify(x => x.GetElementByFIO(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetEmployeeByData_GetByEmail_NotFoundRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _employeeBusinessLogicContract.GetEmployeeByData("123@gmail.com"), Throws.TypeOf<ElementNotFoundException>());
_employeeStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Never);
_employeeStorageContract.Verify(x => x.GetElementByFIO(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetEmployeeByData_StorageThrowError_ThrowException_Test()
{
//Arrange
_employeeStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
_employeeStorageContract.Setup(x => x.GetElementByFIO(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _employeeBusinessLogicContract.GetEmployeeByData(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
Assert.That(() => _employeeBusinessLogicContract.GetEmployeeByData("fio"), Throws.TypeOf<StorageException>());
_employeeStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
_employeeStorageContract.Verify(x => x.GetElementByFIO(It.IsAny<string>()), Times.Once);
}
[Test]
public void InsertEmployee_CorrectRecord_Test()
{
//Arrange
var flag = false;
var record = new EmployeeDataModel(Guid.NewGuid().ToString(), "fio", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, false);
_employeeStorageContract.Setup(x => x.AddElement(It.IsAny<EmployeeDataModel>()))
.Callback((EmployeeDataModel x) =>
{
flag = x.Id == record.Id && x.FIO == record.FIO && x.PostId == record.PostId && x.BirthDate == record.BirthDate &&
x.EmploymentDate == record.EmploymentDate && x.IsDeleted == record.IsDeleted;
});
//Act
_employeeBusinessLogicContract.InsertEmployee(record);
//Assert
_employeeStorageContract.Verify(x => x.AddElement(It.IsAny<EmployeeDataModel>()), Times.Once);
Assert.That(flag);
}
[Test]
public void InsertEmployee_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_employeeStorageContract.Setup(x => x.AddElement(It.IsAny<EmployeeDataModel>())).Throws(new ElementExistsException("Data", "Data"));
//Act&Assert
Assert.That(() => _employeeBusinessLogicContract.InsertEmployee(new(Guid.NewGuid().ToString(), "fio", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, false)), Throws.TypeOf<ElementExistsException>());
_employeeStorageContract.Verify(x => x.AddElement(It.IsAny<EmployeeDataModel>()), Times.Once);
}
[Test]
public void InsertEmployee_NullRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _employeeBusinessLogicContract.InsertEmployee(null), Throws.TypeOf<ArgumentNullException>());
_employeeStorageContract.Verify(x => x.AddElement(It.IsAny<EmployeeDataModel>()), Times.Never);
}
[Test]
public void InsertEmployee_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _employeeBusinessLogicContract.InsertEmployee(new EmployeeDataModel("id", "fio", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, false)), Throws.TypeOf<ValidationException>());
_employeeStorageContract.Verify(x => x.AddElement(It.IsAny<EmployeeDataModel>()), Times.Never);
}
[Test]
public void InsertEmployee_StorageThrowError_ThrowException_Test()
{
//Arrange
_employeeStorageContract.Setup(x => x.AddElement(It.IsAny<EmployeeDataModel>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _employeeBusinessLogicContract.InsertEmployee(new(Guid.NewGuid().ToString(), "fio", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, false)), Throws.TypeOf<StorageException>());
_employeeStorageContract.Verify(x => x.AddElement(It.IsAny<EmployeeDataModel>()), Times.Once);
}
[Test]
public void UpdateEmployee_CorrectRecord_Test()
{
//Arrange
var flag = false;
var record = new EmployeeDataModel(Guid.NewGuid().ToString(), "fio", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, false);
_employeeStorageContract.Setup(x => x.UpdElement(It.IsAny<EmployeeDataModel>()))
.Callback((EmployeeDataModel x) =>
{
flag = x.Id == record.Id && x.FIO == record.FIO && x.PostId == record.PostId && x.BirthDate == record.BirthDate &&
x.EmploymentDate == record.EmploymentDate && x.IsDeleted == record.IsDeleted;
});
//Act
_employeeBusinessLogicContract.UpdateEmployee(record);
//Assert
_employeeStorageContract.Verify(x => x.UpdElement(It.IsAny<EmployeeDataModel>()), Times.Once);
Assert.That(flag);
}
[Test]
public void UpdateEmployee_RecordWithIncorrectData_ThrowException_Test()
{
//Arrange
_employeeStorageContract.Setup(x => x.UpdElement(It.IsAny<EmployeeDataModel>())).Throws(new ElementNotFoundException(""));
//Act&Assert
Assert.That(() => _employeeBusinessLogicContract.UpdateEmployee(new(Guid.NewGuid().ToString(), "fio", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, false)), Throws.TypeOf<ElementNotFoundException>());
_employeeStorageContract.Verify(x => x.UpdElement(It.IsAny<EmployeeDataModel>()), Times.Once);
}
[Test]
public void UpdateEmployee_NullRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _employeeBusinessLogicContract.UpdateEmployee(null), Throws.TypeOf<ArgumentNullException>());
_employeeStorageContract.Verify(x => x.UpdElement(It.IsAny<EmployeeDataModel>()), Times.Never);
}
[Test]
public void UpdateEmployee_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _employeeBusinessLogicContract.UpdateEmployee(new EmployeeDataModel("id", "fio", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, false)), Throws.TypeOf<ValidationException>());
_employeeStorageContract.Verify(x => x.UpdElement(It.IsAny<EmployeeDataModel>()), Times.Never);
}
[Test]
public void UpdateEmployee_StorageThrowError_ThrowException_Test()
{
//Arrange
_employeeStorageContract.Setup(x => x.UpdElement(It.IsAny<EmployeeDataModel>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _employeeBusinessLogicContract.UpdateEmployee(new(Guid.NewGuid().ToString(), "fio", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, false)), Throws.TypeOf<StorageException>());
_employeeStorageContract.Verify(x => x.UpdElement(It.IsAny<EmployeeDataModel>()), Times.Once);
}
[Test]
public void DeleteEmployee_CorrectRecord_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
var flag = false;
_employeeStorageContract.Setup(x => x.DelElement(It.Is((string x) => x == id))).Callback(() => { flag = true; });
//Act
_employeeBusinessLogicContract.DeleteEmployee(id);
//Assert
_employeeStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
Assert.That(flag);
}
[Test]
public void DeleteEmployee_RecordWithIncorrectId_ThrowException_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
_employeeStorageContract.Setup(x => x.DelElement(It.Is((string x) => x != id))).Throws(new ElementNotFoundException(id));
//Act&Assert
Assert.That(() => _employeeBusinessLogicContract.DeleteEmployee(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_employeeStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
}
[Test]
public void DeleteEmployee_IdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _employeeBusinessLogicContract.DeleteEmployee(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _employeeBusinessLogicContract.DeleteEmployee(string.Empty), Throws.TypeOf<ArgumentNullException>());
_employeeStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Never);
}
[Test]
public void DeleteEmployee_IdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _employeeBusinessLogicContract.DeleteEmployee("id"), Throws.TypeOf<ValidationException>());
_employeeStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Never);
}
[Test]
public void DeleteEmployee_StorageThrowError_ThrowException_Test()
{
//Arrange
_employeeStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _employeeBusinessLogicContract.DeleteEmployee(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_employeeStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
}
}

View File

@@ -0,0 +1,454 @@
using Microsoft.Extensions.Logging;
using Moq;
using SquirrelBusinessLogic.Implementations;
using SquirrelContract.DataModels;
using SquirrelContract.Enums;
using SquirrelContract.Exceptions;
using SquirrelContract.StoragesContracts;
namespace SquirrelTests.BusinessLogicContractsTests;
[TestFixture]
internal class PostBusinessLogicContractTests
{
private PostBusinessLogicContract _postBusinessLogicContract;
private Mock<IPostStorageContract> _postStorageContract;
[OneTimeSetUp]
public void OneTimeSetUp()
{
_postStorageContract = new Mock<IPostStorageContract>();
_postBusinessLogicContract = new PostBusinessLogicContract(_postStorageContract.Object, new Mock<ILogger>().Object);
}
[TearDown]
public void TearDown()
{
_postStorageContract.Reset();
}
[Test]
public void GetAllPosts_ReturnListOfRecords_Test()
{
//Arrange
var listOriginal = new List<PostDataModel>()
{
new(Guid.NewGuid().ToString(),"name 1", PostType.Manager, 10, true, DateTime.UtcNow),
new(Guid.NewGuid().ToString(), "name 2", PostType.Manager, 10, false, DateTime.UtcNow),
new(Guid.NewGuid().ToString(), "name 3", PostType.Manager, 10, true, DateTime.UtcNow),
};
_postStorageContract.Setup(x => x.GetList(It.IsAny<bool>())).Returns(listOriginal);
//Act
var listOnlyActive = _postBusinessLogicContract.GetAllPosts(true);
var listAll = _postBusinessLogicContract.GetAllPosts(false);
//Assert
Assert.Multiple(() =>
{
Assert.That(listOnlyActive, Is.Not.Null);
Assert.That(listAll, Is.Not.Null);
Assert.That(listOnlyActive, Is.EquivalentTo(listOriginal));
Assert.That(listAll, Is.EquivalentTo(listOriginal));
});
_postStorageContract.Verify(x => x.GetList(true), Times.Once);
_postStorageContract.Verify(x => x.GetList(false), Times.Once);
}
[Test]
public void GetAllPosts_ReturnEmptyList_Test()
{
//Arrange
_postStorageContract.Setup(x => x.GetList(It.IsAny<bool>())).Returns([]);
//Act
var listOnlyActive = _postBusinessLogicContract.GetAllPosts(true);
var listAll = _postBusinessLogicContract.GetAllPosts(false);
//Assert
Assert.Multiple(() =>
{
Assert.That(listOnlyActive, Is.Not.Null);
Assert.That(listAll, Is.Not.Null);
Assert.That(listOnlyActive, Has.Count.EqualTo(0));
Assert.That(listAll, Has.Count.EqualTo(0));
});
_postStorageContract.Verify(x => x.GetList(It.IsAny<bool>()), Times.Exactly(2));
}
[Test]
public void GetAllPosts_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.GetAllPosts(It.IsAny<bool>()), Throws.TypeOf<NullListException>());
_postStorageContract.Verify(x => x.GetList(It.IsAny<bool>()), Times.Once);
}
[Test]
public void GetAllPosts_StorageThrowError_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x => x.GetList(It.IsAny<bool>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.GetAllPosts(It.IsAny<bool>()), Throws.TypeOf<StorageException>());
_postStorageContract.Verify(x => x.GetList(It.IsAny<bool>()), Times.Once);
}
[Test]
public void GetAllDataOfPost_ReturnListOfRecords_Test()
{
//Arrange
var postId = Guid.NewGuid().ToString();
var listOriginal = new List<PostDataModel>()
{
new(postId, "name 1", PostType.Manager, 10, true, DateTime.UtcNow),
new(postId, "name 2", PostType.Manager, 10, false, DateTime.UtcNow)
};
_postStorageContract.Setup(x => x.GetPostWithHistory(It.IsAny<string>())).Returns(listOriginal);
//Act
var list = _postBusinessLogicContract.GetAllDataOfPost(postId);
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(2));
_postStorageContract.Verify(x => x.GetPostWithHistory(postId), Times.Once);
}
[Test]
public void GetAllDataOfPost_ReturnEmptyList_Test()
{
//Arrange
_postStorageContract.Setup(x => x.GetPostWithHistory(It.IsAny<string>())).Returns([]);
//Act
var list = _postBusinessLogicContract.GetAllDataOfPost(Guid.NewGuid().ToString());
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
_postStorageContract.Verify(x => x.GetPostWithHistory(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllDataOfPost_PostIdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.GetAllDataOfPost(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _postBusinessLogicContract.GetAllDataOfPost(string.Empty), Throws.TypeOf<ArgumentNullException>());
_postStorageContract.Verify(x => x.GetPostWithHistory(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllDataOfPost_PostIdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.GetAllDataOfPost("id"), Throws.TypeOf<ValidationException>());
_postStorageContract.Verify(x => x.GetPostWithHistory(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllDataOfPost_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.GetAllDataOfPost(Guid.NewGuid().ToString()), Throws.TypeOf<NullListException>());
_postStorageContract.Verify(x => x.GetPostWithHistory(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllDataOfPost_StorageThrowError_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x => x.GetPostWithHistory(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.GetAllDataOfPost(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_postStorageContract.Verify(x => x.GetPostWithHistory(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetPostByData_GetById_ReturnRecord_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
var record = new PostDataModel(id, "name", PostType.Manager, 10, true, DateTime.UtcNow);
_postStorageContract.Setup(x => x.GetElementById(id)).Returns(record);
//Act
var element = _postBusinessLogicContract.GetPostByData(id);
//Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.Id, Is.EqualTo(id));
_postStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetPostByData_GetByName_ReturnRecord_Test()
{
//Arrange
var postName = "name";
var record = new PostDataModel(Guid.NewGuid().ToString(), postName, PostType.Manager, 10, true, DateTime.UtcNow);
_postStorageContract.Setup(x => x.GetElementByName(postName)).Returns(record);
//Act
var element = _postBusinessLogicContract.GetPostByData(postName);
//Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.PostName, Is.EqualTo(postName));
_postStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetPostByData_EmptyData_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.GetPostByData(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _postBusinessLogicContract.GetPostByData(string.Empty), Throws.TypeOf<ArgumentNullException>());
_postStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Never);
_postStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetPostByData_GetById_NotFoundRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.GetPostByData(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_postStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
_postStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetPostByData_GetByName_NotFoundRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.GetPostByData("name"), Throws.TypeOf<ElementNotFoundException>());
_postStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Never);
_postStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetPostByData_StorageThrowError_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
_postStorageContract.Setup(x => x.GetElementByName(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.GetPostByData(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
Assert.That(() => _postBusinessLogicContract.GetPostByData("name"), Throws.TypeOf<StorageException>());
_postStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
_postStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Once);
}
[Test]
public void InsertPost_CorrectRecord_Test()
{
//Arrange
var flag = false;
var record = new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Bartender, 10, true, DateTime.UtcNow.AddDays(-1));
_postStorageContract.Setup(x => x.AddElement(It.IsAny<PostDataModel>()))
.Callback((PostDataModel x) =>
{
flag = x.Id == record.Id && x.PostName == record.PostName && x.PostType == record.PostType && x.Salary == record.Salary &&
x.ChangeDate == record.ChangeDate;
});
//Act
_postBusinessLogicContract.InsertPost(record);
//Assert
_postStorageContract.Verify(x => x.AddElement(It.IsAny<PostDataModel>()), Times.Once);
Assert.That(flag);
}
[Test]
public void InsertPost_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x => x.AddElement(It.IsAny<PostDataModel>())).Throws(new ElementExistsException("Data", "Data"));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.InsertPost(new(Guid.NewGuid().ToString(), "name", PostType.Bartender, 10, true, DateTime.UtcNow)), Throws.TypeOf<ElementExistsException>());
_postStorageContract.Verify(x => x.AddElement(It.IsAny<PostDataModel>()), Times.Once);
}
[Test]
public void InsertPost_NullRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.InsertPost(null), Throws.TypeOf<ArgumentNullException>());
_postStorageContract.Verify(x => x.AddElement(It.IsAny<PostDataModel>()), Times.Never);
}
[Test]
public void InsertPost_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.InsertPost(new PostDataModel("id", "name", PostType.Bartender, 10, true, DateTime.UtcNow)), Throws.TypeOf<ValidationException>());
_postStorageContract.Verify(x => x.AddElement(It.IsAny<PostDataModel>()), Times.Never);
}
[Test]
public void InsertPost_StorageThrowError_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x => x.AddElement(It.IsAny<PostDataModel>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.InsertPost(new(Guid.NewGuid().ToString(), "name", PostType.Bartender, 10, true, DateTime.UtcNow)), Throws.TypeOf<StorageException>());
_postStorageContract.Verify(x => x.AddElement(It.IsAny<PostDataModel>()), Times.Once);
}
[Test]
public void UpdatePost_CorrectRecord_Test()
{
//Arrange
var flag = false;
var record = new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Bartender, 10, true, DateTime.UtcNow.AddDays(-1));
_postStorageContract.Setup(x => x.UpdElement(It.IsAny<PostDataModel>()))
.Callback((PostDataModel x) =>
{
flag = x.Id == record.Id && x.PostName == record.PostName && x.PostType == record.PostType && x.Salary == record.Salary &&
x.ChangeDate == record.ChangeDate;
});
//Act
_postBusinessLogicContract.UpdatePost(record);
//Assert
_postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Once);
Assert.That(flag);
}
[Test]
public void UpdatePost_RecordWithIncorrectData_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x => x.UpdElement(It.IsAny<PostDataModel>())).Throws(new ElementNotFoundException(""));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "name", PostType.Bartender, 10, true, DateTime.UtcNow)), Throws.TypeOf<ElementNotFoundException>());
_postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Once);
}
[Test]
public void UpdatePost_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x => x.UpdElement(It.IsAny<PostDataModel>())).Throws(new ElementExistsException("Data", "Data"));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "anme", PostType.Bartender, 10, true, DateTime.UtcNow)), Throws.TypeOf<ElementExistsException>());
_postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Once);
}
[Test]
public void UpdatePost_NullRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.UpdatePost(null), Throws.TypeOf<ArgumentNullException>());
_postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Never);
}
[Test]
public void UpdatePost_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.UpdatePost(new PostDataModel("id", "name", PostType.Bartender, 10, true, DateTime.UtcNow)), Throws.TypeOf<ValidationException>());
_postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Never);
}
[Test]
public void UpdatePost_StorageThrowError_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x => x.UpdElement(It.IsAny<PostDataModel>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "name", PostType.Bartender, 10, true, DateTime.UtcNow)), Throws.TypeOf<StorageException>());
_postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Once);
}
[Test]
public void DeletePost_CorrectRecord_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
var flag = false;
_postStorageContract.Setup(x => x.DelElement(It.Is((string x) => x == id))).Callback(() => { flag = true; });
//Act
_postBusinessLogicContract.DeletePost(id);
//Assert
_postStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
Assert.That(flag);
}
[Test]
public void DeletePost_RecordWithIncorrectId_ThrowException_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
_postStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new ElementNotFoundException(id));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.DeletePost(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_postStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
}
[Test]
public void DeletePost_IdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.DeletePost(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _postBusinessLogicContract.DeletePost(string.Empty), Throws.TypeOf<ArgumentNullException>());
_postStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Never);
}
[Test]
public void DeletePost_IdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.DeletePost("id"), Throws.TypeOf<ValidationException>());
_postStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Never);
}
[Test]
public void DeletePost_StorageThrowError_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.DeletePost(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_postStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
}
[Test]
public void RestorePost_CorrectRecord_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
var flag = false;
_postStorageContract.Setup(x => x.ResElement(It.Is((string x) => x == id))).Callback(() => { flag = true; });
//Act
_postBusinessLogicContract.RestorePost(id);
//Assert
_postStorageContract.Verify(x => x.ResElement(It.IsAny<string>()), Times.Once);
Assert.That(flag);
}
[Test]
public void RestorePost_RecordWithIncorrectId_ThrowException_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
_postStorageContract.Setup(x => x.ResElement(It.IsAny<string>())).Throws(new ElementNotFoundException(id));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.RestorePost(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_postStorageContract.Verify(x => x.ResElement(It.IsAny<string>()), Times.Once);
}
[Test]
public void RestorePost_IdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.RestorePost(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _postBusinessLogicContract.RestorePost(string.Empty), Throws.TypeOf<ArgumentNullException>());
_postStorageContract.Verify(x => x.ResElement(It.IsAny<string>()), Times.Never);
}
[Test]
public void RestorePost_IdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.RestorePost("id"), Throws.TypeOf<ValidationException>());
_postStorageContract.Verify(x => x.ResElement(It.IsAny<string>()), Times.Never);
}
[Test]
public void RestorePost_StorageThrowError_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x => x.ResElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.RestorePost(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_postStorageContract.Verify(x => x.ResElement(It.IsAny<string>()), Times.Once);
}
}

View File

@@ -0,0 +1,347 @@
using BarBelochkaContract.DataModels;
using Microsoft.Extensions.Logging;
using Moq;
using SquirrelBusinessLogic.Implementations;
using SquirrelContract.DataModels;
using SquirrelContract.Enums;
using SquirrelContract.Exceptions;
using SquirrelContract.StoragesContracts;
namespace SquirrelTests.BusinessLogicContractsTests;
[TestFixture]
internal class SalaryBusinessLogicContractTests
{
private SalaryBusinessLogicContract _salaryBusinessLogicContract;
private Mock<ISalaryStorageContract> _salaryStorageContract;
private Mock<ISaleStorageContract> _saleStorageContract;
private Mock<IPostStorageContract> _postStorageContract;
private Mock<IEmployeeStorageContract> _employeeStorageContract;
[OneTimeSetUp]
public void OneTimeSetUp()
{
_salaryStorageContract = new Mock<ISalaryStorageContract>();
_saleStorageContract = new Mock<ISaleStorageContract>();
_postStorageContract = new Mock<IPostStorageContract>();
_employeeStorageContract = new Mock<IEmployeeStorageContract>();
_salaryBusinessLogicContract = new SalaryBusinessLogicContract(_salaryStorageContract.Object,
_saleStorageContract.Object, _postStorageContract.Object, _employeeStorageContract.Object, new Mock<ILogger>().Object);
}
[TearDown]
public void TearDown()
{
_salaryStorageContract.Reset();
_saleStorageContract.Reset();
_postStorageContract.Reset();
_employeeStorageContract.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 GetAllSalariesByEmployee_ReturnListOfRecords_Test()
{
//Arrange
var startDate = DateTime.UtcNow;
var endDate = DateTime.UtcNow.AddDays(1);
var employeeId = 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.GetAllSalariesByPeriodByEmployee(startDate, endDate, employeeId);
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.EquivalentTo(listOriginal));
_salaryStorageContract.Verify(x => x.GetList(startDate, endDate, employeeId), Times.Once);
}
[Test]
public void GetAllSalariesByEmployee_ReturnEmptyList_Test()
{
//Arrange
_salaryStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>())).Returns([]);
//Act
var list = _salaryBusinessLogicContract.GetAllSalariesByPeriodByEmployee(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 GetAllSalariesByEmployee_IncorrectDates_ThrowException_Test()
{
//Arrange
var dateTime = DateTime.UtcNow;
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.GetAllSalariesByPeriodByEmployee(dateTime, dateTime, Guid.NewGuid().ToString()), Throws.TypeOf<IncorrectDatesException>());
Assert.That(() => _salaryBusinessLogicContract.GetAllSalariesByPeriodByEmployee(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 GetAllSalariesByEmployee_EmployeeIdIsNUllOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.GetAllSalariesByPeriodByEmployee(DateTime.UtcNow, DateTime.UtcNow.AddDays(1), null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _salaryBusinessLogicContract.GetAllSalariesByPeriodByEmployee(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 GetAllSalariesByEmployee_EmployeeIdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.GetAllSalariesByPeriodByEmployee(DateTime.UtcNow, DateTime.UtcNow.AddDays(1), "workerId"), Throws.TypeOf<ValidationException>());
_salaryStorageContract.Verify(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSalariesByEmployee_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.GetAllSalariesByPeriodByEmployee(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 GetAllSalariesByEmployee_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.GetAllSalariesByPeriodByEmployee(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 employeeId = Guid.NewGuid().ToString();
var saleSum = 200.0;
var postSalary = 2000.0;
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns([new SaleDataModel(Guid.NewGuid().ToString(), employeeId, null, saleSum, DiscountType.None, 0, false, [])]);
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Manager, postSalary, true, DateTime.UtcNow));
_employeeStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Returns([new EmployeeDataModel(employeeId, "Test", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)]);
var sum = 0.0;
var expectedSum = postSalary + saleSum * 0.1;
_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_WithSeveralWorkers_Test()
{
//Arrange
var employee1Id = Guid.NewGuid().ToString();
var employee2Id = Guid.NewGuid().ToString();
var employee3Id = Guid.NewGuid().ToString();
var list = new List<EmployeeDataModel>() {
new(employee1Id, "Test", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false),
new(employee2Id, "Test", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false),
new(employee3Id, "Test", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)
};
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns([new SaleDataModel(Guid.NewGuid().ToString(), employee1Id, null, 1, DiscountType.None, 0, false, []),
new SaleDataModel(Guid.NewGuid().ToString(), employee1Id, null, 1, DiscountType.None, 0, false, []),
new SaleDataModel(Guid.NewGuid().ToString(), employee2Id, null, 1, DiscountType.None, 0, false, []),
new SaleDataModel(Guid.NewGuid().ToString(), employee3Id, null, 1, DiscountType.None, 0, false, []),
new SaleDataModel(Guid.NewGuid().ToString(), employee3Id, null, 1, DiscountType.None, 0, false, [])]);
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Manager, 2000, true, DateTime.UtcNow));
_employeeStorageContract.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_WithoutSalesByWorker_Test()
{
//Arrange
var postSalary = 2000.0;
var employeeId = Guid.NewGuid().ToString();
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns([]);
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Manager, postSalary, true, DateTime.UtcNow));
_employeeStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Returns([new EmployeeDataModel(employeeId, "Test", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)]);
var sum = 0.0;
var expectedSum = postSalary;
_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_SaleStorageReturnNull_ThrowException_Test()
{
//Arrange
var employeeId = Guid.NewGuid().ToString();
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Manager, 2000, true, DateTime.UtcNow));
_employeeStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Returns([new EmployeeDataModel(employeeId, "Test", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)]);
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow), Throws.TypeOf<NullListException>());
}
[Test]
public void CalculateSalaryByMounth_PostStorageReturnNull_ThrowException_Test()
{
//Arrange
var employeeId = Guid.NewGuid().ToString();
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns([new SaleDataModel(Guid.NewGuid().ToString(), employeeId, null, 200, DiscountType.None, 0, false, [])]);
_employeeStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Returns([new EmployeeDataModel(employeeId, "Test", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)]);
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow), Throws.TypeOf<NullListException>());
}
[Test]
public void CalculateSalaryByMounth_WorkerStorageReturnNull_ThrowException_Test()
{
//Arrange
var employeeId = Guid.NewGuid().ToString();
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns([new SaleDataModel(Guid.NewGuid().ToString(), employeeId, null, 200, DiscountType.None, 0, false, [])]);
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Manager, 2000, true, DateTime.UtcNow));
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow), Throws.TypeOf<NullListException>());
}
[Test]
public void CalculateSalaryByMounth_SaleStorageThrowException_ThrowException_Test()
{
//Arrange
var employeeId = Guid.NewGuid().ToString();
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
.Throws(new StorageException(new InvalidOperationException()));
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Manager, 2000, true, DateTime.UtcNow));
_employeeStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Returns([new EmployeeDataModel(employeeId, "Test", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)]);
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow), Throws.TypeOf<StorageException>());
}
[Test]
public void CalculateSalaryByMounth_PostStorageThrowException_ThrowException_Test()
{
//Arrange
var employeeId = Guid.NewGuid().ToString();
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns([new SaleDataModel(Guid.NewGuid().ToString(), employeeId, null, 200, DiscountType.None, 0, false, [])]);
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Throws(new StorageException(new InvalidOperationException()));
_employeeStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Returns([new EmployeeDataModel(employeeId, "Test", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)]);
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow), Throws.TypeOf<StorageException>());
}
[Test]
public void CalculateSalaryByMounth_WorkerStorageThrowException_ThrowException_Test()
{
//Arrange
var employeeId = Guid.NewGuid().ToString();
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns([new SaleDataModel(Guid.NewGuid().ToString(), employeeId, null, 200, DiscountType.None, 0, false, [])]);
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Manager, 2000, true, DateTime.UtcNow));
_employeeStorageContract.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

@@ -0,0 +1,521 @@
using Microsoft.Extensions.Logging;
using Moq;
using SquirrelBusinessLogic.Implementations;
using SquirrelContract.DataModels;
using SquirrelContract.Enums;
using SquirrelContract.Exceptions;
using SquirrelContract.StoragesContracts;
namespace SquirrelTests.BusinessLogicContractsTests;
[TestFixture]
internal class SaleBusinessLogicContractTests
{
private SaleBusinessLogicContract _saleBusinessLogicContract;
private Mock<ISaleStorageContract> _saleStorageContract;
private Mock<IWarehouseStorageContract> _warehouseStorageContract;
[OneTimeSetUp]
public void OneTimeSetUp()
{
_saleStorageContract = new Mock<ISaleStorageContract>();
_warehouseStorageContract = new Mock<IWarehouseStorageContract>();
_saleBusinessLogicContract = new SaleBusinessLogicContract(_saleStorageContract.Object, _warehouseStorageContract.Object, new Mock<ILogger>().Object);
}
[TearDown]
public void TearDown()
{
_saleStorageContract.Reset();
_warehouseStorageContract.Reset();
}
[Test]
public void GetAllSalesByPeriod_ReturnListOfRecords_Test()
{
//Arrange
var date = DateTime.UtcNow;
var listOriginal = new List<SaleDataModel>()
{
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, DiscountType.None, 0, false,
[new SaleCocktailDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]),
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, DiscountType.None, 0, false, []),
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, DiscountType.None, 0, false, []),
};
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Returns(listOriginal);
//Act
var list = _saleBusinessLogicContract.GetAllSalesByPeriod(date, date.AddDays(1));
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.EquivalentTo(listOriginal));
_saleStorageContract.Verify(x => x.GetList(date, date.AddDays(1), null, null, null), Times.Once);
}
[Test]
public void GetAllSalesByPeriod_ReturnEmptyList_Test()
{
//Arrange
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Returns([]);
//Act
var list = _saleBusinessLogicContract.GetAllSalesByPeriod(DateTime.UtcNow, DateTime.UtcNow.AddDays(1));
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSalesByPeriod_IncorrectDates_ThrowException_Test()
{
//Arrange
var date = DateTime.UtcNow;
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByPeriod(date, date), Throws.TypeOf<IncorrectDatesException>());
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByPeriod(date, date.AddSeconds(-1)), Throws.TypeOf<IncorrectDatesException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSalesByPeriod_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByPeriod(DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<NullListException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSalesByPeriod_StorageThrowError_ThrowException_Test()
{
//Arrange
_saleStorageContract.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(() => _saleBusinessLogicContract.GetAllSalesByPeriod(DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<StorageException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSalesByEmployeeByPeriod_ReturnListOfRecords_Test()
{
//Arrange
var date = DateTime.UtcNow;
var employeeId = Guid.NewGuid().ToString();
var listOriginal = new List<SaleDataModel>()
{
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, DiscountType.None, 0, false,
[new SaleCocktailDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]),
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, DiscountType.None, 0, false, []),
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, DiscountType.None, 0, false, []),
};
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Returns(listOriginal);
//Act
var list = _saleBusinessLogicContract.GetAllSalesByEmployeeByPeriod(employeeId, date, date.AddDays(1));
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.EquivalentTo(listOriginal));
_saleStorageContract.Verify(x => x.GetList(date, date.AddDays(1), employeeId, null, null), Times.Once);
}
[Test]
public void GetAllSalesByEmployeeByPeriod_ReturnEmptyList_Test()
{
//Arrange
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Returns([]);
//Act
var list = _saleBusinessLogicContract.GetAllSalesByEmployeeByPeriod(Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow.AddDays(1));
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSalesByEmployeeByPeriod_IncorrectDates_ThrowException_Test()
{
//Arrange
var date = DateTime.UtcNow;
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByEmployeeByPeriod(Guid.NewGuid().ToString(), date, date), Throws.TypeOf<IncorrectDatesException>());
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByEmployeeByPeriod(Guid.NewGuid().ToString(), date, date.AddSeconds(-1)), Throws.TypeOf<IncorrectDatesException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSalesByEmployeeByPeriod_EmployeeIdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByEmployeeByPeriod(null, DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByEmployeeByPeriod(string.Empty, DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<ArgumentNullException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSalesByEmployeeByPeriod_EmployeeIdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByEmployeeByPeriod("employeeId", DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<ValidationException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSalesByEmployeeByPeriod_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByEmployeeByPeriod(Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<NullListException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSalesByEmployeeByPeriod_StorageThrowError_ThrowException_Test()
{
//Arrange
_saleStorageContract.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(() => _saleBusinessLogicContract.GetAllSalesByEmployeeByPeriod(Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<StorageException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSalesByClientByPeriod_ReturnListOfRecords_Test()
{
//Arrange
var date = DateTime.UtcNow;
var clientId = Guid.NewGuid().ToString();
var listOriginal = new List<SaleDataModel>()
{
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, DiscountType.None, 0, false,
[new SaleCocktailDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]),
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, DiscountType.None, 0, false, []),
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, DiscountType.None, 0, false, []),
};
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Returns(listOriginal);
//Act
var list = _saleBusinessLogicContract.GetAllSalesByClientByPeriod(clientId, date, date.AddDays(1));
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.EquivalentTo(listOriginal));
_saleStorageContract.Verify(x => x.GetList(date, date.AddDays(1), null, clientId, null), Times.Once);
}
[Test]
public void GetAllSalesByClientByPeriod_ReturnEmptyList_Test()
{
//Arrange
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Returns([]);
//Act
var list = _saleBusinessLogicContract.GetAllSalesByClientByPeriod(Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow.AddDays(1));
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSalesByClientByPeriod_IncorrectDates_ThrowException_Test()
{
//Arrange
var date = DateTime.UtcNow;
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByClientByPeriod(Guid.NewGuid().ToString(), date, date), Throws.TypeOf<IncorrectDatesException>());
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByClientByPeriod(Guid.NewGuid().ToString(), date, date.AddSeconds(-1)), Throws.TypeOf<IncorrectDatesException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSalesByClientByPeriod_ClientIdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByClientByPeriod(null, DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByClientByPeriod(string.Empty, DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<ArgumentNullException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSalesByClientByPeriod_ClientIdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByClientByPeriod("clientId", DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<ValidationException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSalesByClientByPeriod_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByClientByPeriod(Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<NullListException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSalesByClientByPeriod_StorageThrowError_ThrowException_Test()
{
//Arrange
_saleStorageContract.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(() => _saleBusinessLogicContract.GetAllSalesByClientByPeriod(Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<StorageException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSalesByCocktailByPeriod_ReturnListOfRecords_Test()
{
//Arrange
var date = DateTime.UtcNow;
var cocktailId = Guid.NewGuid().ToString();
var listOriginal = new List<SaleDataModel>()
{
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, DiscountType.None, 0, false,
[new SaleCocktailDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]),
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, DiscountType.None, 0, false, []),
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, DiscountType.None, 0, false, []),
};
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Returns(listOriginal);
//Act
var list = _saleBusinessLogicContract.GetAllSalesByCocktailByPeriod(cocktailId, date, date.AddDays(1));
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.EquivalentTo(listOriginal));
_saleStorageContract.Verify(x => x.GetList(date, date.AddDays(1), null, null, cocktailId), Times.Once);
}
[Test]
public void GetAllSalesByCocktailByPeriod_ReturnEmptyList_Test()
{
//Arrange
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Returns([]);
//Act
var list = _saleBusinessLogicContract.GetAllSalesByCocktailByPeriod(Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow.AddDays(1));
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSalesByCocktailByPeriod_IncorrectDates_ThrowException_Test()
{
//Arrange
var date = DateTime.UtcNow;
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByCocktailByPeriod(Guid.NewGuid().ToString(), date, date), Throws.TypeOf<IncorrectDatesException>());
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByCocktailByPeriod(Guid.NewGuid().ToString(), date, date.AddSeconds(-1)), Throws.TypeOf<IncorrectDatesException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSalesByCocktailByPeriod_CocktailIdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByCocktailByPeriod(null, DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByCocktailByPeriod(string.Empty, DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<ArgumentNullException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSalesByCocktailByPeriod_CocktailIdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByCocktailByPeriod("CocktailId", DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<ValidationException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSalesByCocktailByPeriod_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByCocktailByPeriod(Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<NullListException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSalesByCocktailByPeriod_StorageThrowError_ThrowException_Test()
{
//Arrange
_saleStorageContract.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(() => _saleBusinessLogicContract.GetAllSalesByCocktailByPeriod(Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<StorageException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetSaleByData_GetById_ReturnRecord_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
var record = new SaleDataModel(id, Guid.NewGuid().ToString(), null, 10, DiscountType.None, 0, false,
[new SaleCocktailDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]);
_saleStorageContract.Setup(x => x.GetElementById(id)).Returns(record);
//Act
var element = _saleBusinessLogicContract.GetSaleByData(id);
//Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.Id, Is.EqualTo(id));
_saleStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetSaleByData_EmptyData_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetSaleByData(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _saleBusinessLogicContract.GetSaleByData(string.Empty), Throws.TypeOf<ArgumentNullException>());
_saleStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetSaleByData_IdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetSaleByData("saleId"), Throws.TypeOf<ValidationException>());
_saleStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetSaleByData_GetById_NotFoundRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetSaleByData(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_saleStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetSaleByData_StorageThrowError_ThrowException_Test()
{
//Arrange
_saleStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetSaleByData(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_saleStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void InsertSale_CorrectRecord_Test()
{
//Arrange
var flag = false;
var record = new SaleDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 10, DiscountType.None, 10,
false, [new SaleCocktailDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]);
_warehouseStorageContract.Setup(x => x.CheckCocktails(It.IsAny<SaleDataModel>())).Returns(true);
_saleStorageContract.Setup(x => x.AddElement(It.IsAny<SaleDataModel>()))
.Callback((SaleDataModel x) =>
{
flag = x.Id == record.Id && x.EmployeeId == record.EmployeeId && x.ClientId == record.ClientId &&
x.SaleDate == record.SaleDate && x.Sum == record.Sum && x.DiscountType == record.DiscountType &&
x.Discount == record.Discount && x.IsCancel == record.IsCancel && x.Cocktails.Count == record.Cocktails.Count &&
x.Cocktails.First().CocktailId == record.Cocktails.First().CocktailId &&
x.Cocktails.First().SaleId == record.Cocktails.First().SaleId &&
x.Cocktails.First().Count == record.Cocktails.First().Count;
});
//Act
_saleBusinessLogicContract.InsertSale(record);
//Assert
_warehouseStorageContract.Verify(x => x.CheckCocktails(It.IsAny<SaleDataModel>()), Times.Once);
_saleStorageContract.Verify(x => x.AddElement(It.IsAny<SaleDataModel>()), Times.Once);
Assert.That(flag);
}
[Test]
public void InsertSale_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_warehouseStorageContract.Setup(x => x.CheckCocktails(It.IsAny<SaleDataModel>())).Returns(true);
_saleStorageContract.Setup(x => x.AddElement(It.IsAny<SaleDataModel>())).Throws(new ElementExistsException("Data", "Data"));
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.InsertSale(new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(),
Guid.NewGuid().ToString(), 10, DiscountType.None, 10, false, [new SaleCocktailDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<ElementExistsException>());
_saleStorageContract.Verify(x => x.AddElement(It.IsAny<SaleDataModel>()), Times.Once);
_warehouseStorageContract.Verify(x => x.CheckCocktails(It.IsAny<SaleDataModel>()), Times.Once);
}
[Test]
public void InsertSale_NullRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.InsertSale(null), Throws.TypeOf<ArgumentNullException>());
_saleStorageContract.Verify(x => x.AddElement(It.IsAny<SaleDataModel>()), Times.Never);
}
[Test]
public void InsertSale_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.InsertSale(new SaleDataModel("id", Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 10, DiscountType.None, 10, false, [])), Throws.TypeOf<ValidationException>());
_saleStorageContract.Verify(x => x.AddElement(It.IsAny<SaleDataModel>()), Times.Never);
}
[Test]
public void InsertSale_StorageThrowError_ThrowException_Test()
{
//Arrange
_warehouseStorageContract.Setup(x => x.CheckCocktails(It.IsAny<SaleDataModel>())).Returns(true);
_saleStorageContract.Setup(x => x.AddElement(It.IsAny<SaleDataModel>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.InsertSale(new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(),
Guid.NewGuid().ToString(), 10, DiscountType.None, 10, false, [new SaleCocktailDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<StorageException>());
_warehouseStorageContract.Verify(x => x.CheckCocktails(It.IsAny<SaleDataModel>()), Times.Once);
_saleStorageContract.Verify(x => x.AddElement(It.IsAny<SaleDataModel>()), Times.Once);
}
[Test]
public void InsertSale_InsufficientError_ThrowException_Test()
{
//Arrange
_warehouseStorageContract.Setup(x => x.CheckCocktails(It.IsAny<SaleDataModel>())).Returns(false);
Assert.That(() => _saleBusinessLogicContract.InsertSale(new SaleDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(),
Guid.NewGuid().ToString(), 10, DiscountType.None, 10, false,
[new SaleCocktailDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<InsufficientStockException>());
//Act&Assert
_warehouseStorageContract.Verify(x => x.CheckCocktails(It.IsAny<SaleDataModel>()), Times.Once);
}
[Test]
public void CancelSale_CorrectRecord_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
var flag = false;
_saleStorageContract.Setup(x => x.DelElement(It.Is((string x) => x == id))).Callback(() => { flag = true; });
//Act
_saleBusinessLogicContract.CancelSale(id);
//Assert
_saleStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
Assert.That(flag);
}
[Test]
public void CancelSale_RecordWithIncorrectId_ThrowException_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
_saleStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new ElementNotFoundException(id));
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.CancelSale(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_saleStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
}
[Test]
public void CancelSale_IdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.CancelSale(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _saleBusinessLogicContract.CancelSale(string.Empty), Throws.TypeOf<ArgumentNullException>());
_saleStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Never);
}
[Test]
public void CancelSale_IdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.CancelSale("id"), Throws.TypeOf<ValidationException>());
_saleStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Never);
}
[Test]
public void CancelSale_StorageThrowError_ThrowException_Test()
{
//Arrange
_saleStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.CancelSale(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_saleStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
}
}

View File

@@ -0,0 +1,284 @@
using Microsoft.Extensions.Logging;
using Moq;
using SquirrelBusinessLogic.Implementations;
using SquirrelContract.BusinessLogicContracts;
using SquirrelContract.DataModels;
using SquirrelContract.Enums;
using SquirrelContract.Exceptions;
using SquirrelContract.StoragesContracts;
using static System.Runtime.InteropServices.JavaScript.JSType;
namespace SquirrelTests.BusinessLogicContractsTests;
[TestFixture]
internal class SupplyBusinessLogicContractTests
{
private SupplyBusinessLogicContract _supplyBusinessLogicContract;
private Mock<ISupplyStorageContract> _supplyStorageContract;
private Mock<IWarehouseStorageContract> _warehouseStorageContract;
[OneTimeSetUp]
public void OneTimeSetUp()
{
_supplyStorageContract = new Mock<ISupplyStorageContract>();
_warehouseStorageContract = new Mock<IWarehouseStorageContract>();
_supplyBusinessLogicContract = new SupplyBusinessLogicContract(_supplyStorageContract.Object, _warehouseStorageContract.Object, new Mock<ILogger>().Object);
}
[TearDown]
public void TearDown()
{
_supplyStorageContract.Reset();
}
[Test]
public void GetAllSuppliesByPeriod_ReturnListOfRecords_Test()
{
var date = DateTime.UtcNow;
// Arrange
var listOriginal = new List<SupplyDataModel>()
{
new(Guid.NewGuid().ToString(), DateTime.Now, []),
new(Guid.NewGuid().ToString(), DateTime.Now, []),
new(Guid.NewGuid().ToString(), DateTime.Now, [])
};
_supplyStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>())).Returns(listOriginal);
// Act
var list = _supplyBusinessLogicContract.GetAllSuppliesByPeriod(date, date.AddDays(1));
// Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.EquivalentTo(listOriginal));
_supplyStorageContract.Verify(x => x.GetList(date, date.AddDays(1), null), Times.Once);
}
[Test]
public void GetAllSuppliesByPeriod_ReturnEmptyList_Test()
{
//Arrange
_supplyStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>())).Returns([]);
//Act
var list = _supplyBusinessLogicContract.GetAllSuppliesByPeriod(DateTime.UtcNow, DateTime.UtcNow.AddDays(1));
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
_supplyStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSuppliesByPeriod_IncorrectDates_ThrowException_Test()
{
//Arrange
var date = DateTime.UtcNow;
//Act&Assert
Assert.That(() => _supplyBusinessLogicContract.GetAllSuppliesByPeriod(date, date), Throws.TypeOf<IncorrectDatesException>());
Assert.That(() => _supplyBusinessLogicContract.GetAllSuppliesByPeriod(date, date.AddSeconds(-1)), Throws.TypeOf<IncorrectDatesException>());
_supplyStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSuppliesByPeriod_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _supplyBusinessLogicContract.GetAllSuppliesByPeriod(DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<NullListException>());
_supplyStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSuppliesByPeriod_StorageThrowError_ThrowException_Test()
{
//Arrange
_supplyStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _supplyBusinessLogicContract.GetAllSuppliesByPeriod(DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<StorageException>());
_supplyStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSuppliesByCocktailByPeriod_ReturnListOfRecords_Test()
{
//Arrange
var date = DateTime.UtcNow;
var cocktailId = Guid.NewGuid().ToString();
var listOriginal = new List<SupplyDataModel>()
{
new(Guid.NewGuid().ToString(), DateTime.Now,
[new SupplyCocktailDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]),
new(Guid.NewGuid().ToString(), DateTime.Now, []),
new(Guid.NewGuid().ToString(), DateTime.Now, []),
};
_supplyStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>())).Returns(listOriginal);
//Act
var list = _supplyBusinessLogicContract.GetAllSuppliesByCocktailByPeriod(cocktailId, date, date.AddDays(1));
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.EquivalentTo(listOriginal));
_supplyStorageContract.Verify(x => x.GetList(date, date.AddDays(1), cocktailId), Times.Once);
}
[Test]
public void GetAllSuppliesByCocktailByPeriod_ReturnEmptyList_Test()
{
//Arrange
_supplyStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>())).Returns([]);
//Act
var list = _supplyBusinessLogicContract.GetAllSuppliesByCocktailByPeriod(Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow.AddDays(1));
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
_supplyStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSuppliesByCocktailByPeriod_IncorrectDates_ThrowException_Test()
{
//Arrange
var date = DateTime.UtcNow;
//Act&Assert
Assert.That(() => _supplyBusinessLogicContract.GetAllSuppliesByCocktailByPeriod(Guid.NewGuid().ToString(), date, date), Throws.TypeOf<IncorrectDatesException>());
Assert.That(() => _supplyBusinessLogicContract.GetAllSuppliesByCocktailByPeriod(Guid.NewGuid().ToString(), date, date.AddSeconds(-1)), Throws.TypeOf<IncorrectDatesException>());
_supplyStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSuppliesByCocktailByPeriod_CocktailIdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _supplyBusinessLogicContract.GetAllSuppliesByCocktailByPeriod(null, DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _supplyBusinessLogicContract.GetAllSuppliesByCocktailByPeriod(string.Empty, DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<ArgumentNullException>());
_supplyStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSuppliesByCocktailByPeriod_CocktailIdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _supplyBusinessLogicContract.GetAllSuppliesByCocktailByPeriod("cocktailId", DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<ValidationException>());
_supplyStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSuppliesByCocktailByPeriod_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _supplyBusinessLogicContract.GetAllSuppliesByCocktailByPeriod(Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<NullListException>());
_supplyStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSuppliesByCocktailByPeriod_StorageThrowError_ThrowException_Test()
{
//Arrange
_supplyStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _supplyBusinessLogicContract.GetAllSuppliesByCocktailByPeriod(Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<StorageException>());
_supplyStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetSupplyByData_GetById_ReturnRecord_Test()
{
// Arrange
var id = Guid.NewGuid().ToString();
var record = new SupplyDataModel(id, DateTime.Now, []);
_supplyStorageContract.Setup(x => x.GetElementById(id)).Returns(record);
// Act
var element = _supplyBusinessLogicContract.GetSupplyByData(id);
// Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.Id, Is.EqualTo(id));
_supplyStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetSupplyByData_EmptyData_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _supplyBusinessLogicContract.GetSupplyByData(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _supplyBusinessLogicContract.GetSupplyByData(string.Empty), Throws.TypeOf<ArgumentNullException>());
_supplyStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetSupplyByData_GetById_NotFoundRecord_ThrowException_Test()
{
// Arrange
_supplyStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new ElementNotFoundException(""));
// Act & Assert
Assert.That(() => _supplyBusinessLogicContract.GetSupplyByData(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_supplyStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetSuppliesByData_StorageThrowError_ThrowException_Test()
{
// Arrange
_supplyStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
// Act & Assert
Assert.That(() => _supplyBusinessLogicContract.GetSupplyByData(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_supplyStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void InsertSupply_CorrectRecord_Test()
{
// Arrange
var supplyId = Guid.NewGuid().ToString();
var cocktailId = Guid.NewGuid().ToString();
var warehouseId = Guid.NewGuid().ToString();
var record = new SupplyDataModel(supplyId, DateTime.Now,
[new SupplyCocktailDataModel(supplyId, cocktailId, 5)]);
var warehouse = new WarehouseDataModel(warehouseId, "Main Warehouse",
[new WarehouseCocktailDataModel(warehouseId, cocktailId, 10)]);
_supplyStorageContract.Setup(x => x.AddElement(It.IsAny<SupplyDataModel>()));
_warehouseStorageContract.Setup(x => x.GetList()).Returns([warehouse]);
_warehouseStorageContract.Setup(x => x.UpdWarehouseOnSupply(warehouseId, cocktailId, 5));
// Act
_supplyBusinessLogicContract.InsertSupply(record);
// Assert
_supplyStorageContract.Verify(x => x.AddElement(It.IsAny<SupplyDataModel>()), Times.Once);
_warehouseStorageContract.Verify(x => x.UpdWarehouseOnSupply(warehouseId, cocktailId, 5), Times.Once);
}
[Test]
public void InsertSupply_RecordWithExistsData_ThrowException_Test()
{
// Arrange
_supplyStorageContract.Setup(x => x.AddElement(It.IsAny<SupplyDataModel>())).Throws(new ElementExistsException("Data", "Data"));
// Act & Assert
Assert.That(() => _supplyBusinessLogicContract.InsertSupply(new(Guid.NewGuid().ToString(), DateTime.Now,
[new SupplyCocktailDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<ElementExistsException>());
_supplyStorageContract.Verify(x => x.AddElement(It.IsAny<SupplyDataModel>()), Times.Once);
}
[Test]
public void InsertSupply_NullRecord_ThrowException_Test()
{
// Act & Assert
Assert.That(() => _supplyBusinessLogicContract.InsertSupply(null), Throws.TypeOf<ArgumentNullException>());
_supplyStorageContract.Verify(x => x.AddElement(It.IsAny<SupplyDataModel>()), Times.Never);
}
[Test]
public void InsertSupply_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _supplyBusinessLogicContract.InsertSupply(new SupplyDataModel("id", DateTime.UtcNow, [])), Throws.TypeOf<ValidationException>());
_supplyStorageContract.Verify(x => x.AddElement(It.IsAny<SupplyDataModel>()), Times.Never);
}
[Test]
public void InsertSupply_StorageThrowError_ThrowException_Test()
{
// Arrange
_supplyStorageContract.Setup(x => x.AddElement(It.IsAny<SupplyDataModel>())).Throws(new StorageException(new InvalidOperationException()));
// Act & Assert
Assert.That(() => _supplyBusinessLogicContract.InsertSupply(new(Guid.NewGuid().ToString(), DateTime.Now,
[new SupplyCocktailDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<StorageException>());
_supplyStorageContract.Verify(x => x.AddElement(It.IsAny<SupplyDataModel>()), Times.Once);
}
}

View File

@@ -0,0 +1,320 @@
using Microsoft.Extensions.Logging;
using Moq;
using SquirrelBusinessLogic.Implementations;
using SquirrelContract.BusinessLogicContracts;
using SquirrelContract.DataModels;
using SquirrelContract.Enums;
using SquirrelContract.Exceptions;
using SquirrelContract.StoragesContracts;
namespace SquirrelTests.BusinessLogicContractsTests;
[TestFixture]
internal class WarehouseBusinessLogicContractTests
{
private WarehouseBusinessLogicContract _warehouseBusinessLogicContract;
private Mock<IWarehouseStorageContract> _warehouseStorageContract;
[OneTimeSetUp]
public void OneTimeSetUp()
{
_warehouseStorageContract = new Mock<IWarehouseStorageContract>();
_warehouseBusinessLogicContract = new WarehouseBusinessLogicContract(_warehouseStorageContract.Object, new Mock<ILogger>().Object);
}
[TearDown]
public void TearDown()
{
_warehouseStorageContract.Reset();
}
[Test]
public void GetAllWarehouses_ReturnListOfRecords_Test()
{
// Arrange
var listOriginal = new List<WarehouseDataModel>()
{
new(Guid.NewGuid().ToString(), "aba", []),
new(Guid.NewGuid().ToString(), "aaa", []),
new(Guid.NewGuid().ToString(), "aaa", []),
};
_warehouseStorageContract.Setup(x => x.GetList()).Returns(listOriginal);
// Act
var list = _warehouseBusinessLogicContract.GetAllWarehouses();
// Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.EquivalentTo(listOriginal));
}
[Test]
public void GetAllWarehouses_ReturnEmptyList_Test()
{
// Arrange
_warehouseStorageContract.Setup(x => x.GetList()).Returns([]);
// Act
var list = _warehouseBusinessLogicContract.GetAllWarehouses();
// Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
_warehouseStorageContract.Verify(x => x.GetList(), Times.Once);
}
[Test]
public void GetAllWarehouses_ReturnNull_ThrowException_Test()
{
// Arrange
_warehouseStorageContract.Setup(x => x.GetList()).Returns((List<WarehouseDataModel>)null);
// Act & Assert
Assert.That(() => _warehouseBusinessLogicContract.GetAllWarehouses(), Throws.TypeOf<NullListException>());
_warehouseStorageContract.Verify(x => x.GetList(), Times.Once);
}
[Test]
public void GetAllWarehouses_StorageThrowError_ThrowException_Test()
{
// Arrange
_warehouseStorageContract.Setup(x => x.GetList()).Throws(new StorageException(new InvalidOperationException()));
// Act & Assert
Assert.That(() => _warehouseBusinessLogicContract.GetAllWarehouses(), Throws.TypeOf<StorageException>());
_warehouseStorageContract.Verify(x => x.GetList(), Times.Once);
}
[Test]
public void GetAllWarehousesByData_GetById_ReturnRecord_Test()
{
// Arrange
var id = Guid.NewGuid().ToString();
var record = new WarehouseDataModel(id, "aba", []);
_warehouseStorageContract.Setup(x => x.GetElementById(id)).Returns(record);
// Act
var element = _warehouseBusinessLogicContract.GetWarehouseByData(id);
// Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.Id, Is.EqualTo(id));
_warehouseStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetCocktailByData_GetByName_ReturnRecord_Test()
{
//Arrange
var name = "name";
var record = new WarehouseDataModel(Guid.NewGuid().ToString(), name, []);
_warehouseStorageContract.Setup(x => x.GetElementByName(name)).Returns(record);
//Act
var element = _warehouseBusinessLogicContract.GetWarehouseByData(name);
//Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.Name, Is.EqualTo(name));
_warehouseStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetWarehouseByData_EmptyData_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _warehouseBusinessLogicContract.GetWarehouseByData(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _warehouseBusinessLogicContract.GetWarehouseByData(string.Empty), Throws.TypeOf<ArgumentNullException>());
_warehouseStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Never);
_warehouseStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetWarehouseByData_GetById_NotFoundRecord_ThrowException_Test()
{
// Arrange
_warehouseStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new ElementNotFoundException(""));
// Act & Assert
Assert.That(() => _warehouseBusinessLogicContract.GetWarehouseByData(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_warehouseStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetWarehouseByData_GetByName_NotFoundRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _warehouseBusinessLogicContract.GetWarehouseByData("name"), Throws.TypeOf<ElementNotFoundException>());
_warehouseStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetWarehouseByData_StorageThrowError_ThrowException_Test()
{
//Arrange
_warehouseStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
_warehouseStorageContract.Setup(x => x.GetElementByName(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _warehouseBusinessLogicContract.GetWarehouseByData(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
Assert.That(() => _warehouseBusinessLogicContract.GetWarehouseByData("name"), Throws.TypeOf<StorageException>());
_warehouseStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
_warehouseStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Once);
}
[Test]
public void InsertWarehouse_CorrectRecord_Test()
{
// Arrange
var record = new WarehouseDataModel(Guid.NewGuid().ToString(), "aba",
[new WarehouseCocktailDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]);
_warehouseStorageContract.Setup(x => x.AddElement(It.IsAny<WarehouseDataModel>()));
// Act
_warehouseBusinessLogicContract.InsertWarehouse(record);
// Assert
_warehouseStorageContract.Verify(x => x.AddElement(It.IsAny<WarehouseDataModel>()), Times.Once);
}
[Test]
public void InsertWarehouse_RecordWithExistsData_ThrowException_Test()
{
// Arrange
_warehouseStorageContract.Setup(x => x.AddElement(It.IsAny<WarehouseDataModel>())).Throws(new ElementExistsException("Data", "Data"));
// Act & Assert
Assert.That(() => _warehouseBusinessLogicContract.InsertWarehouse(new(Guid.NewGuid().ToString(), "aba",
[new WarehouseCocktailDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<ElementExistsException>());
_warehouseStorageContract.Verify(x => x.AddElement(It.IsAny<WarehouseDataModel>()), Times.Once);
}
[Test]
public void InsertWarehouse_NullRecord_ThrowException_Test()
{
// Act & Assert
Assert.That(() => _warehouseBusinessLogicContract.InsertWarehouse(null), Throws.TypeOf<ArgumentNullException>());
_warehouseStorageContract.Verify(x => x.AddElement(It.IsAny<WarehouseDataModel>()), Times.Never);
}
[Test]
public void InsertWarehouse_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _warehouseBusinessLogicContract.InsertWarehouse(new WarehouseDataModel("id", "aba", [])), Throws.TypeOf<ValidationException>());
_warehouseStorageContract.Verify(x => x.AddElement(It.IsAny<WarehouseDataModel>()), Times.Never);
}
[Test]
public void InsertWarehouse_StorageThrowError_ThrowException_Test()
{
// Arrange
_warehouseStorageContract.Setup(x => x.AddElement(It.IsAny<WarehouseDataModel>())).Throws(new StorageException(new InvalidOperationException()));
// Act & Assert
Assert.That(() => _warehouseBusinessLogicContract.InsertWarehouse(new(Guid.NewGuid().ToString(), "aba",
[new WarehouseCocktailDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<StorageException>());
_warehouseStorageContract.Verify(x => x.AddElement(It.IsAny<WarehouseDataModel>()), Times.Once);
}
[Test]
public void UpdateWarehouse_CorrectRecord_Test()
{
// Arrange
var record = new WarehouseDataModel(Guid.NewGuid().ToString(), "aba",
[new WarehouseCocktailDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]);
_warehouseStorageContract.Setup(x => x.UpdElement(It.IsAny<WarehouseDataModel>()));
// Act
_warehouseBusinessLogicContract.UpdateWarehouse(record);
// Assert
_warehouseStorageContract.Verify(x => x.UpdElement(It.IsAny<WarehouseDataModel>()), Times.Once);
}
[Test]
public void UpdateWarehouse_RecordWithIncorrectData_ThrowException_Test()
{
// Arrange
_warehouseStorageContract.Setup(x => x.UpdElement(It.IsAny<WarehouseDataModel>())).Throws(new ElementNotFoundException(""));
// Act & Assert
Assert.That(() => _warehouseBusinessLogicContract.UpdateWarehouse(new(Guid.NewGuid().ToString(), "aba",
[new WarehouseCocktailDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<ElementNotFoundException>());
_warehouseStorageContract.Verify(x => x.UpdElement(It.IsAny<WarehouseDataModel>()), Times.Once);
}
[Test]
public void UpdateWarehouse_RecordWithExistsData_ThrowException_Test()
{
// Arrange
_warehouseStorageContract.Setup(x => x.UpdElement(It.IsAny<WarehouseDataModel>())).Throws(new ElementExistsException("Data", "Data"));
// Act & Assert
Assert.That(() => _warehouseBusinessLogicContract.UpdateWarehouse(new(Guid.NewGuid().ToString(), "aba",
[new WarehouseCocktailDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<ElementExistsException>());
_warehouseStorageContract.Verify(x => x.UpdElement(It.IsAny<WarehouseDataModel>()), Times.Once);
}
[Test]
public void UpdateWarehouse_NullRecord_ThrowException_Test()
{
// Act & Assert
Assert.That(() => _warehouseBusinessLogicContract.UpdateWarehouse(null), Throws.TypeOf<ArgumentNullException>());
_warehouseStorageContract.Verify(x => x.UpdElement(It.IsAny<WarehouseDataModel>()), Times.Never);
}
[Test]
public void UpdateWarehouse_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _warehouseBusinessLogicContract.UpdateWarehouse(new WarehouseDataModel(Guid.NewGuid().ToString(), "aba", [])), Throws.TypeOf<ValidationException>());
_warehouseStorageContract.Verify(x => x.UpdElement(It.IsAny<WarehouseDataModel>()), Times.Never);
}
[Test]
public void UpdateWarehouse_StorageThrowError_ThrowException_Test()
{
// Arrange
_warehouseStorageContract.Setup(x => x.UpdElement(It.IsAny<WarehouseDataModel>())).Throws(new StorageException(new InvalidOperationException()));
// Act & Assert
Assert.That(() => _warehouseBusinessLogicContract.UpdateWarehouse(new(Guid.NewGuid().ToString(), "aba",
[new WarehouseCocktailDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<StorageException>());
_warehouseStorageContract.Verify(x => x.UpdElement(It.IsAny<WarehouseDataModel>()), Times.Once);
}
[Test]
public void DeleteWarehouse_CorrectRecord_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
var flag = false;
_warehouseStorageContract.Setup(x => x.DelElement(It.Is((string x) => x == id))).Callback(() => { flag = true; });
//Act
_warehouseBusinessLogicContract.DeleteWarehouse(id);
//Assert
_warehouseStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once); Assert.That(flag);
}
[Test]
public void DeleteWarehouse_RecordWithIncorrectId_ThrowException_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
_warehouseStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new ElementNotFoundException(id));
//Act&Assert
Assert.That(() => _warehouseBusinessLogicContract.DeleteWarehouse(Guid.NewGuid().ToString()),
Throws.TypeOf<ElementNotFoundException>());
_warehouseStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
}
[Test]
public void DeleteWarehouse_IdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _warehouseBusinessLogicContract.DeleteWarehouse(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _warehouseBusinessLogicContract.DeleteWarehouse(string.Empty), Throws.TypeOf<ArgumentNullException>());
_warehouseStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Never);
}
[Test]
public void DeleteWarehouse_IdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _warehouseBusinessLogicContract.DeleteWarehouse("id"),
Throws.TypeOf<ValidationException>());
_warehouseStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Never);
}
[Test]
public void DeleteWarehouse_StorageThrowError_ThrowException_Test()
{
//Arrange
_warehouseStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _warehouseBusinessLogicContract.DeleteWarehouse(Guid.NewGuid().ToString()),
Throws.TypeOf<StorageException>());
_warehouseStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
}
}

View File

@@ -0,0 +1,70 @@
using SquirrelContract.DataModels;
using SquirrelContract.Exceptions;
namespace SquirrelTests.DataModelsTests;
[TestFixture]
internal class ClientDataModelTests
{
[Test]
public void IdIsNullOrEmptyTest()
{
var client = CreateDataModel(null, "fio", "number", 10);
Assert.That(() => client.Validate(), Throws.TypeOf<ValidationException>());
client = CreateDataModel(string.Empty, "fio", "number", 10);
Assert.That(() => client.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void IdIsNotGuidTest()
{
var client = CreateDataModel("id", "fio", "number", 10);
Assert.That(() => client.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void FIOIsNullOrEmptyTest()
{
var client = CreateDataModel(Guid.NewGuid().ToString(), null, "number", 10);
Assert.That(() => client.Validate(), Throws.TypeOf<ValidationException>());
client = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, "number", 10);
Assert.That(() => client.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void PhoneNumberIsNullOrEmptyTest()
{
var client = CreateDataModel(Guid.NewGuid().ToString(), "fio", null, 10);
Assert.That(() => client.Validate(), Throws.TypeOf<ValidationException>());
client = CreateDataModel(Guid.NewGuid().ToString(), "fio", string.Empty, 10);
Assert.That(() => client.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void PhoneNumberIsIncorrectTest()
{
var client = CreateDataModel(Guid.NewGuid().ToString(), "fio", "777", 10);
Assert.That(() => client.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void AllFieldsIsCorrectTest()
{
var clientId = Guid.NewGuid().ToString();
var fio = "Fio";
var phoneNumber = "+7-777-777-77-77";
var discountSize = 11;
var buyer = CreateDataModel(clientId, fio, phoneNumber, discountSize);
Assert.That(() => buyer.Validate(), Throws.Nothing);
Assert.Multiple(() =>
{
Assert.That(buyer.Id, Is.EqualTo(clientId));
Assert.That(buyer.FIO, Is.EqualTo(fio));
Assert.That(buyer.PhoneNumber, Is.EqualTo(phoneNumber));
Assert.That(buyer.DiscountSize, Is.EqualTo(discountSize));
});
}
private static ClientDataModel CreateDataModel(string? id, string? fio, string? phoneNumber, double discountSize) =>
new(id, fio, phoneNumber, discountSize);
}

View File

@@ -0,0 +1,71 @@
using SquirrelContract.DataModels;
using SquirrelContract.Enums;
using SquirrelContract.Exceptions;
namespace SquirrelTests.DataModelsTests;
[TestFixture]
internal class CocktailDataModelTests
{
[Test]
public void IdIsNullOrEmptyTest()
{
var cocktail = CreateDataModel(null, "name", 10.5, AlcoholType.Beer);
Assert.That(() => cocktail.Validate(), Throws.TypeOf<ValidationException>());
cocktail = CreateDataModel(string.Empty, "name", 10.5, AlcoholType.Beer);
Assert.That(() => cocktail.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void IdIsNotGuidTest()
{
var cocktail = CreateDataModel("id", "name", 10.5, AlcoholType.Beer);
Assert.That(() => cocktail.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void CocktailNameIsNullOrEmptyTest()
{
var cocktail = CreateDataModel(Guid.NewGuid().ToString(), null, 10.5, AlcoholType.Beer);
Assert.That(() => cocktail.Validate(), Throws.TypeOf<ValidationException>());
cocktail = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, 10.5, AlcoholType.Beer);
Assert.That(() => cocktail.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void PriceIsLessOrZeroTest()
{
var cocktail = CreateDataModel(Guid.NewGuid().ToString(), null, 0, AlcoholType.Beer);
Assert.That(() => cocktail.Validate(), Throws.TypeOf<ValidationException>());
cocktail = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, -10.5, AlcoholType.Beer);
Assert.That(() => cocktail.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void BaseAlcoholIsNoneTest()
{
var cocktail = CreateDataModel(Guid.NewGuid().ToString(), null, 0, AlcoholType.None);
Assert.That(() => cocktail.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void AllFieldsIsCorrectTest()
{
var cocktailId = Guid.NewGuid().ToString();
var cocktailName = "name";
var price = 10.5;
var baseAlcohol = AlcoholType.Vodka;
var cocktail = CreateDataModel(cocktailId, cocktailName, price, baseAlcohol);
Assert.That(() => cocktail.Validate(), Throws.Nothing);
Assert.Multiple(() =>
{
Assert.That(cocktail.Id, Is.EqualTo(cocktailId));
Assert.That(cocktail.CocktailName, Is.EqualTo(cocktailName));
Assert.That(cocktail.Price, Is.EqualTo(price));
Assert.That(cocktail.BaseAlcohol, Is.EqualTo(baseAlcohol));
});
}
private static CocktailDataModel CreateDataModel(string? id, string? cocktailName, double price, AlcoholType baseAlcohol) =>
new(id, cocktailName, price, baseAlcohol);
}

View File

@@ -0,0 +1,52 @@
using SquirrelContract.DataModels;
using SquirrelContract.Exceptions;
namespace SquirrelTests.DataModelsTests;
[TestFixture]
internal class CocktailHistoryDataModelTests
{
[Test]
public void CocktailIdIsNullOrEmptyTest()
{
var cocktail = CreateDataModel(null, 10);
Assert.That(() => cocktail.Validate(), Throws.TypeOf<ValidationException>());
cocktail = CreateDataModel(string.Empty, 10);
Assert.That(() => cocktail.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void ProductIdIsNotGuidTest()
{
var cocktail = CreateDataModel("id", 10);
Assert.That(() => cocktail.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void OldPriceIsLessOrZeroTest()
{
var cocktail = CreateDataModel(Guid.NewGuid().ToString(), 0);
Assert.That(() => cocktail.Validate(), Throws.TypeOf<ValidationException>());
cocktail = CreateDataModel(Guid.NewGuid().ToString(), -10);
Assert.That(() => cocktail.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void AllFieldsIsCorrectTest()
{
var cocktailId = Guid.NewGuid().ToString();
var oldPrice = 10;
var cocktailHistory = CreateDataModel(cocktailId, oldPrice);
Assert.That(() => cocktailHistory.Validate(), Throws.Nothing);
Assert.Multiple(() =>
{
Assert.That(cocktailHistory.CocktailId, Is.EqualTo(cocktailId));
Assert.That(cocktailHistory.OldPrice, Is.EqualTo(oldPrice));
Assert.That(cocktailHistory.ChangeDate, Is.LessThan(DateTime.UtcNow));
Assert.That(cocktailHistory.ChangeDate, Is.GreaterThan(DateTime.UtcNow.AddMinutes(-1)));
});
}
private static CocktailHistoryDataModel CreateDataModel(string? cocktailId, double oldPrice) =>
new(cocktailId, oldPrice);
}

View File

@@ -0,0 +1,108 @@
using SquirrelContract.DataModels;
using SquirrelContract.Exceptions;
namespace SquirrelTests.DataModelsTests;
[TestFixture]
internal class EmployeeDataModelTests
{
[Test]
public void IdIsNullOrEmptyTest()
{
var employee = CreateDataModel(null, "fio", "abc@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18), DateTime.Now, false);
Assert.That(() => employee.Validate(), Throws.TypeOf<ValidationException>());
employee = CreateDataModel(string.Empty, "fio", "abc@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18), DateTime.Now, false);
Assert.That(() => employee.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void IdIsNotGuidTest()
{
var employee = CreateDataModel("id", "fio", "abc@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18), DateTime.Now, false);
Assert.That(() => employee.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void FIOIsNullOrEmptyTest()
{
var employee = CreateDataModel(Guid.NewGuid().ToString(), null, "abc@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18), DateTime.Now, false);
Assert.That(() => employee.Validate(), Throws.TypeOf<ValidationException>());
employee = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, "abc@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18), DateTime.Now, false);
Assert.That(() => employee.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void EmailIsNullOrEmptyTest()
{
var employee = CreateDataModel(Guid.NewGuid().ToString(), "fio", null, Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18), DateTime.Now, false);
Assert.That(() => employee.Validate(), Throws.TypeOf<ValidationException>());
employee = CreateDataModel(Guid.NewGuid().ToString(), "fio", string.Empty, Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18), DateTime.Now, false);
Assert.That(() => employee.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void EmailIsIncorrectTest()
{
var employee = CreateDataModel(Guid.NewGuid().ToString(), "fio", "abc@gmail", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18), DateTime.Now, false);
Assert.That(() => employee.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void PostIdIsNullOrEmptyTest()
{
var employee = CreateDataModel(Guid.NewGuid().ToString(), "fio", "abc@gmail.com", null, DateTime.Now.AddYears(-18), DateTime.Now, false);
Assert.That(() => employee.Validate(), Throws.TypeOf<ValidationException>());
employee = CreateDataModel(Guid.NewGuid().ToString(), "fio", "abc@gmail.com", string.Empty, DateTime.Now.AddYears(-18), DateTime.Now, false);
Assert.That(() => employee.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void PostIdIsNotGuidTest()
{
var employee = CreateDataModel(Guid.NewGuid().ToString(), "fio", "abc@gmail.com", "postId", DateTime.Now.AddYears(-18), DateTime.Now, false);
Assert.That(() => employee.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void BirthDateIsNotCorrectTest()
{
var employee = CreateDataModel(Guid.NewGuid().ToString(), "fio", "abc@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(1), DateTime.Now, false);
Assert.That(() => employee.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void BirthDateAndEmploymentDateIsNotCorrectTest()
{
var employee = CreateDataModel(Guid.NewGuid().ToString(), "fio", "abc@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18), DateTime.Now.AddYears(-18).AddDays(-1), false);
Assert.That(() => employee.Validate(), Throws.TypeOf<ValidationException>());
employee = CreateDataModel(Guid.NewGuid().ToString(), "fio", "abc@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18), DateTime.Now.AddYears(-16), false);
Assert.That(() => employee.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void AllFieldsIsCorrectTest()
{
var employeeId = Guid.NewGuid().ToString();
var fio = "fio";
var employeeEmail = "abc@gmail.com";
var postId = Guid.NewGuid().ToString();
var birthDate = DateTime.Now.AddYears(-18).AddDays(-1);
var employmentDate = DateTime.Now;
var isDelete = false;
var employee = CreateDataModel(employeeId, fio, employeeEmail, postId, birthDate, employmentDate, isDelete);
Assert.That(() => employee.Validate(), Throws.Nothing);
Assert.Multiple(() =>
{
Assert.That(employee.Id, Is.EqualTo(employeeId));
Assert.That(employee.FIO, Is.EqualTo(fio));
Assert.That(employee.Email, Is.EqualTo(employeeEmail));
Assert.That(employee.PostId, Is.EqualTo(postId));
Assert.That(employee.BirthDate, Is.EqualTo(birthDate));
Assert.That(employee.EmploymentDate, Is.EqualTo(employmentDate));
Assert.That(employee.IsDeleted, Is.EqualTo(isDelete));
});
}
private static EmployeeDataModel CreateDataModel(string? id, string? fio, string? email, string? postId, DateTime birthDate, DateTime employmentDate, bool isDeleted) =>
new(id, fio, email, postId, birthDate, employmentDate, isDeleted);
}

View File

@@ -0,0 +1,75 @@
using SquirrelContract.DataModels;
using SquirrelContract.Enums;
using SquirrelContract.Exceptions;
namespace SquirrelTests.DataModelsTests;
[TestFixture]
internal class PostDataModelTests
{
[Test]
public void IdIsNullOrEmptyTest()
{
var post = CreateDataModel(null, "name", PostType.Manager, 10, true, DateTime.UtcNow);
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
post = CreateDataModel(string.Empty, "name", PostType.Manager, 10, true, DateTime.UtcNow);
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void IdIsNotGuidTest()
{
var post = CreateDataModel("id", "name", PostType.Manager, 10, true, DateTime.UtcNow);
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void PostNameIsEmptyTest()
{
var manufacturer = CreateDataModel(Guid.NewGuid().ToString(), null, PostType.Manager, 10, true, DateTime.UtcNow);
Assert.That(() => manufacturer.Validate(), Throws.TypeOf<ValidationException>());
manufacturer = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, PostType.Manager, 10, true, DateTime.UtcNow);
Assert.That(() => manufacturer.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void PostTypeIsNoneTest()
{
var post = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.None, 10, true, DateTime.UtcNow);
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void SalaryIsLessOrZeroTest()
{
var post = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.Manager, 0, true, DateTime.UtcNow);
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
post = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.Manager, -10, true, DateTime.UtcNow);
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void AllFieldsIsCorrectTest()
{
var postId = Guid.NewGuid().ToString();
var postName = "name";
var postType = PostType.Manager;
var salary = 10;
var isActual = false;
var changeDate = DateTime.UtcNow.AddDays(-1);
var post = CreateDataModel(postId, postName, postType, salary, isActual, changeDate);
Assert.That(() => post.Validate(), Throws.Nothing);
Assert.Multiple(() =>
{
Assert.That(post.Id, Is.EqualTo(postId));
Assert.That(post.PostName, Is.EqualTo(postName));
Assert.That(post.PostType, Is.EqualTo(postType));
Assert.That(post.Salary, Is.EqualTo(salary));
Assert.That(post.IsActual, Is.EqualTo(isActual));
Assert.That(post.ChangeDate, Is.EqualTo(changeDate));
});
}
private static PostDataModel CreateDataModel(string? id, string? postName, PostType postType, double salary, bool isActual, DateTime changeDate) =>
new(id, postName, postType, salary, isActual, changeDate);
}

View File

@@ -0,0 +1,52 @@
using BarBelochkaContract.DataModels;
using SquirrelContract.Exceptions;
namespace SquirrelTests.DataModelsTests;
[TestFixture]
internal class SalaryDataModelTests
{
[Test]
public void EmployeeIdIsEmptyTest()
{
var salary = CreateDataModel(null, DateTime.Now, 10);
Assert.That(() => salary.Validate(), Throws.TypeOf<ValidationException>());
salary = CreateDataModel(string.Empty, DateTime.Now, 10);
Assert.That(() => salary.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void EmployeeIdIsNotGuidTest()
{
var salary = CreateDataModel("employeeId", DateTime.Now, 10);
Assert.That(() => salary.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void SalaryIsLessOrZeroTest()
{
var salary = CreateDataModel(Guid.NewGuid().ToString(), DateTime.Now, 0);
Assert.That(() => salary.Validate(), Throws.TypeOf<ValidationException>());
salary = CreateDataModel(Guid.NewGuid().ToString(), DateTime.Now, -10);
Assert.That(() => salary.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void AllFieldsIsCorrectTest()
{
var employeeId = Guid.NewGuid().ToString();
var salaryDate = DateTime.Now.AddDays(-3).AddMinutes(-5);
var enployeeSalary = 10;
var salary = CreateDataModel(employeeId, salaryDate, enployeeSalary);
Assert.That(() => salary.Validate(), Throws.Nothing);
Assert.Multiple(() =>
{
Assert.That(salary.EmployeeId, Is.EqualTo(employeeId));
Assert.That(salary.SalaryDate, Is.EqualTo(salaryDate));
Assert.That(salary.Salary, Is.EqualTo(enployeeSalary));
});
}
private static SalaryDataModel CreateDataModel(string? employeeId, DateTime salaryDate, double employeeSalary) =>
new(employeeId, salaryDate, employeeSalary);
}

View File

@@ -0,0 +1,68 @@
using SquirrelContract.DataModels;
using SquirrelContract.Exceptions;
namespace SquirrelTests.DataModelsTests;
[TestFixture]
internal class SaleCocktailDataModelTests
{
[Test]
public void SaleIdIsNullOrEmptyTest()
{
var saleCocktail = CreateDataModel(null, Guid.NewGuid().ToString(), 10);
Assert.That(() => saleCocktail.Validate(), Throws.TypeOf<ValidationException>());
saleCocktail = CreateDataModel(string.Empty, Guid.NewGuid().ToString(), 10);
Assert.That(() => saleCocktail.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void SaleIdIsNotGuidTest()
{
var saleProduct = CreateDataModel("saleId", Guid.NewGuid().ToString(), 10);
Assert.That(() => saleProduct.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void CocktailIdIsNullOrEmptyTest()
{
var saleCocktail = CreateDataModel(Guid.NewGuid().ToString(), null, 10);
Assert.That(() => saleCocktail.Validate(), Throws.TypeOf<ValidationException>());
saleCocktail = CreateDataModel(string.Empty, Guid.NewGuid().ToString(), 10);
Assert.That(() => saleCocktail.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void ProductIdIsNotGuidTest()
{
var saleCocktail = CreateDataModel(Guid.NewGuid().ToString(), "productId", 10);
Assert.That(() => saleCocktail.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void CountIsLessOrZeroTest()
{
var saleCocktail = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 0);
Assert.That(() => saleCocktail.Validate(), Throws.TypeOf<ValidationException>());
saleCocktail = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), -10);
Assert.That(() => saleCocktail.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void AllFieldsIsCorrectTest()
{
var saleId = Guid.NewGuid().ToString();
var cocktailId = Guid.NewGuid().ToString();
var count = 10;
var saleCocktail = CreateDataModel(saleId, cocktailId, count);
Assert.That(() => saleCocktail.Validate(), Throws.Nothing);
Assert.Multiple(() =>
{
Assert.That(saleCocktail.SaleId, Is.EqualTo(saleId));
Assert.That(saleCocktail.CocktailId, Is.EqualTo(cocktailId));
Assert.That(saleCocktail.Count, Is.EqualTo(count));
});
}
private static SaleCocktailDataModel CreateDataModel(string? saleId, string? cocktailId, int count) =>
new(saleId, cocktailId, count);
}

View File

@@ -0,0 +1,97 @@
using SquirrelContract.DataModels;
using SquirrelContract.Enums;
using SquirrelContract.Exceptions;
namespace SquirrelTests.DataModelsTests;
[TestFixture]
internal class SaleDataModelTests
{
[Test]
public void IdIsNullOrEmptyTest()
{
var sale = CreateDataModel(null, Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 10, DiscountType.OnSale, 10, false, CreateSubDataModel());
Assert.That(() => sale.Validate(), Throws.TypeOf<ValidationException>());
sale = CreateDataModel(string.Empty, Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 10, DiscountType.OnSale, 10, false, CreateSubDataModel());
Assert.That(() => sale.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void IdIsNotGuidTest()
{
var sale = CreateDataModel("id", Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 10, DiscountType.OnSale, 10, false, CreateSubDataModel());
Assert.That(() => sale.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void EmployeeIdIsNullOrEmptyTest()
{
var sale = CreateDataModel(Guid.NewGuid().ToString(), null, Guid.NewGuid().ToString(), 10, DiscountType.OnSale, 10, false, CreateSubDataModel());
Assert.That(() => sale.Validate(), Throws.TypeOf<ValidationException>());
sale = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, Guid.NewGuid().ToString(), 10, DiscountType.OnSale, 10, false, CreateSubDataModel());
Assert.That(() => sale.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void EmployeeIdIsNotGuidTest()
{
var sale = CreateDataModel(Guid.NewGuid().ToString(), "employeeId", Guid.NewGuid().ToString(), 10, DiscountType.OnSale, 10, false, CreateSubDataModel());
Assert.That(() => sale.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void ClientIdIsNotGuidTest()
{
var sale = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), "clientId", 10, DiscountType.OnSale, 10, false, CreateSubDataModel());
Assert.That(() => sale.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void SumIsLessOrZeroTest()
{
var sale = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 0, DiscountType.OnSale, 10, false, CreateSubDataModel());
Assert.That(() => sale.Validate(), Throws.TypeOf<ValidationException>());
sale = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), -10, DiscountType.OnSale, 10, false, CreateSubDataModel());
Assert.That(() => sale.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void CocktailsIsNullOrEmptyTest()
{
var sale = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 10, DiscountType.OnSale, 10, false, null);
Assert.That(() => sale.Validate(), Throws.TypeOf<ValidationException>());
sale = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 10, DiscountType.OnSale, 10, false, []);
Assert.That(() => sale.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void AllFieldsIsCorrectTest()
{
var saleId = Guid.NewGuid().ToString();
var employeeId = Guid.NewGuid().ToString();
var clientId = Guid.NewGuid().ToString();
var sum = 10;
var discountType = DiscountType.Certificate;
var discount = 1;
var isCancel = true;
var cocktails = CreateSubDataModel();
var sale = CreateDataModel(saleId, employeeId, clientId, sum, discountType, discount, isCancel, cocktails);
Assert.That(() => sale.Validate(), Throws.Nothing);
Assert.Multiple(() =>
{
Assert.That(sale.Id, Is.EqualTo(saleId));
Assert.That(sale.EmployeeId, Is.EqualTo(employeeId));
Assert.That(sale.ClientId, Is.EqualTo(clientId));
Assert.That(sale.Sum, Is.EqualTo(sum));
Assert.That(sale.DiscountType, Is.EqualTo(discountType));
Assert.That(sale.Discount, Is.EqualTo(discount));
Assert.That(sale.IsCancel, Is.EqualTo(isCancel));
Assert.That(sale.Cocktails, Is.EquivalentTo(cocktails));
});
}
private static SaleDataModel CreateDataModel(string? id, string? employeeId, string? clientId, double sum, DiscountType discountType, double discount, bool isCancel, List<SaleCocktailDataModel>? cocktails) =>
new(id, employeeId, clientId, sum, discountType, discount, isCancel, cocktails);
private static List<SaleCocktailDataModel> CreateSubDataModel()
=> [new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 1)];
}

View File

@@ -0,0 +1,68 @@
using SquirrelContract.DataModels;
using SquirrelContract.Exceptions;
namespace SquirrelTests.DataModelsTests;
[TestFixture]
internal class SupplyCocktailDataModelTests
{
[Test]
public void SupplyIdIsNullOrEmptyTest()
{
var supplyCocktail = CreateDataModel(null, Guid.NewGuid().ToString(), 10);
Assert.That(() => supplyCocktail.Validate(), Throws.TypeOf<ValidationException>());
supplyCocktail = CreateDataModel(string.Empty, Guid.NewGuid().ToString(), 10);
Assert.That(() => supplyCocktail.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void SupplyIdIsNotGuidTest()
{
var supplyCocktail = CreateDataModel("SupplyId", Guid.NewGuid().ToString(), 10);
Assert.That(() => supplyCocktail.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void CocktailIdIsNullOrEmptyTest()
{
var supplyCocktail = CreateDataModel(Guid.NewGuid().ToString(), null, 10);
Assert.That(() => supplyCocktail.Validate(), Throws.TypeOf<ValidationException>());
supplyCocktail = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, 10);
Assert.That(() => supplyCocktail.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void CocktailIdIsNotGuidTest()
{
var supplyCocktail = CreateDataModel(Guid.NewGuid().ToString(), "ComponentId", 10);
Assert.That(() => supplyCocktail.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void CountIsLessOrZeroTest()
{
var supplyCocktail = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 0);
Assert.That(() => supplyCocktail.Validate(), Throws.TypeOf<ValidationException>());
supplyCocktail = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), -10);
Assert.That(() => supplyCocktail.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void AllFieldsIsCorrectTest()
{
var cocktailId = Guid.NewGuid().ToString();
var supplyId = Guid.NewGuid().ToString();
var count = 5;
var supplyCocktail = CreateDataModel(supplyId, cocktailId, count);
Assert.That(() => supplyCocktail.Validate(), Throws.Nothing);
Assert.Multiple(() =>
{
Assert.That(supplyCocktail.SupplyId, Is.EqualTo(supplyId));
Assert.That(supplyCocktail.CocktailId, Is.EqualTo(cocktailId));
Assert.That(supplyCocktail.Count, Is.EqualTo(count));
});
}
private static SupplyCocktailDataModel CreateDataModel(string? supplyId, string? cocktailId, int count) =>
new(supplyId, cocktailId, count);
}

View File

@@ -0,0 +1,64 @@
using SquirrelContract.DataModels;
using SquirrelContract.Exceptions;
namespace SquirrelTests.DataModelsTests;
[TestFixture]
internal class SupplyDataModelTests
{
[Test]
public void IdIsNullOrEmptyTest()
{
var supply = CreateDataModel(null, DateTime.Now, CreateSubDataModel());
Assert.That(() => supply.Validate(), Throws.TypeOf<ValidationException>());
supply = CreateDataModel(string.Empty, DateTime.Now, CreateSubDataModel());
Assert.That(() => supply.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void IdIsNotGuidTest()
{
var supply = CreateDataModel("id", DateTime.Now, CreateSubDataModel());
Assert.That(() => supply.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void CocktailsIsNullOrEmptyTest()
{
var supply = CreateDataModel(Guid.NewGuid().ToString(), DateTime.Now, null);
Assert.That(() => supply.Validate(), Throws.TypeOf<ValidationException>());
supply = CreateDataModel(Guid.NewGuid().ToString(), DateTime.Now, []);
Assert.That(() => supply.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void DateIsNotCorrectTest()
{
var supply = CreateDataModel(Guid.NewGuid().ToString(), DateTime.Now.AddDays(5), CreateSubDataModel());
Assert.That(() => supply.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void AllFieldsIsCorrectTest()
{
var supplyId = Guid.NewGuid().ToString();
var date = DateTime.Now;
var cocktails = CreateSubDataModel();
var supply = CreateDataModel(supplyId, date, cocktails);
Assert.That(() => supply.Validate(), Throws.Nothing);
Assert.Multiple(() =>
{
Assert.That(supply.Id, Is.EqualTo(supplyId));
Assert.That(supply.SupplyDate, Is.EqualTo(date));
Assert.That(supply.Cocktails, Is.EquivalentTo(cocktails));
});
}
private static SupplyDataModel CreateDataModel(string? id, DateTime date, List<SupplyCocktailDataModel> cocktails) =>
new(id, date, cocktails);
private static List<SupplyCocktailDataModel> CreateSubDataModel()
=> [new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 1)];
}

View File

@@ -0,0 +1,68 @@
using SquirrelContract.DataModels;
using SquirrelContract.Exceptions;
namespace SquirrelTests.DataModelsTests;
[TestFixture]
internal class WarehouseCocktailDataModelTests
{
[Test]
public void WarehouseIdIsNullOrEmptyTest()
{
var warehouseCocktail = CreateDataModel(null, Guid.NewGuid().ToString(), 10);
Assert.That(() => warehouseCocktail.Validate(), Throws.TypeOf<ValidationException>());
warehouseCocktail = CreateDataModel(string.Empty, Guid.NewGuid().ToString(), 10);
Assert.That(() => warehouseCocktail.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void WarehouseIdIsNotGuidTest()
{
var warehouseCocktail = CreateDataModel("id", Guid.NewGuid().ToString(), 10);
Assert.That(() => warehouseCocktail.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void CocktailIdIsNullOrEmptyTest()
{
var warehouseCocktail = CreateDataModel(Guid.NewGuid().ToString(), null, 10);
Assert.That(() => warehouseCocktail.Validate(), Throws.TypeOf<ValidationException>());
warehouseCocktail = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, 10);
Assert.That(() => warehouseCocktail.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void CocktailIdIsNotGuidTest()
{
var warehouseCocktail = CreateDataModel(Guid.NewGuid().ToString(), "id", 10);
Assert.That(() => warehouseCocktail.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void CountIsLessOrZeroTest()
{
var warehouseCocktail = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 0);
Assert.That(() => warehouseCocktail.Validate(), Throws.TypeOf<ValidationException>());
warehouseCocktail = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), -10);
Assert.That(() => warehouseCocktail.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void AllFieldsIsCorrectTest()
{
var cocktailId = Guid.NewGuid().ToString();
var warehouseId = Guid.NewGuid().ToString();
var count = 5;
var warehouseCocktail = CreateDataModel(warehouseId, cocktailId, count);
Assert.That(() => warehouseCocktail.Validate(), Throws.Nothing);
Assert.Multiple(() =>
{
Assert.That(warehouseCocktail.WarehouseId, Is.EqualTo(warehouseId));
Assert.That(warehouseCocktail.CocktailId, Is.EqualTo(cocktailId));
Assert.That(warehouseCocktail.Count, Is.EqualTo(count));
});
}
private static WarehouseCocktailDataModel CreateDataModel(string? storageId, string? cocktailId, int count) =>
new(storageId, cocktailId, count);
}

View File

@@ -0,0 +1,64 @@
using SquirrelContract.DataModels;
using SquirrelContract.Exceptions;
namespace SquirrelTests.DataModelsTests;
[TestFixture]
internal class WarehouseDataModelTests
{
[Test]
public void IdIsNullOrEmptyTest()
{
var warehouse = CreateDataModel(null, "name", CreateSubDataModel());
Assert.That(() => warehouse.Validate(), Throws.TypeOf<ValidationException>());
warehouse = CreateDataModel(string.Empty, "name", CreateSubDataModel());
Assert.That(() => warehouse.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void IdIsNotGuidTest()
{
var warehouse = CreateDataModel("id", "name", CreateSubDataModel());
Assert.That(() => warehouse.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void WarehouseNameIsEmptyTest()
{
var warehouse = CreateDataModel(Guid.NewGuid().ToString(), null, CreateSubDataModel());
Assert.That(() => warehouse.Validate(), Throws.TypeOf<ValidationException>());
warehouse = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, CreateSubDataModel());
Assert.That(() => warehouse.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void CocktailsIsNullOrEmptyTest()
{
var warehouse = CreateDataModel(Guid.NewGuid().ToString(), "name", null);
Assert.That(() => warehouse.Validate(), Throws.TypeOf<ValidationException>());
warehouse = CreateDataModel(Guid.NewGuid().ToString(), "name", []);
Assert.That(() => warehouse.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void AllFieldsIsCorrectTest()
{
var warehouseId = Guid.NewGuid().ToString();
var warehouseName = "name";
var cocktails = CreateSubDataModel();
var warehouse = CreateDataModel(warehouseId, warehouseName, cocktails);
Assert.That(() => warehouse.Validate(), Throws.Nothing);
Assert.Multiple(() =>
{
Assert.That(warehouse.Id, Is.EqualTo(warehouseId));
Assert.That(warehouse.Name, Is.EqualTo(warehouseName));
Assert.That(warehouse.Cocktails, Is.EquivalentTo(cocktails));
});
}
private static WarehouseDataModel CreateDataModel(string? id, string? warehouseName, List<WarehouseCocktailDataModel> cocktails) =>
new(id, warehouseName, cocktails);
private static List<WarehouseCocktailDataModel> CreateSubDataModel()
=> [new(Guid.NewGuid().ToString(), "name", 1)];
}

View File

@@ -0,0 +1,10 @@
using SquirrelContract.Infastructure;
namespace SquirrelTests.Infrastructure;
internal class ConfigurationDatabaseTest : IConfigurationDatabase
{
public string ConnectionString =>
"Host=127.0.0.1;Port=5432;Database=SquirrelTest;Username=postgres;Password=postgres;";
}

View File

@@ -0,0 +1,30 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<LangVersion>latest</LangVersion>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="coverlet.collector" Version="6.0.2" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.12.0" />
<PackageReference Include="Moq" Version="4.20.72" />
<PackageReference Include="NUnit" Version="4.2.2" />
<PackageReference Include="NUnit.Analyzers" Version="4.4.0" />
<PackageReference Include="NUnit3TestAdapter" Version="4.6.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\SquirrelBusinessLogic\SquirrelBusinessLogic.csproj" />
<ProjectReference Include="..\SquirrelContract\SquirrelContract.csproj" />
<ProjectReference Include="..\SquirrelDatabase\SquirrelDatabase.csproj" />
</ItemGroup>
<ItemGroup>
<Using Include="NUnit.Framework" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,25 @@
using SquirrelTests.Infrastructure;
using SquirrelDatabase;
namespace SquirrelTests.StoragesContracts;
internal abstract class BaseStorageContractTest
{
protected SquirrelDbContext SquirrelDbContext { get; private set; }
[OneTimeSetUp]
public void OneTimeSetUp()
{
SquirrelDbContext = new SquirrelDbContext(new ConfigurationDatabaseTest());
SquirrelDbContext.Database.EnsureDeleted();
SquirrelDbContext.Database.EnsureCreated();
}
[OneTimeTearDown]
public void OneTimeTearDown()
{
SquirrelDbContext.Database.EnsureDeleted();
SquirrelDbContext.Dispose();
}
}

View File

@@ -0,0 +1,214 @@
using SquirrelContract.DataModels;
using SquirrelContract.Enums;
using SquirrelContract.Exceptions;
using SquirrelDatabase.Implementations;
using SquirrelDatabase.Models;
using Microsoft.EntityFrameworkCore;
using SquirrelContract.StoragesContracts;
using SquirrelTests.StoragesContracts;
namespace SquirrelTests.StorageContracts;
[TestFixture]
internal class ClientStorageContractTests : BaseStorageContractTest
{
private IClientStorageContract _clientStorageContract;
[SetUp]
public void SetUp()
{
_clientStorageContract = new ClientStorageContract(SquirrelDbContext);
}
[TearDown]
public void TearDown()
{
SquirrelDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Sales\" CASCADE;");
SquirrelDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Employees\" CASCADE;");
SquirrelDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Clients\" CASCADE;");
}
[Test]
public void Try_GetList_WhenHaveRecords_Test()
{
var client = InsertClientToDatabaseAndReturn(Guid.NewGuid().ToString(), phoneNumber: "+5-555-555-55-55");
InsertClientToDatabaseAndReturn(Guid.NewGuid().ToString(), phoneNumber: "+6-666-666-66-66");
InsertClientToDatabaseAndReturn(Guid.NewGuid().ToString(), phoneNumber: "+7-777-777-77-77");
var list = _clientStorageContract.GetList();
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(3));
AssertElement(list.First(x => x.Id == client.Id), client);
}
[Test]
public void Try_GetList_WhenNoRecords_Test()
{
var list = _clientStorageContract.GetList();
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.Empty);
}
[Test]
public void Try_GetElementById_WhenHaveRecord_Test()
{
var client = InsertClientToDatabaseAndReturn(Guid.NewGuid().ToString());
AssertElement(_clientStorageContract.GetElementById(client.Id), client);
}
[Test]
public void Try_GetElementById_WhenNoRecord_Test()
{
InsertClientToDatabaseAndReturn(Guid.NewGuid().ToString());
Assert.That(() => _clientStorageContract.GetElementById(Guid.NewGuid().ToString()), Is.Null);
}
[Test]
public void Try_GetElementByFIO_WhenHaveRecord_Test()
{
var client = InsertClientToDatabaseAndReturn(Guid.NewGuid().ToString());
AssertElement(_clientStorageContract.GetElementByFIO(client.FIO), client);
}
[Test]
public void Try_GetElementByFIO_WhenNoRecord_Test()
{
InsertClientToDatabaseAndReturn(Guid.NewGuid().ToString());
Assert.That(() => _clientStorageContract.GetElementByFIO("New Fio"), Is.Null);
}
[Test]
public void Try_GetElementByPhoneNumber_WhenHaveRecord_Test()
{
var client = InsertClientToDatabaseAndReturn(Guid.NewGuid().ToString());
AssertElement(_clientStorageContract.GetElementByPhoneNumber(client.PhoneNumber), client);
}
[Test]
public void Try_GetElementByPhoneNumber_WhenNoRecord_Test()
{
InsertClientToDatabaseAndReturn(Guid.NewGuid().ToString());
Assert.That(() => _clientStorageContract.GetElementByPhoneNumber("+8-888-888-88-88"), Is.Null);
}
[Test]
public void Try_AddElement_Test()
{
var client = CreateModel(Guid.NewGuid().ToString());
_clientStorageContract.AddElement(client);
AssertElement(GetClientFromDatabase(client.Id), client);
}
[Test]
public void Try_AddElement_WhenHaveRecordWithSameId_Test()
{
var client = CreateModel(Guid.NewGuid().ToString(), "New Fio", "+5-555-555-55-55", 500);
InsertClientToDatabaseAndReturn(client.Id);
Assert.That(() => _clientStorageContract.AddElement(client), Throws.TypeOf<ElementExistsException>());
}
[Test]
public void Try_AddElement_WhenHaveRecordWithSamePhoneNumber_Test()
{
var client = CreateModel(Guid.NewGuid().ToString(), "New Fio", "+5-555-555-55-55", 500);
InsertClientToDatabaseAndReturn(Guid.NewGuid().ToString(), phoneNumber: client.PhoneNumber);
Assert.That(() => _clientStorageContract.AddElement(client), Throws.TypeOf<ElementExistsException>());
}
[Test]
public void Try_UpdElement_Test()
{
var client = CreateModel(Guid.NewGuid().ToString(), "New Fio", "+5-555-555-55-55", 500);
InsertClientToDatabaseAndReturn(client.Id);
_clientStorageContract.UpdElement(client);
AssertElement(GetClientFromDatabase(client.Id), client);
}
[Test]
public void Try_UpdElement_WhenNoRecordWithThisId_Test()
{
Assert.That(() => _clientStorageContract.UpdElement(CreateModel(Guid.NewGuid().ToString())), Throws.TypeOf<ElementNotFoundException>());
}
[Test]
public void Try_UpdElement_WhenHaveRecordWithSamePhoneNumber_Test()
{
var client = CreateModel(Guid.NewGuid().ToString(), "New Fio", "+5-555-555-55-55", 500);
InsertClientToDatabaseAndReturn(client.Id, phoneNumber: "+7-777-777-77-77");
InsertClientToDatabaseAndReturn(Guid.NewGuid().ToString(), phoneNumber: client.PhoneNumber);
Assert.That(() => _clientStorageContract.UpdElement(client), Throws.TypeOf<ElementExistsException>());
}
[Test]
public void Try_DelElement_Test()
{
var client = InsertClientToDatabaseAndReturn(Guid.NewGuid().ToString());
_clientStorageContract.DelElement(client.Id);
var element = GetClientFromDatabase(client.Id);
Assert.That(element, Is.Null);
}
[Test]
public void Try_DelElement_WhenHaveSalesByThisClient_Test()
{
var client = InsertClientToDatabaseAndReturn(Guid.NewGuid().ToString());
var employeeId = Guid.NewGuid().ToString();
SquirrelDbContext.Employees.Add(new Employee() { Id = employeeId, FIO = "test", PostId = Guid.NewGuid().ToString(), Email = "abc@gmail.com" });
SquirrelDbContext.Sales.Add(new Sale() { Id = Guid.NewGuid().ToString(), EmployeeId = employeeId, ClientId = client.Id, Sum = 10, DiscountType = DiscountType.None, Discount = 0 });
SquirrelDbContext.Sales.Add(new Sale() { Id = Guid.NewGuid().ToString(), EmployeeId = employeeId, ClientId = client.Id, Sum = 10, DiscountType = DiscountType.None, Discount = 0 });
SquirrelDbContext.SaveChanges();
var salesBeforeDelete = SquirrelDbContext.Sales.Where(x => x.ClientId == client.Id).ToArray();
_clientStorageContract.DelElement(client.Id);
var element = GetClientFromDatabase(client.Id);
var salesAfterDelete = SquirrelDbContext.Sales.Where(x => x.ClientId == client.Id).ToArray();
Assert.Multiple(() =>
{
Assert.That(element, Is.Null);
Assert.That(salesBeforeDelete, Has.Length.EqualTo(2));
Assert.That(salesAfterDelete, Is.Empty);
Assert.That(SquirrelDbContext.Sales.Count(), Is.EqualTo(2));
});
}
[Test]
public void Try_DelElement_WhenNoRecordWithThisId_Test()
{
Assert.That(() => _clientStorageContract.DelElement(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
}
private Client InsertClientToDatabaseAndReturn(string id, string fio = "test", string phoneNumber = "+7-777-777-77-77", double discountSize = 10)
{
var client = new Client() { Id = id, FIO = fio, PhoneNumber = phoneNumber, DiscountSize = discountSize };
SquirrelDbContext.Clients.Add(client);
SquirrelDbContext.SaveChanges();
return client;
}
private static void AssertElement(ClientDataModel? actual, Client expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.Id, Is.EqualTo(expected.Id));
Assert.That(actual.FIO, Is.EqualTo(expected.FIO));
Assert.That(actual.PhoneNumber, Is.EqualTo(expected.PhoneNumber));
Assert.That(actual.DiscountSize, Is.EqualTo(expected.DiscountSize));
});
}
private static ClientDataModel CreateModel(string id, string fio = "test", string phoneNumber = "+7-777-777-77-77", double discountSize = 10)
=> new(id, fio, phoneNumber, discountSize);
private Client? GetClientFromDatabase(string id) => SquirrelDbContext.Clients.FirstOrDefault(x => x.Id == id);
private static void AssertElement(Client? actual, ClientDataModel expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.Id, Is.EqualTo(expected.Id));
Assert.That(actual.FIO, Is.EqualTo(expected.FIO));
Assert.That(actual.PhoneNumber, Is.EqualTo(expected.PhoneNumber));
Assert.That(actual.DiscountSize, Is.EqualTo(expected.DiscountSize));
});
}
}

View File

@@ -0,0 +1,208 @@
using Microsoft.EntityFrameworkCore;
using SquirrelContract.DataModels;
using SquirrelContract.Enums;
using SquirrelContract.Exceptions;
using SquirrelDatabase.Implementations;
using SquirrelDatabase.Models;
using SquirrelTests.StoragesContracts;
using static NUnit.Framework.Internal.OSPlatform;
namespace SquirrelTests.StorageContracts;
[TestFixture]
internal class CocktailStorageContractTests : BaseStorageContractTest
{
private CocktailStorageContract _cocktailStorageContract;
[SetUp]
public void SetUp()
{
_cocktailStorageContract = new CocktailStorageContract(SquirrelDbContext);
}
[TearDown]
public void TearDown()
{
SquirrelDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Cocktails\" CASCADE;");
}
[Test]
public void Try_GetList_WhenHaveRecords_Test()
{
var cocktail = InsertCocktailToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 1");
InsertCocktailToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 2");
InsertCocktailToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 3");
var list = _cocktailStorageContract.GetList();
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(3));
AssertElement(list.First(x => x.Id == cocktail.Id), cocktail);
}
[Test]
public void Try_GetList_WhenNoRecords_Test()
{
var list = _cocktailStorageContract.GetList();
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.Empty);
}
[Test]
public void Try_GetHistoryByCocktailId_WhenHaveRecords_Test()
{
var cocktail = InsertCocktailToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 1");
InsertCocktailHistoryToDatabaseAndReturn(cocktail.Id, 20, DateTime.UtcNow.AddDays(-1));
InsertCocktailHistoryToDatabaseAndReturn(cocktail.Id, 30, DateTime.UtcNow.AddMinutes(-10));
InsertCocktailHistoryToDatabaseAndReturn(cocktail.Id, 40, DateTime.UtcNow.AddDays(1));
var list = _cocktailStorageContract.GetHistoryByCocktailId(cocktail.Id);
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(3));
}
[Test]
public void Try_GetHistoryByCocktailId_WhenNoRecords_Test()
{
var cocktail = InsertCocktailToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 1");
InsertCocktailHistoryToDatabaseAndReturn(cocktail.Id, 20, DateTime.UtcNow.AddDays(-1));
InsertCocktailHistoryToDatabaseAndReturn(cocktail.Id, 30, DateTime.UtcNow.AddMinutes(-10));
InsertCocktailHistoryToDatabaseAndReturn(cocktail.Id, 40, DateTime.UtcNow.AddDays(1));
var list = _cocktailStorageContract.GetHistoryByCocktailId(Guid.NewGuid().ToString());
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
}
[Test]
public void Try_GetElementById_WhenHaveRecord_Test()
{
var cocktail = InsertCocktailToDatabaseAndReturn(Guid.NewGuid().ToString());
AssertElement(_cocktailStorageContract.GetElementById(cocktail.Id), cocktail);
}
[Test]
public void Try_GetElementById_WhenNoRecord_Test()
{
InsertCocktailToDatabaseAndReturn(Guid.NewGuid().ToString());
Assert.That(() => _cocktailStorageContract.GetElementById(Guid.NewGuid().ToString()), Is.Null);
}
[Test]
public void Try_GetElementByName_WhenHaveRecord_Test()
{
var cocktail = InsertCocktailToDatabaseAndReturn(Guid.NewGuid().ToString());
AssertElement(_cocktailStorageContract.GetElementByName(cocktail.CocktailName), cocktail);
}
[Test]
public void Try_GetElementByName_WhenNoRecord_Test()
{
InsertCocktailToDatabaseAndReturn(Guid.NewGuid().ToString());
Assert.That(() => _cocktailStorageContract.GetElementByName("name"), Is.Null);
}
[Test]
public void Try_AddElement_Test()
{
var cocktail = CreateModel(Guid.NewGuid().ToString());
_cocktailStorageContract.AddElement(cocktail);
AssertElement(GetCocktailFromDatabaseById(cocktail.Id), cocktail);
}
[Test]
public void Try_AddElement_WhenHaveRecordWithSameId_Test()
{
var cocktail = CreateModel(Guid.NewGuid().ToString());
InsertCocktailToDatabaseAndReturn(cocktail.Id, cocktailName: "name unique");
Assert.That(() => _cocktailStorageContract.AddElement(cocktail), Throws.TypeOf<ElementExistsException>());
}
[Test]
public void Try_AddElement_WhenHaveRecordWithSameName_Test()
{
var cocktail = CreateModel(Guid.NewGuid().ToString(), "name unique");
InsertCocktailToDatabaseAndReturn(Guid.NewGuid().ToString(), cocktailName: cocktail.CocktailName);
Assert.That(() => _cocktailStorageContract.AddElement(cocktail), Throws.TypeOf<ElementExistsException>());
}
[Test]
public void Try_UpdElement_Test()
{
var cocktail = CreateModel(Guid.NewGuid().ToString(), "new name", AlcoholType.Vodka);
InsertCocktailToDatabaseAndReturn(cocktail.Id);
_cocktailStorageContract.UpdElement(cocktail);
AssertElement(GetCocktailFromDatabaseById(cocktail.Id), cocktail);
}
[Test]
public void Try_UpdElement_WhenNoRecordWithThisId_Test()
{
Assert.That(() => _cocktailStorageContract.UpdElement(CreateModel(Guid.NewGuid().ToString())), Throws.TypeOf<ElementNotFoundException>());
}
[Test]
public void Try_UpdElement_WhenHaveRecordWithSameName_Test()
{
var cocktail = CreateModel(Guid.NewGuid().ToString(), "name unique");
InsertCocktailToDatabaseAndReturn(cocktail.Id, cocktailName: "name");
InsertCocktailToDatabaseAndReturn(Guid.NewGuid().ToString(), cocktailName: cocktail.CocktailName);
Assert.That(() => _cocktailStorageContract.UpdElement(cocktail), Throws.TypeOf<ElementExistsException>());
}
[Test]
public void Try_DelElement_Test()
{
var cocktail = InsertCocktailToDatabaseAndReturn(Guid.NewGuid().ToString());
_cocktailStorageContract.DelElement(cocktail.Id);
var element = GetCocktailFromDatabaseById(cocktail.Id);
Assert.That(element, Is.Null);
}
[Test]
public void Try_DelElement_WhenNoRecordWithThisId_Test()
{
Assert.That(() => _cocktailStorageContract.DelElement(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
}
private Cocktail InsertCocktailToDatabaseAndReturn(string id, string cocktailName = "test", AlcoholType baseAlcohol = AlcoholType.Vodka, double price = 1)
{
var cocktail = new Cocktail() { Id = id, CocktailName = cocktailName, BaseAlcohol = baseAlcohol, Price = price };
SquirrelDbContext.Cocktails.Add(cocktail);
SquirrelDbContext.SaveChanges();
return cocktail;
}
private CocktailHistory InsertCocktailHistoryToDatabaseAndReturn(string cocktailId, double price, DateTime changeDate)
{
var cocktailHistory = new CocktailHistory() { Id = Guid.NewGuid().ToString(), CocktailId = cocktailId, OldPrice = price, ChangeDate = changeDate };
SquirrelDbContext.CocktailHistories.Add(cocktailHistory);
SquirrelDbContext.SaveChanges();
return cocktailHistory;
}
private static void AssertElement(CocktailDataModel? actual, Cocktail expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.Id, Is.EqualTo(expected.Id));
Assert.That(actual.CocktailName, Is.EqualTo(expected.CocktailName));
Assert.That(actual.BaseAlcohol, Is.EqualTo(expected.BaseAlcohol));
Assert.That(actual.Price, Is.EqualTo(expected.Price));
});
}
private static CocktailDataModel CreateModel(string id, string cocktailName = "test", AlcoholType baseAlcohol = AlcoholType.Beer, double price = 1)
=> new(id, cocktailName, price, baseAlcohol);
private Cocktail? GetCocktailFromDatabaseById(string id) => SquirrelDbContext.Cocktails.FirstOrDefault(x => x.Id == id);
private static void AssertElement(Cocktail? actual, CocktailDataModel expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.Id, Is.EqualTo(expected.Id));
Assert.That(actual.CocktailName, Is.EqualTo(expected.CocktailName));
Assert.That(actual.BaseAlcohol, Is.EqualTo(expected.BaseAlcohol));
Assert.That(actual.Price, Is.EqualTo(expected.Price));
});
}
}

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