15 Commits

90 changed files with 8108 additions and 1 deletions

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="CatHasPawsTests" />
<InternalsVisibleTo Include="DynamicProxyGenAssembly2" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="9.0.1" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\CatHasPawsContratcs\CatHasPawsContratcs.csproj" />
</ItemGroup>
</Project>

View File

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

View File

@@ -0,0 +1,66 @@
using CatHasPawsContratcs.BusinessLogicsContracts;
using CatHasPawsContratcs.DataModels;
using CatHasPawsContratcs.Exceptions;
using CatHasPawsContratcs.Extensions;
using CatHasPawsContratcs.StoragesContracts;
using Microsoft.Extensions.Logging;
using System.Text.Json;
namespace CatHasPawsBusinessLogic.Implementations;
internal class ManufacturerBusinessLogicContract(IManufacturerStorageContract manufacturerStorageContract, ILogger logger) : IManufacturerBusinessLogicContract
{
private readonly ILogger _logger = logger;
private readonly IManufacturerStorageContract _manufacturerStorageContract = manufacturerStorageContract;
public List<ManufacturerDataModel> GetAllManufacturers()
{
_logger.LogInformation("GetAllManufacturers");
return _manufacturerStorageContract.GetList() ?? throw new NullListException();
}
public ManufacturerDataModel GetManufacturerByData(string data)
{
_logger.LogInformation("Get element by data: {data}", data);
if (data.IsEmpty())
{
throw new ArgumentNullException(nameof(data));
}
if (data.IsGuid())
{
return _manufacturerStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data);
}
return _manufacturerStorageContract.GetElementByName(data) ?? _manufacturerStorageContract.GetElementByOldName(data) ??
throw new ElementNotFoundException(data);
}
public void InsertManufacturer(ManufacturerDataModel manufacturerDataModel)
{
_logger.LogInformation("New data: {json}", JsonSerializer.Serialize(manufacturerDataModel));
ArgumentNullException.ThrowIfNull(manufacturerDataModel);
manufacturerDataModel.Validate();
_manufacturerStorageContract.AddElement(manufacturerDataModel);
}
public void UpdateManufacturer(ManufacturerDataModel manufacturerDataModel)
{
_logger.LogInformation("Update data: {json}", JsonSerializer.Serialize(manufacturerDataModel));
ArgumentNullException.ThrowIfNull(manufacturerDataModel);
manufacturerDataModel.Validate();
_manufacturerStorageContract.UpdElement(manufacturerDataModel);
}
public void DeleteManufacturer(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");
}
_manufacturerStorageContract.DelElement(id);
}
}

View File

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

View File

@@ -0,0 +1,64 @@
using CatHasPawsContratcs.BusinessLogicsContracts;
using CatHasPawsContratcs.DataModels;
using CatHasPawsContratcs.Exceptions;
using CatHasPawsContratcs.Extensions;
using CatHasPawsContratcs.StoragesContracts;
using Microsoft.Extensions.Logging;
namespace CatHasPawsBusinessLogic.Implementations;
internal class SalaryBusinessLogicContract(ISalaryStorageContract salaryStorageContract,
ISaleStorageContract saleStorageContract, IPostStorageContract postStorageContract, IWorkerStorageContract workerStorageContract, 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 IWorkerStorageContract _workerStorageContract = workerStorageContract;
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> GetAllSalariesByPeriodByWorker(DateTime fromDate, DateTime toDate, string workerId)
{
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate);
}
if (workerId.IsEmpty())
{
throw new ArgumentNullException(nameof(workerId));
}
if (!workerId.IsGuid())
{
throw new ValidationException("The value in the field workerId is not a unique identifier.");
}
_logger.LogInformation("GetAllSalaries params: {fromDate}, {toDate}, {workerId}", fromDate, toDate, workerId);
return _salaryStorageContract.GetList(fromDate, toDate, workerId) ?? 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 workers = _workerStorageContract.GetList() ?? throw new NullListException();
foreach (var worker in workers)
{
var sales = _saleStorageContract.GetList(startDate, finishDate, workerId: worker.Id)?.Sum(x => x.Sum) ??
throw new NullListException();
var post = _postStorageContract.GetElementById(worker.PostId) ??
throw new NullListException();
var salary = post.Salary + sales * 0.1;
_logger.LogDebug("The employee {workerId} was paid a salary of {salary}", worker.Id, salary);
_salaryStorageContract.AddElement(new SalaryDataModel(worker.Id, finishDate, salary));
}
}
}

View File

@@ -0,0 +1,115 @@
using CatHasPawsContratcs.BusinessLogicsContracts;
using CatHasPawsContratcs.DataModels;
using CatHasPawsContratcs.Exceptions;
using CatHasPawsContratcs.Extensions;
using CatHasPawsContratcs.StoragesContracts;
using Microsoft.Extensions.Logging;
using System.Text.Json;
namespace CatHasPawsBusinessLogic.Implementations;
internal class SaleBusinessLogicContract(ISaleStorageContract saleStorageContract, ILogger logger) : ISaleBusinessLogicContract
{
private readonly ILogger _logger = logger;
private readonly ISaleStorageContract _saleStorageContract = saleStorageContract;
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> GetAllSalesByWorkerByPeriod(string workerId, DateTime fromDate, DateTime toDate)
{
_logger.LogInformation("GetAllSales params: {workerId}, {fromDate}, {toDate}", workerId, fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate);
}
if (workerId.IsEmpty())
{
throw new ArgumentNullException(nameof(workerId));
}
if (!workerId.IsGuid())
{
throw new ValidationException("The value in the field workerId is not a unique identifier.");
}
return _saleStorageContract.GetList(fromDate, toDate, workerId: workerId) ?? throw new NullListException();
}
public List<SaleDataModel> GetAllSalesByBuyerByPeriod(string buyerId, DateTime fromDate, DateTime toDate)
{
_logger.LogInformation("GetAllSales params: {buyerId}, {fromDate}, {toDate}", buyerId, fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate);
}
if (buyerId.IsEmpty())
{
throw new ArgumentNullException(nameof(buyerId));
}
if (!buyerId.IsGuid())
{
throw new ValidationException("The value in the field buyerId is not a unique identifier.");
}
return _saleStorageContract.GetList(fromDate, toDate, buyerId: buyerId) ?? throw new NullListException();
}
public List<SaleDataModel> GetAllSalesByProductByPeriod(string productId, DateTime fromDate, DateTime toDate)
{
_logger.LogInformation("GetAllSales params: {productId}, {fromDate}, {toDate}", productId, fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate);
}
if (productId.IsEmpty())
{
throw new ArgumentNullException(nameof(productId));
}
if (!productId.IsGuid())
{
throw new ValidationException("The value in the field productId is not a unique identifier.");
}
return _saleStorageContract.GetList(fromDate, toDate, productId: productId) ?? 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();
_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,99 @@
using CatHasPawsContratcs.BusinessLogicsContracts;
using CatHasPawsContratcs.DataModels;
using CatHasPawsContratcs.Exceptions;
using CatHasPawsContratcs.Extensions;
using CatHasPawsContratcs.StoragesContracts;
using Microsoft.Extensions.Logging;
using System.Text.Json;
namespace CatHasPawsBusinessLogic.Implementations;
internal class WorkerBusinessLogicContract(IWorkerStorageContract workerStorageContract, ILogger logger) : IWorkerBusinessLogicContract
{
private readonly ILogger _logger = logger;
private readonly IWorkerStorageContract _workerStorageContract = workerStorageContract;
public List<WorkerDataModel> GetAllWorkers(bool onlyActive = true)
{
_logger.LogInformation("GetAllWorkers params: {onlyActive}", onlyActive);
return _workerStorageContract.GetList(onlyActive) ?? throw new NullListException();
}
public List<WorkerDataModel> GetAllWorkersByPost(string postId, bool onlyActive = true)
{
_logger.LogInformation("GetAllWorkers 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 _workerStorageContract.GetList(onlyActive, postId) ?? throw new NullListException();
}
public List<WorkerDataModel> GetAllWorkersByBirthDate(DateTime fromDate, DateTime toDate, bool onlyActive = true)
{
_logger.LogInformation("GetAllWorkers params: {onlyActive}, {fromDate}, {toDate}", onlyActive, fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate);
}
return _workerStorageContract.GetList(onlyActive, fromBirthDate: fromDate, toBirthDate: toDate) ?? throw new NullListException();
}
public List<WorkerDataModel> GetAllWorkersByEmploymentDate(DateTime fromDate, DateTime toDate, bool onlyActive = true)
{
_logger.LogInformation("GetAllWorkers params: {onlyActive}, {fromDate}, {toDate}", onlyActive, fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate);
}
return _workerStorageContract.GetList(onlyActive, fromEmploymentDate: fromDate, toEmploymentDate: toDate) ?? throw new NullListException();
}
public WorkerDataModel GetWorkerByData(string data)
{
_logger.LogInformation("Get element by data: {data}", data);
if (data.IsEmpty())
{
throw new ArgumentNullException(nameof(data));
}
if (data.IsGuid())
{
return _workerStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data);
}
return _workerStorageContract.GetElementByFIO(data) ?? throw new ElementNotFoundException(data);
}
public void InsertWorker(WorkerDataModel workerDataModel)
{
_logger.LogInformation("New data: {json}", JsonSerializer.Serialize(workerDataModel));
ArgumentNullException.ThrowIfNull(workerDataModel);
workerDataModel.Validate();
_workerStorageContract.AddElement(workerDataModel);
}
public void UpdateWorker(WorkerDataModel workerDataModel)
{
_logger.LogInformation("Update data: {json}", JsonSerializer.Serialize(workerDataModel));
ArgumentNullException.ThrowIfNull(workerDataModel);
workerDataModel.Validate();
_workerStorageContract.UpdElement(workerDataModel);
}
public void DeleteWorker(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");
}
_workerStorageContract.DelElement(id);
}
}

View File

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

View File

@@ -0,0 +1,16 @@
using CatHasPawsContratcs.DataModels;
namespace CatHasPawsContratcs.BusinessLogicsContracts;
public interface IManufacturerBusinessLogicContract
{
List<ManufacturerDataModel> GetAllManufacturers();
ManufacturerDataModel GetManufacturerByData(string data);
void InsertManufacturer(ManufacturerDataModel manufacturerDataModel);
void UpdateManufacturer(ManufacturerDataModel manufacturerDataModel);
void DeleteManufacturer(string id);
}

View File

@@ -0,0 +1,20 @@
using CatHasPawsContratcs.DataModels;
namespace CatHasPawsContratcs.BusinessLogicsContracts;
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,20 @@
using CatHasPawsContratcs.DataModels;
namespace CatHasPawsContratcs.BusinessLogicsContracts;
public interface IProductBusinessLogicContract
{
List<ProductDataModel> GetAllProducts(bool onlyActive = true);
List<ProductDataModel> GetAllProductsByManufacturer(string manufacturerId, bool onlyActive = true);
List<ProductHistoryDataModel> GetProductHistoryByProduct(string productId);
ProductDataModel GetProductByData(string data);
void InsertProduct(ProductDataModel productDataModel);
void UpdateProduct(ProductDataModel productDataModel);
void DeleteProduct(string id);
}

View File

@@ -0,0 +1,12 @@
using CatHasPawsContratcs.DataModels;
namespace CatHasPawsContratcs.BusinessLogicsContracts;
public interface ISalaryBusinessLogicContract
{
List<SalaryDataModel> GetAllSalariesByPeriod(DateTime fromDate, DateTime toDate);
List<SalaryDataModel> GetAllSalariesByPeriodByWorker(DateTime fromDate, DateTime toDate, string workerId);
void CalculateSalaryByMounth(DateTime date);
}

View File

@@ -0,0 +1,20 @@
using CatHasPawsContratcs.DataModels;
namespace CatHasPawsContratcs.BusinessLogicsContracts;
public interface ISaleBusinessLogicContract
{
List<SaleDataModel> GetAllSalesByPeriod(DateTime fromDate, DateTime toDate);
List<SaleDataModel> GetAllSalesByWorkerByPeriod(string workerId, DateTime fromDate, DateTime toDate);
List<SaleDataModel> GetAllSalesByBuyerByPeriod(string buyerId, DateTime fromDate, DateTime toDate);
List<SaleDataModel> GetAllSalesByProductByPeriod(string productId, DateTime fromDate, DateTime toDate);
SaleDataModel GetSaleByData(string data);
void InsertSale(SaleDataModel saleDataModel);
void CancelSale(string id);
}

View File

@@ -0,0 +1,22 @@
using CatHasPawsContratcs.DataModels;
namespace CatHasPawsContratcs.BusinessLogicsContracts;
public interface IWorkerBusinessLogicContract
{
List<WorkerDataModel> GetAllWorkers(bool onlyActive = true);
List<WorkerDataModel> GetAllWorkersByPost(string postId, bool onlyActive = true);
List<WorkerDataModel> GetAllWorkersByBirthDate(DateTime fromDate, DateTime toDate, bool onlyActive = true);
List<WorkerDataModel> GetAllWorkersByEmploymentDate(DateTime fromDate, DateTime toDate, bool onlyActive = true);
WorkerDataModel GetWorkerByData(string data);
void InsertWorker(WorkerDataModel workerDataModel);
void UpdateWorker(WorkerDataModel workerDataModel);
void DeleteWorker(string id);
}

View File

@@ -0,0 +1,35 @@
using CatHasPawsContratcs.Exceptions;
using CatHasPawsContratcs.Extensions;
using CatHasPawsContratcs.Infrastructure;
using System.Text.RegularExpressions;
namespace CatHasPawsContratcs.DataModels;
public class BuyerDataModel(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,28 @@
using CatHasPawsContratcs.Exceptions;
using CatHasPawsContratcs.Extensions;
using CatHasPawsContratcs.Infrastructure;
namespace CatHasPawsContratcs.DataModels;
public class ManufacturerDataModel(string id, string manufacturerName, string? prevManufacturerName, string? prevPrevManufacturerName) : IValidation
{
public string Id { get; private set; } = id;
public string ManufacturerName { get; private set; } = manufacturerName;
public string? PrevManufacturerName { get; private set; } = prevManufacturerName;
public string? PrevPrevManufacturerName { get; private set; } = prevPrevManufacturerName;
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 (ManufacturerName.IsEmpty())
throw new ValidationException("Field ManufacturerName is empty");
}
}

View File

@@ -0,0 +1,39 @@
using CatHasPawsContratcs.Enums;
using CatHasPawsContratcs.Exceptions;
using CatHasPawsContratcs.Extensions;
using CatHasPawsContratcs.Infrastructure;
namespace CatHasPawsContratcs.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,45 @@
using CatHasPawsContratcs.Enums;
using CatHasPawsContratcs.Exceptions;
using CatHasPawsContratcs.Extensions;
using CatHasPawsContratcs.Infrastructure;
namespace CatHasPawsContratcs.DataModels;
public class ProductDataModel(string id, string productName, ProductType productType, string manufacturerId, double price, bool isDeleted) : IValidation
{
public string Id { get; private set; } = id;
public string ProductName { get; private set; } = productName;
public ProductType ProductType { get; private set; } = productType;
public string ManufacturerId { get; private set; } = manufacturerId;
public double Price { get; private set; } = price;
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 (ProductName.IsEmpty())
throw new ValidationException("Field ProductName is empty");
if (ProductType == ProductType.None)
throw new ValidationException("Field ProductType is empty");
if (ManufacturerId.IsEmpty())
throw new ValidationException("Field ManufacturerId is empty");
if (!ManufacturerId.IsGuid())
throw new ValidationException("The value in the field ManufacturerId is not a unique identifier");
if (Price <= 0)
throw new ValidationException("Field Price is less than or equal to 0");
}
}

View File

@@ -0,0 +1,26 @@
using CatHasPawsContratcs.Exceptions;
using CatHasPawsContratcs.Extensions;
using CatHasPawsContratcs.Infrastructure;
namespace CatHasPawsContratcs.DataModels;
public class ProductHistoryDataModel(string productId, double oldPrice) : IValidation
{
public string ProductId { get; private set; } = productId;
public double OldPrice { get; private set; } = oldPrice;
public DateTime ChangeDate { get; private set; } = DateTime.UtcNow;
public void Validate()
{
if (ProductId.IsEmpty())
throw new ValidationException("Field ProductId is empty");
if (!ProductId.IsGuid())
throw new ValidationException("The value in the field ProductId 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,26 @@
using CatHasPawsContratcs.Exceptions;
using CatHasPawsContratcs.Extensions;
using CatHasPawsContratcs.Infrastructure;
namespace CatHasPawsContratcs.DataModels;
public class SalaryDataModel(string workerId, DateTime salaryDate, double workerSalary) : IValidation
{
public string WorkerId { get; private set; } = workerId;
public DateTime SalaryDate { get; private set; } = salaryDate;
public double Salary { get; private set; } = workerSalary;
public void Validate()
{
if (WorkerId.IsEmpty())
throw new ValidationException("Field WorkerId is empty");
if (!WorkerId.IsGuid())
throw new ValidationException("The value in the field WorkerId 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,51 @@
using CatHasPawsContratcs.Enums;
using CatHasPawsContratcs.Exceptions;
using CatHasPawsContratcs.Extensions;
using CatHasPawsContratcs.Infrastructure;
namespace CatHasPawsContratcs.DataModels;
public class SaleDataModel(string id, string workerId, string? buyerId, double sum, DiscountType discountType, double discount, bool isCancel, List<SaleProductDataModel> saleProducts) : IValidation
{
public string Id { get; private set; } = id;
public string WorkerId { get; private set; } = workerId;
public string? BuyerId { get; private set; } = buyerId;
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<SaleProductDataModel> Products { get; private set; } = saleProducts;
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 (WorkerId.IsEmpty())
throw new ValidationException("Field WorkerId is empty");
if (!WorkerId.IsGuid())
throw new ValidationException("The value in the field WorkerId is not a unique identifier");
if (!BuyerId?.IsGuid() ?? !BuyerId?.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 ((Products?.Count ?? 0) == 0)
throw new ValidationException("The sale must include products");
}
}

View File

@@ -0,0 +1,32 @@
using CatHasPawsContratcs.Exceptions;
using CatHasPawsContratcs.Extensions;
using CatHasPawsContratcs.Infrastructure;
namespace CatHasPawsContratcs.DataModels;
public class SaleProductDataModel(string saleId, string productId, int count) : IValidation
{
public string SaleId { get; private set; } = saleId;
public string ProductId { get; private set; } = productId;
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 (ProductId.IsEmpty())
throw new ValidationException("Field ProductId is empty");
if (!ProductId.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,47 @@
using CatHasPawsContratcs.Exceptions;
using CatHasPawsContratcs.Extensions;
using CatHasPawsContratcs.Infrastructure;
namespace CatHasPawsContratcs.DataModels;
public class WorkerDataModel(string id, string fio, 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 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 (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(-16).Date)
throw new ValidationException($"Minors cannot be hired (BirthDate = {BirthDate.ToShortDateString()})");
if (EmploymentDate.Date < BirthDate.Date)
throw new ValidationException("The date of employment cannot be less than the date of birth");
if ((EmploymentDate - BirthDate).TotalDays / 365 < 16) // EmploymentDate.Year - BirthDate.Year
throw new ValidationException($"Minors cannot be hired (EmploymentDate - {EmploymentDate.ToShortDateString()}, BirthDate - {BirthDate.ToShortDateString()})");
}
}

View File

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

View File

@@ -0,0 +1,9 @@
namespace CatHasPawsContratcs.Enums;
public enum PostType
{
None = 0,
Supervisor = 1,
CashierConsultant = 2,
Assistant = 3
}

View File

@@ -0,0 +1,9 @@
namespace CatHasPawsContratcs.Enums;
public enum ProductType
{
None = 0,
Feed = 1,
Toy = 2,
Accessory = 3
}

View File

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

View File

@@ -0,0 +1,14 @@
namespace CatHasPawsContratcs.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,11 @@
namespace CatHasPawsContratcs.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,6 @@
namespace CatHasPawsContratcs.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,6 @@
namespace CatHasPawsContratcs.Exceptions;
public class NullListException : Exception
{
public NullListException() : base("The returned list is null") { }
}

View File

@@ -0,0 +1,6 @@
namespace CatHasPawsContratcs.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 CatHasPawsContratcs.Exceptions;
public class ValidationException(string message) : Exception(message)
{
}

View File

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

View File

@@ -0,0 +1,14 @@
namespace CatHasPawsContratcs.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 CatHasPawsContratcs.Infrastructure;
public interface IConfigurationDatabase
{
string ConnectionString { get; }
}

View File

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

View File

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

View File

@@ -0,0 +1,20 @@
using CatHasPawsContratcs.DataModels;
namespace CatHasPawsContratcs.StoragesContracts;
public interface IManufacturerStorageContract
{
List<ManufacturerDataModel> GetList();
ManufacturerDataModel? GetElementById(string id);
ManufacturerDataModel? GetElementByName(string name);
ManufacturerDataModel? GetElementByOldName(string name);
void AddElement(ManufacturerDataModel manufacturerDataModel);
void UpdElement(ManufacturerDataModel manufacturerDataModel);
void DelElement(string id);
}

View File

@@ -0,0 +1,22 @@
using CatHasPawsContratcs.DataModels;
namespace CatHasPawsContratcs.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,20 @@
using CatHasPawsContratcs.DataModels;
namespace CatHasPawsContratcs.StoragesContracts;
public interface IProductStorageContract
{
List<ProductDataModel> GetList(bool onlyActive = true, string? manufacturerId = null);
List<ProductHistoryDataModel> GetHistoryByProductId(string productId);
ProductDataModel? GetElementById(string id);
ProductDataModel? GetElementByName(string name);
void AddElement(ProductDataModel productDataModel);
void UpdElement(ProductDataModel productDataModel);
void DelElement(string id);
}

View File

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

View File

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

View File

@@ -0,0 +1,18 @@
using CatHasPawsContratcs.DataModels;
namespace CatHasPawsContratcs.StoragesContracts;
public interface IWorkerStorageContract
{
List<WorkerDataModel> GetList(bool onlyActive = true, string? postId = null, DateTime? fromBirthDate = null, DateTime? toBirthDate = null, DateTime? fromEmploymentDate = null, DateTime? toEmploymentDate = null);
WorkerDataModel? GetElementById(string id);
WorkerDataModel? GetElementByFIO(string fio);
void AddElement(WorkerDataModel workerDataModel);
void UpdElement(WorkerDataModel workerDataModel);
void DelElement(string id);
}

View File

@@ -0,0 +1,24 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="AutoMapper" Version="14.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="9.0.2" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="9.0.3" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\CatHasPawsContratcs\CatHasPawsContratcs.csproj" />
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="CatHasPawsTests" />
<InternalsVisibleTo Include="DynamicProxyGenAssembly2" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,66 @@
using CatHasPawsContratcs.Infrastructure;
using CatHasPawsDatabase.Models;
using Microsoft.EntityFrameworkCore;
namespace CatHasPawsDatabase;
internal class CatHasPawsDbContext(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<Buyer>().HasIndex(x => x.PhoneNumber).IsUnique();
modelBuilder.Entity<Manufacturer>().HasIndex(x => x.ManufacturerName).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<Product>()
.HasIndex(x => new { x.ProductName, x.IsDeleted })
.IsUnique()
.HasFilter($"\"{nameof(Product.IsDeleted)}\" = FALSE");
modelBuilder
.Entity<Product>()
.HasOne(e => e.Manufacturer)
.WithMany(e => e.Products)
.OnDelete(DeleteBehavior.Restrict);
modelBuilder.Entity<SaleProduct>().HasKey(x => new { x.SaleId, x.ProductId });
}
public DbSet<Buyer> Buyers { get; set; }
public DbSet<Manufacturer> Manufacturers { get; set; }
public DbSet<Post> Posts { get; set; }
public DbSet<Product> Products { get; set; }
public DbSet<ProductHistory> ProductHistories { get; set; }
public DbSet<Salary> Salaries { get; set; }
public DbSet<Sale> Sales { get; set; }
public DbSet<SaleProduct> SaleProducts { get; set; }
public DbSet<Worker> Workers { get; set; }
}

View File

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

View File

@@ -0,0 +1,156 @@
using AutoMapper;
using CatHasPawsContratcs.DataModels;
using CatHasPawsContratcs.Exceptions;
using CatHasPawsContratcs.StoragesContracts;
using CatHasPawsDatabase.Models;
using Microsoft.EntityFrameworkCore;
using Npgsql;
namespace CatHasPawsDatabase.Implementations;
internal class ManufacturerStorageContract : IManufacturerStorageContract
{
private readonly CatHasPawsDbContext _dbContext;
private readonly Mapper _mapper;
public ManufacturerStorageContract(CatHasPawsDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Manufacturer, ManufacturerDataModel>();
cfg.CreateMap<ManufacturerDataModel, Manufacturer>();
});
_mapper = new Mapper(config);
}
public List<ManufacturerDataModel> GetList()
{
try
{
return [.. _dbContext.Manufacturers.Select(x => _mapper.Map<ManufacturerDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public ManufacturerDataModel? GetElementById(string id)
{
try
{
return _mapper.Map<ManufacturerDataModel>(GetManufacturerById(id));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public ManufacturerDataModel? GetElementByName(string name)
{
try
{
return _mapper.Map<ManufacturerDataModel>(_dbContext.Manufacturers.FirstOrDefault(x => x.ManufacturerName == name));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public ManufacturerDataModel? GetElementByOldName(string name)
{
try
{
return _mapper.Map<ManufacturerDataModel>(_dbContext.Manufacturers.FirstOrDefault(x => x.PrevManufacturerName == name ||
x.PrevPrevManufacturerName == name));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void AddElement(ManufacturerDataModel manufacturerDataModel)
{
try
{
_dbContext.Manufacturers.Add(_mapper.Map<Manufacturer>(manufacturerDataModel));
_dbContext.SaveChanges();
}
catch (InvalidOperationException ex) when (ex.TargetSite?.Name == "ThrowIdentityConflict")
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("Id", manufacturerDataModel.Id);
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Manufacturers_ManufacturerName" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("ManufacturerName", manufacturerDataModel.ManufacturerName);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void UpdElement(ManufacturerDataModel manufacturerDataModel)
{
try
{
var element = GetManufacturerById(manufacturerDataModel.Id) ?? throw new ElementNotFoundException(manufacturerDataModel.Id);
if (element.ManufacturerName != manufacturerDataModel.ManufacturerName)
{
element.PrevPrevManufacturerName = element.PrevManufacturerName;
element.PrevManufacturerName = element.ManufacturerName;
element.ManufacturerName = manufacturerDataModel.ManufacturerName;
}
_dbContext.Manufacturers.Update(element);
_dbContext.SaveChanges();
}
catch (ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Manufacturers_ManufacturerName" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("ManufacturerName", manufacturerDataModel.ManufacturerName);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void DelElement(string id)
{
try
{
var element = GetManufacturerById(id) ?? throw new ElementNotFoundException(id);
_dbContext.Manufacturers.Remove(element);
_dbContext.SaveChanges();
}
catch (ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
private Manufacturer? GetManufacturerById(string id) => _dbContext.Manufacturers.FirstOrDefault(x => x.Id == id);
}

View File

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

View File

@@ -0,0 +1,57 @@
using AutoMapper;
using CatHasPawsContratcs.DataModels;
using CatHasPawsContratcs.Exceptions;
using CatHasPawsContratcs.StoragesContracts;
using CatHasPawsDatabase.Models;
namespace CatHasPawsDatabase.Implementations;
internal class SalaryStorageContract : ISalaryStorageContract
{
private readonly CatHasPawsDbContext _dbContext;
private readonly Mapper _mapper;
public SalaryStorageContract(CatHasPawsDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Salary, SalaryDataModel>();
cfg.CreateMap<SalaryDataModel, Salary>()
.ForMember(dest => dest.WorkerSalary, opt => opt.MapFrom(src => src.Salary));
});
_mapper = new Mapper(config);
}
public List<SalaryDataModel> GetList(DateTime startDate, DateTime endDate, string? workerId = null)
{
try
{
var query = _dbContext.Salaries.Where(x => x.SalaryDate >= startDate && x.SalaryDate <= endDate);
if (workerId is not null)
{
query = query.Where(x => x.WorkerId == workerId);
}
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 CatHasPawsContratcs.DataModels;
using CatHasPawsContratcs.Exceptions;
using CatHasPawsContratcs.StoragesContracts;
using CatHasPawsDatabase.Models;
using Microsoft.EntityFrameworkCore;
namespace CatHasPawsDatabase.Implementations;
internal class SaleStorageContract : ISaleStorageContract
{
private readonly CatHasPawsDbContext _dbContext;
private readonly Mapper _mapper;
public SaleStorageContract(CatHasPawsDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<SaleProduct, SaleProductDataModel>();
cfg.CreateMap<SaleProductDataModel, SaleProduct>();
cfg.CreateMap<Sale, SaleDataModel>();
cfg.CreateMap<SaleDataModel, Sale>()
.ForMember(x => x.IsCancel, x => x.MapFrom(src => false))
.ForMember(x => x.SaleProducts, x => x.MapFrom(src => src.Products));
});
_mapper = new Mapper(config);
}
public List<SaleDataModel> GetList(DateTime? startDate = null, DateTime? endDate = null, string? workerId = null, string? buyerId = null, string? productId = null)
{
try
{
var query = _dbContext.Sales.Include(x => x.SaleProducts).AsQueryable();
if (startDate is not null && endDate is not null)
{
query = query.Where(x => x.SaleDate >= startDate && x.SaleDate < endDate);
}
if (workerId is not null)
{
query = query.Where(x => x.WorkerId == workerId);
}
if (buyerId is not null)
{
query = query.Where(x => x.BuyerId == buyerId);
}
if (productId is not null)
{
query = query.Where(x => x.SaleProducts!.Any(y => y.ProductId == productId));
}
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,141 @@
using AutoMapper;
using CatHasPawsContratcs.DataModels;
using CatHasPawsContratcs.Exceptions;
using CatHasPawsContratcs.StoragesContracts;
using CatHasPawsDatabase.Models;
namespace CatHasPawsDatabase.Implementations;
internal class WorkerStorageContract : IWorkerStorageContract
{
private readonly CatHasPawsDbContext _dbContext;
private readonly Mapper _mapper;
public WorkerStorageContract(CatHasPawsDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Worker, WorkerDataModel>();
cfg.CreateMap<WorkerDataModel, Worker>();
});
_mapper = new Mapper(config);
}
public List<WorkerDataModel> GetList(bool onlyActive = true, string? postId = null, DateTime? fromBirthDate = null, DateTime? toBirthDate = null, DateTime? fromEmploymentDate = null, DateTime? toEmploymentDate = null)
{
try
{
var query = _dbContext.Workers.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<WorkerDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public WorkerDataModel? GetElementById(string id)
{
try
{
return _mapper.Map<WorkerDataModel>(GetWorkerById(id));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public WorkerDataModel? GetElementByFIO(string fio)
{
try
{
return _mapper.Map<WorkerDataModel>(_dbContext.Workers.FirstOrDefault(x => x.FIO == fio));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void AddElement(WorkerDataModel workerDataModel)
{
try
{
_dbContext.Workers.Add(_mapper.Map<Worker>(workerDataModel));
_dbContext.SaveChanges();
}
catch (InvalidOperationException ex) when (ex.TargetSite?.Name == "ThrowIdentityConflict")
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("Id", workerDataModel.Id);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void UpdElement(WorkerDataModel workerDataModel)
{
try
{
var element = GetWorkerById(workerDataModel.Id) ?? throw new ElementNotFoundException(workerDataModel.Id);
_dbContext.Workers.Update(_mapper.Map(workerDataModel, 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 = GetWorkerById(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 Worker? GetWorkerById(string id) => _dbContext.Workers.FirstOrDefault(x => x.Id == id && !x.IsDeleted);
}

View File

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

View File

@@ -0,0 +1,17 @@
using System.ComponentModel.DataAnnotations.Schema;
namespace CatHasPawsDatabase.Models;
internal class Manufacturer
{
public required string Id { get; set; }
public required string ManufacturerName { get; set; }
public string? PrevManufacturerName { get; set; }
public string? PrevPrevManufacturerName { get; set; }
[ForeignKey("ManufacturerId")]
public List<Product>? Products { get; set; }
}

View File

@@ -0,0 +1,20 @@
using CatHasPawsContratcs.Enums;
namespace CatHasPawsDatabase.Models;
internal 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,27 @@
using CatHasPawsContratcs.Enums;
using System.ComponentModel.DataAnnotations.Schema;
namespace CatHasPawsDatabase.Models;
internal class Product
{
public required string Id { get; set; }
public required string ProductName { get; set; }
public ProductType ProductType { get; set; }
public required string ManufacturerId { get; set; }
public double Price { get; set; }
public bool IsDeleted { get; set; }
public Manufacturer? Manufacturer { get; set; }
[ForeignKey("ProductId")]
public List<ProductHistory>? ProductHistories { get; set; }
[ForeignKey("ProductId")]
public List<SaleProduct>? SaleProducts { get; set; }
}

View File

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

View File

@@ -0,0 +1,14 @@
namespace CatHasPawsDatabase.Models;
internal class Salary
{
public string Id { get; set; } = Guid.NewGuid().ToString();
public required string WorkerId { get; set; }
public DateTime SalaryDate { get; set; }
public double WorkerSalary { get; set; }
public Worker? Worker { get; set; }
}

View File

@@ -0,0 +1,30 @@
using CatHasPawsContratcs.Enums;
using System.ComponentModel.DataAnnotations.Schema;
namespace CatHasPawsDatabase.Models;
internal class Sale
{
public string Id { get; set; } = Guid.NewGuid().ToString();
public required string WorkerId { get; set; }
public string? BuyerId { 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 Worker? Worker { get; set; }
public Buyer? Buyer { get; set; }
[ForeignKey("SaleId")]
public List<SaleProduct>? SaleProducts { get; set; }
}

View File

@@ -0,0 +1,14 @@
namespace CatHasPawsDatabase.Models;
internal class SaleProduct
{
public required string SaleId { get; set; }
public required string ProductId { get; set; }
public int Count { get; set; }
public Sale? Sale { get; set; }
public Product? Product { get; set; }
}

View File

@@ -0,0 +1,24 @@
using System.ComponentModel.DataAnnotations.Schema;
namespace CatHasPawsDatabase.Models;
internal class Worker
{
public required string Id { get; set; }
public required string FIO { get; set; }
public required string PostId { get; set; }
public DateTime BirthDate { get; set; }
public DateTime EmploymentDate { get; set; }
public bool IsDeleted { get; set; }
[ForeignKey("WorkerId")]
public List<Salary>? Salaries { get; set; }
[ForeignKey("WorkerId")]
public List<Sale>? Sales { get; set; }
}

View File

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

View File

@@ -0,0 +1,349 @@
using CatHasPawsBusinessLogic.Implementations;
using CatHasPawsContratcs.DataModels;
using CatHasPawsContratcs.Exceptions;
using CatHasPawsContratcs.StoragesContracts;
using Microsoft.Extensions.Logging;
using Moq;
namespace CatHasPawsTests.BusinessLogicsContractsTests;
[TestFixture]
internal class ManufacturerBusinessLogicContractTests
{
private ManufacturerBusinessLogicContract _manufacturerBusinessLogicContract;
private Mock<IManufacturerStorageContract> _manufacturerStorageContract;
[OneTimeSetUp]
public void OneTimeSetUp()
{
_manufacturerStorageContract = new Mock<IManufacturerStorageContract>();
_manufacturerBusinessLogicContract = new ManufacturerBusinessLogicContract(_manufacturerStorageContract.Object, new Mock<ILogger>().Object);
}
[SetUp]
public void SetUp()
{
_manufacturerStorageContract.Reset();
}
[Test]
public void GetAllManufacturers_ReturnListOfRecords_Test()
{
//Arrange
var listOriginal = new List<ManufacturerDataModel>()
{
new(Guid.NewGuid().ToString(), "name 1", null, null),
new(Guid.NewGuid().ToString(), "name 2", null, null),
new(Guid.NewGuid().ToString(), "name 3", null, null),
};
_manufacturerStorageContract.Setup(x => x.GetList()).Returns(listOriginal);
//Act
var list = _manufacturerBusinessLogicContract.GetAllManufacturers();
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.EquivalentTo(listOriginal));
}
[Test]
public void GetAllManufacturers_ReturnEmptyList_Test()
{
//Arrange
_manufacturerStorageContract.Setup(x => x.GetList()).Returns([]);
//Act
var list = _manufacturerBusinessLogicContract.GetAllManufacturers();
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
_manufacturerStorageContract.Verify(x => x.GetList(), Times.Once);
}
[Test]
public void GetAllManufacturers_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _manufacturerBusinessLogicContract.GetAllManufacturers(), Throws.TypeOf<NullListException>());
_manufacturerStorageContract.Verify(x => x.GetList(), Times.Once);
}
[Test]
public void GetAllManufacturers_StorageThrowError_ThrowException_Test()
{
//Arrange
_manufacturerStorageContract.Setup(x => x.GetList()).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _manufacturerBusinessLogicContract.GetAllManufacturers(), Throws.TypeOf<StorageException>());
_manufacturerStorageContract.Verify(x => x.GetList(), Times.Once);
}
[Test]
public void GetManufacturerByData_GetById_ReturnRecord_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
var record = new ManufacturerDataModel(id, "name", null, null);
_manufacturerStorageContract.Setup(x => x.GetElementById(id)).Returns(record);
//Act
var element = _manufacturerBusinessLogicContract.GetManufacturerByData(id);
//Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.Id, Is.EqualTo(id));
_manufacturerStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetManufacturerByData_GetByName_ReturnRecord_Test()
{
//Arrange
var manufacturerName = "name";
var record = new ManufacturerDataModel(Guid.NewGuid().ToString(), manufacturerName, null, null);
_manufacturerStorageContract.Setup(x => x.GetElementByName(manufacturerName)).Returns(record);
//Act
var element = _manufacturerBusinessLogicContract.GetManufacturerByData(manufacturerName);
//Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.ManufacturerName, Is.EqualTo(manufacturerName));
_manufacturerStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetManufacturerByData_GetByOldName_ReturnRecord_Test()
{
//Arrange
var manufacturerOldName = "name before";
var record = new ManufacturerDataModel(Guid.NewGuid().ToString(), "name", manufacturerOldName, null);
_manufacturerStorageContract.Setup(x => x.GetElementByOldName(manufacturerOldName)).Returns(record);
//Act
var element = _manufacturerBusinessLogicContract.GetManufacturerByData(manufacturerOldName);
//Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.PrevManufacturerName, Is.EqualTo(manufacturerOldName));
_manufacturerStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Once);
_manufacturerStorageContract.Verify(x => x.GetElementByOldName(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetManufacturerByData_EmptyData_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _manufacturerBusinessLogicContract.GetManufacturerByData(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _manufacturerBusinessLogicContract.GetManufacturerByData(string.Empty), Throws.TypeOf<ArgumentNullException>());
_manufacturerStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Never);
_manufacturerStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Never);
_manufacturerStorageContract.Verify(x => x.GetElementByOldName(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetManufacturerByData__GetById_NotFoundRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _manufacturerBusinessLogicContract.GetManufacturerByData(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_manufacturerStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
_manufacturerStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Never);
_manufacturerStorageContract.Verify(x => x.GetElementByOldName(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetManufacturerByData_GetByNameOrOldName_NotFoundRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _manufacturerBusinessLogicContract.GetManufacturerByData("name"), Throws.TypeOf<ElementNotFoundException>());
_manufacturerStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Never);
_manufacturerStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Once);
_manufacturerStorageContract.Verify(x => x.GetElementByOldName(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetManufacturerByData_StorageThrowError_ThrowException_Test()
{
//Arrange
_manufacturerStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
_manufacturerStorageContract.Setup(x => x.GetElementByName(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _manufacturerBusinessLogicContract.GetManufacturerByData(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
Assert.That(() => _manufacturerBusinessLogicContract.GetManufacturerByData("name"), Throws.TypeOf<StorageException>());
_manufacturerStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
_manufacturerStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Once);
_manufacturerStorageContract.Verify(x => x.GetElementByOldName(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetManufacturerByData_GetByOldName_StorageThrowError_ThrowException_Test()
{
//Arrange
_manufacturerStorageContract.Setup(x => x.GetElementByOldName(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _manufacturerBusinessLogicContract.GetManufacturerByData("name"), Throws.TypeOf<StorageException>());
_manufacturerStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Once);
_manufacturerStorageContract.Verify(x => x.GetElementByOldName(It.IsAny<string>()), Times.Once);
}
[Test]
public void InsertManufacturer_CorrectRecord_Test()
{
//Arrange
var flag = false;
var record = new ManufacturerDataModel(Guid.NewGuid().ToString(), "name", null, null);
_manufacturerStorageContract.Setup(x => x.AddElement(It.IsAny<ManufacturerDataModel>()))
.Callback((ManufacturerDataModel x) =>
{
flag = x.Id == record.Id && x.ManufacturerName == record.ManufacturerName;
});
//Act
_manufacturerBusinessLogicContract.InsertManufacturer(record);
//Assert
_manufacturerStorageContract.Verify(x => x.AddElement(It.IsAny<ManufacturerDataModel>()), Times.Once);
Assert.That(flag);
}
[Test]
public void InsertManufacturer_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_manufacturerStorageContract.Setup(x => x.AddElement(It.IsAny<ManufacturerDataModel>())).Throws(new ElementExistsException("Data", "Data"));
//Act&Assert
Assert.That(() => _manufacturerBusinessLogicContract.InsertManufacturer(new(Guid.NewGuid().ToString(), "name", null, null)), Throws.TypeOf<ElementExistsException>());
_manufacturerStorageContract.Verify(x => x.AddElement(It.IsAny<ManufacturerDataModel>()), Times.Once);
}
[Test]
public void InsertManufacturer_NullRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _manufacturerBusinessLogicContract.InsertManufacturer(null), Throws.TypeOf<ArgumentNullException>());
_manufacturerStorageContract.Verify(x => x.AddElement(It.IsAny<ManufacturerDataModel>()), Times.Never);
}
[Test]
public void InsertManufacturer_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _manufacturerBusinessLogicContract.InsertManufacturer(new ManufacturerDataModel("id", "name", null, null)), Throws.TypeOf<ValidationException>());
_manufacturerStorageContract.Verify(x => x.AddElement(It.IsAny<ManufacturerDataModel>()), Times.Never);
}
[Test]
public void InsertManufacturer_StorageThrowError_ThrowException_Test()
{
//Arrange
_manufacturerStorageContract.Setup(x => x.AddElement(It.IsAny<ManufacturerDataModel>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _manufacturerBusinessLogicContract.InsertManufacturer(new(Guid.NewGuid().ToString(), "name", null, null)), Throws.TypeOf<StorageException>());
_manufacturerStorageContract.Verify(x => x.AddElement(It.IsAny<ManufacturerDataModel>()), Times.Once);
}
[Test]
public void UpdateManufacturer_CorrectRecord_Test()
{
//Arrange
var flag = false;
var record = new ManufacturerDataModel(Guid.NewGuid().ToString(), "name", null, null);
_manufacturerStorageContract.Setup(x => x.UpdElement(It.IsAny<ManufacturerDataModel>()))
.Callback((ManufacturerDataModel x) =>
{
flag = x.Id == record.Id && x.ManufacturerName == record.ManufacturerName;
});
//Act
_manufacturerBusinessLogicContract.UpdateManufacturer(record);
//Assert
_manufacturerStorageContract.Verify(x => x.UpdElement(It.IsAny<ManufacturerDataModel>()), Times.Once);
Assert.That(flag);
}
[Test]
public void UpdateManufacturer_RecordWithIncorrectData_ThrowException_Test()
{
//Arrange
_manufacturerStorageContract.Setup(x => x.UpdElement(It.IsAny<ManufacturerDataModel>())).Throws(new ElementNotFoundException(""));
//Act&Assert
Assert.That(() => _manufacturerBusinessLogicContract.UpdateManufacturer(new(Guid.NewGuid().ToString(), "name", null, null)), Throws.TypeOf<ElementNotFoundException>());
_manufacturerStorageContract.Verify(x => x.UpdElement(It.IsAny<ManufacturerDataModel>()), Times.Once);
}
[Test]
public void UpdateManufacturer_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_manufacturerStorageContract.Setup(x => x.UpdElement(It.IsAny<ManufacturerDataModel>())).Throws(new ElementExistsException("Data", "Data"));
//Act&Assert
Assert.That(() => _manufacturerBusinessLogicContract.UpdateManufacturer(new(Guid.NewGuid().ToString(), "name", null, null)), Throws.TypeOf<ElementExistsException>());
_manufacturerStorageContract.Verify(x => x.UpdElement(It.IsAny<ManufacturerDataModel>()), Times.Once);
}
[Test]
public void UpdateManufacturer_NullRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _manufacturerBusinessLogicContract.UpdateManufacturer(null), Throws.TypeOf<ArgumentNullException>());
_manufacturerStorageContract.Verify(x => x.UpdElement(It.IsAny<ManufacturerDataModel>()), Times.Never);
}
[Test]
public void UpdateManufacturer_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _manufacturerBusinessLogicContract.UpdateManufacturer(new ManufacturerDataModel("id", "name", null, null)), Throws.TypeOf<ValidationException>());
_manufacturerStorageContract.Verify(x => x.UpdElement(It.IsAny<ManufacturerDataModel>()), Times.Never);
}
[Test]
public void UpdateManufacturer_StorageThrowError_ThrowException_Test()
{
//Arrange
_manufacturerStorageContract.Setup(x => x.UpdElement(It.IsAny<ManufacturerDataModel>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _manufacturerBusinessLogicContract.UpdateManufacturer(new(Guid.NewGuid().ToString(), "name", null, null)), Throws.TypeOf<StorageException>());
_manufacturerStorageContract.Verify(x => x.UpdElement(It.IsAny<ManufacturerDataModel>()), Times.Once);
}
[Test]
public void DeleteManufacturer_CorrectRecord_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
var flag = false;
_manufacturerStorageContract.Setup(x => x.DelElement(It.Is((string x) => x == id))).Callback(() => { flag = true; });
//Act
_manufacturerBusinessLogicContract.DeleteManufacturer(id);
//Assert
_manufacturerStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
Assert.That(flag);
}
[Test]
public void DeleteManufacturer_RecordWithIncorrectId_ThrowException_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
_manufacturerStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new ElementNotFoundException(id));
//Act&Assert
Assert.That(() => _manufacturerBusinessLogicContract.DeleteManufacturer(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_manufacturerStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
}
[Test]
public void DeleteManufacturer_IdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _manufacturerBusinessLogicContract.DeleteManufacturer(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _manufacturerBusinessLogicContract.DeleteManufacturer(string.Empty), Throws.TypeOf<ArgumentNullException>());
_manufacturerStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Never);
}
[Test]
public void DeleteManufacturer_IdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _manufacturerBusinessLogicContract.DeleteManufacturer("id"), Throws.TypeOf<ValidationException>());
_manufacturerStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Never);
}
[Test]
public void DeleteManufacturer_StorageThrowError_ThrowException_Test()
{
//Arrange
_manufacturerStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _manufacturerBusinessLogicContract.DeleteManufacturer(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_manufacturerStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
}
}

View File

@@ -0,0 +1,454 @@
using CatHasPawsBusinessLogic.Implementations;
using CatHasPawsContratcs.DataModels;
using CatHasPawsContratcs.Enums;
using CatHasPawsContratcs.Exceptions;
using CatHasPawsContratcs.StoragesContracts;
using Microsoft.Extensions.Logging;
using Moq;
namespace CatHasPawsTests.BusinessLogicsContractsTests;
[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);
}
[SetUp]
public void SetUp()
{
_postStorageContract.Reset();
}
[Test]
public void GetAllPosts_ReturnListOfRecords_Test()
{
//Arrange
var listOriginal = new List<PostDataModel>()
{
new(Guid.NewGuid().ToString(),"name 1", PostType.Assistant, 10, true, DateTime.UtcNow),
new(Guid.NewGuid().ToString(), "name 2", PostType.Assistant, 10, false, DateTime.UtcNow),
new(Guid.NewGuid().ToString(), "name 3", PostType.Assistant, 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.Assistant, 10, true, DateTime.UtcNow),
new(postId, "name 2", PostType.Assistant, 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.Assistant, 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.Assistant, 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.Supervisor, 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.Supervisor, 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.Supervisor, 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.Supervisor, 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.Supervisor, 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.Supervisor, 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.Supervisor, 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.Supervisor, 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.Supervisor, 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,483 @@
using CatHasPawsBusinessLogic.Implementations;
using CatHasPawsContratcs.DataModels;
using CatHasPawsContratcs.Enums;
using CatHasPawsContratcs.Exceptions;
using CatHasPawsContratcs.StoragesContracts;
using Microsoft.Extensions.Logging;
using Moq;
namespace CatHasPawsTests.BusinessLogicsContractsTests;
[TestFixture]
internal class ProductBusinessLogicContractTests
{
private ProductBusinessLogicContract _productBusinessLogicContract;
private Mock<IProductStorageContract> _productStorageContract;
[OneTimeSetUp]
public void OneTimeSetUp()
{
_productStorageContract = new Mock<IProductStorageContract>();
_productBusinessLogicContract = new ProductBusinessLogicContract(_productStorageContract.Object, new Mock<ILogger>().Object);
}
[SetUp]
public void SetUp()
{
_productStorageContract.Reset();
}
[Test]
public void GetAllProducts_ReturnListOfRecords_Test()
{
//Arrange
var listOriginal = new List<ProductDataModel>()
{
new(Guid.NewGuid().ToString(), "name 1", ProductType.Accessory, Guid.NewGuid().ToString(), 10, false),
new(Guid.NewGuid().ToString(), "name 2", ProductType.Accessory, Guid.NewGuid().ToString(), 10, true),
new(Guid.NewGuid().ToString(), "name 3", ProductType.Accessory, Guid.NewGuid().ToString(), 10, false),
};
_productStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string>())).Returns(listOriginal);
//Act
var listOnlyActive = _productBusinessLogicContract.GetAllProducts(true);
var list = _productBusinessLogicContract.GetAllProducts(false);
//Assert
Assert.Multiple(() =>
{
Assert.That(listOnlyActive, Is.Not.Null);
Assert.That(list, Is.Not.Null);
Assert.That(listOnlyActive, Is.EquivalentTo(listOriginal));
Assert.That(list, Is.EquivalentTo(listOriginal));
});
_productStorageContract.Verify(x => x.GetList(true, null), Times.Once);
_productStorageContract.Verify(x => x.GetList(false, null), Times.Once);
}
[Test]
public void GetAllProducts_ReturnEmptyList_Test()
{
//Arrange
_productStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string>())).Returns([]);
//Act
var listOnlyActive = _productBusinessLogicContract.GetAllProducts(true);
var list = _productBusinessLogicContract.GetAllProducts(false);
//Assert
Assert.Multiple(() =>
{
Assert.That(listOnlyActive, Is.Not.Null);
Assert.That(list, Is.Not.Null);
Assert.That(listOnlyActive, Has.Count.EqualTo(0));
Assert.That(list, Has.Count.EqualTo(0));
});
_productStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), null), Times.Exactly(2));
}
[Test]
public void GetAllProducts_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _productBusinessLogicContract.GetAllProducts(It.IsAny<bool>()), Throws.TypeOf<NullListException>());
_productStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllProducts_StorageThrowError_ThrowException_Test()
{
//Arrange
_productStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _productBusinessLogicContract.GetAllProducts(It.IsAny<bool>()), Throws.TypeOf<StorageException>());
_productStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllProductsByManufacturer_ReturnListOfRecords_Test()
{
//Arrange
var manufacturerId = Guid.NewGuid().ToString();
var listOriginal = new List<ProductDataModel>()
{
new(Guid.NewGuid().ToString(), "name 1",ProductType.Accessory, Guid.NewGuid().ToString(), 10, false),
new(Guid.NewGuid().ToString(), "name 2", ProductType.Accessory, Guid.NewGuid().ToString(), 10, true),
new(Guid.NewGuid().ToString(), "name 3", ProductType.Accessory, Guid.NewGuid().ToString(), 10, false),
};
_productStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string>())).Returns(listOriginal);
//Act
var listOnlyActive = _productBusinessLogicContract.GetAllProductsByManufacturer(manufacturerId, true);
var list = _productBusinessLogicContract.GetAllProductsByManufacturer(manufacturerId, false);
//Assert
Assert.Multiple(() =>
{
Assert.That(listOnlyActive, Is.Not.Null);
Assert.That(list, Is.Not.Null);
Assert.That(listOnlyActive, Is.EquivalentTo(listOriginal));
Assert.That(list, Is.EquivalentTo(listOriginal));
});
_productStorageContract.Verify(x => x.GetList(true, manufacturerId), Times.Once);
_productStorageContract.Verify(x => x.GetList(false, manufacturerId), Times.Once);
}
[Test]
public void GetAllProductsByManufacturer_ReturnEmptyList_Test()
{
//Arrange
var manufacturerId = Guid.NewGuid().ToString();
_productStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string>())).Returns([]);
//Act
var listOnlyActive = _productBusinessLogicContract.GetAllProductsByManufacturer(manufacturerId, true);
var list = _productBusinessLogicContract.GetAllProductsByManufacturer(manufacturerId, false);
//Assert
Assert.Multiple(() =>
{
Assert.That(listOnlyActive, Is.Not.Null);
Assert.That(list, Is.Not.Null);
Assert.That(listOnlyActive, Has.Count.EqualTo(0));
Assert.That(list, Has.Count.EqualTo(0));
});
_productStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), manufacturerId), Times.Exactly(2));
}
[Test]
public void GetAllProductsByManufacturer_ManufacturerIdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _productBusinessLogicContract.GetAllProductsByManufacturer(null, It.IsAny<bool>()), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _productBusinessLogicContract.GetAllProductsByManufacturer(string.Empty, It.IsAny<bool>()), Throws.TypeOf<ArgumentNullException>());
_productStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllProductsByManufacturer_ManufacturerIdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _productBusinessLogicContract.GetAllProductsByManufacturer("manufacturerId", It.IsAny<bool>()), Throws.TypeOf<ValidationException>());
_productStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllProductsByManufacturer_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _productBusinessLogicContract.GetAllProductsByManufacturer(Guid.NewGuid().ToString(), It.IsAny<bool>()), Throws.TypeOf<NullListException>());
_productStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllProductsByManufacturer_StorageThrowError_ThrowException_Test()
{
//Arrange
_productStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _productBusinessLogicContract.GetAllProductsByManufacturer(Guid.NewGuid().ToString(), It.IsAny<bool>()), Throws.TypeOf<StorageException>());
_productStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetProductHistoryByProduct_ReturnListOfRecords_Test()
{
//Arrange
var productId = Guid.NewGuid().ToString();
var listOriginal = new List<ProductHistoryDataModel>()
{
new(Guid.NewGuid().ToString(), 10),
new(Guid.NewGuid().ToString(), 15),
new(Guid.NewGuid().ToString(), 10),
};
_productStorageContract.Setup(x => x.GetHistoryByProductId(It.IsAny<string>())).Returns(listOriginal);
//Act
var list = _productBusinessLogicContract.GetProductHistoryByProduct(productId);
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.EquivalentTo(listOriginal));
_productStorageContract.Verify(x => x.GetHistoryByProductId(productId), Times.Once);
}
[Test]
public void GetProductHistoryByProduct_ReturnEmptyList_Test()
{
//Arrange
_productStorageContract.Setup(x => x.GetHistoryByProductId(It.IsAny<string>())).Returns([]);
//Act
var list = _productBusinessLogicContract.GetProductHistoryByProduct(Guid.NewGuid().ToString());
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
_productStorageContract.Verify(x => x.GetHistoryByProductId(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetProductHistoryByProduct_ProductIdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _productBusinessLogicContract.GetProductHistoryByProduct(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _productBusinessLogicContract.GetProductHistoryByProduct(string.Empty), Throws.TypeOf<ArgumentNullException>());
_productStorageContract.Verify(x => x.GetHistoryByProductId(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetProductHistoryByProduct_ProductIdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _productBusinessLogicContract.GetProductHistoryByProduct("productId"), Throws.TypeOf<ValidationException>());
_productStorageContract.Verify(x => x.GetHistoryByProductId(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetProductHistoryByProduct_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _productBusinessLogicContract.GetProductHistoryByProduct(Guid.NewGuid().ToString()), Throws.TypeOf<NullListException>());
_productStorageContract.Verify(x => x.GetHistoryByProductId(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetProductHistoryByProduct_StorageThrowError_ThrowException_Test()
{
//Arrange
_productStorageContract.Setup(x => x.GetHistoryByProductId(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _productBusinessLogicContract.GetProductHistoryByProduct(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_productStorageContract.Verify(x => x.GetHistoryByProductId(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetProductByData_GetById_ReturnRecord_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
var record = new ProductDataModel(id, "name", ProductType.Accessory, Guid.NewGuid().ToString(), 10, false);
_productStorageContract.Setup(x => x.GetElementById(id)).Returns(record);
//Act
var element = _productBusinessLogicContract.GetProductByData(id);
//Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.Id, Is.EqualTo(id));
_productStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetProductByData_GetByName_ReturnRecord_Test()
{
//Arrange
var name = "name";
var record = new ProductDataModel(Guid.NewGuid().ToString(), name, ProductType.Accessory, Guid.NewGuid().ToString(), 10, false);
_productStorageContract.Setup(x => x.GetElementByName(name)).Returns(record);
//Act
var element = _productBusinessLogicContract.GetProductByData(name);
//Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.ProductName, Is.EqualTo(name));
_productStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetProductByData_EmptyData_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _productBusinessLogicContract.GetProductByData(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _productBusinessLogicContract.GetProductByData(string.Empty), Throws.TypeOf<ArgumentNullException>());
_productStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Never);
_productStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetProductByData_GetById_NotFoundRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _productBusinessLogicContract.GetProductByData(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_productStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetProductByData_GetByName_NotFoundRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _productBusinessLogicContract.GetProductByData("name"), Throws.TypeOf<ElementNotFoundException>());
_productStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetProductByData_StorageThrowError_ThrowException_Test()
{
//Arrange
_productStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
_productStorageContract.Setup(x => x.GetElementByName(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _productBusinessLogicContract.GetProductByData(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
Assert.That(() => _productBusinessLogicContract.GetProductByData("name"), Throws.TypeOf<StorageException>());
_productStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
_productStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Once);
}
[Test]
public void InsertProduct_CorrectRecord_Test()
{
//Arrange
var flag = false;
var record = new ProductDataModel(Guid.NewGuid().ToString(), "name", ProductType.Accessory, Guid.NewGuid().ToString(), 10, false);
_productStorageContract.Setup(x => x.AddElement(It.IsAny<ProductDataModel>()))
.Callback((ProductDataModel x) =>
{
flag = x.Id == record.Id && x.ProductName == record.ProductName && x.ProductType == record.ProductType &&
x.ManufacturerId == record.ManufacturerId && x.Price == record.Price && x.IsDeleted == record.IsDeleted;
});
//Act
_productBusinessLogicContract.InsertProduct(record);
//Assert
_productStorageContract.Verify(x => x.AddElement(It.IsAny<ProductDataModel>()), Times.Once);
Assert.That(flag);
}
[Test]
public void InsertProduct_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_productStorageContract.Setup(x => x.AddElement(It.IsAny<ProductDataModel>())).Throws(new ElementExistsException("Data", "Data"));
//Act&Assert
Assert.That(() => _productBusinessLogicContract.InsertProduct(new(Guid.NewGuid().ToString(), "name", ProductType.Accessory, Guid.NewGuid().ToString(), 10, false)), Throws.TypeOf<ElementExistsException>());
_productStorageContract.Verify(x => x.AddElement(It.IsAny<ProductDataModel>()), Times.Once);
}
[Test]
public void InsertProduct_NullRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _productBusinessLogicContract.InsertProduct(null), Throws.TypeOf<ArgumentNullException>());
_productStorageContract.Verify(x => x.AddElement(It.IsAny<ProductDataModel>()), Times.Never);
}
[Test]
public void InsertProduct_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _productBusinessLogicContract.InsertProduct(new ProductDataModel("id", "name", ProductType.Accessory, Guid.NewGuid().ToString(), 10, false)), Throws.TypeOf<ValidationException>());
_productStorageContract.Verify(x => x.AddElement(It.IsAny<ProductDataModel>()), Times.Never);
}
[Test]
public void InsertProduct_StorageThrowError_ThrowException_Test()
{
//Arrange
_productStorageContract.Setup(x => x.AddElement(It.IsAny<ProductDataModel>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _productBusinessLogicContract.InsertProduct(new(Guid.NewGuid().ToString(), "name", ProductType.Accessory, Guid.NewGuid().ToString(), 10, false)), Throws.TypeOf<StorageException>());
_productStorageContract.Verify(x => x.AddElement(It.IsAny<ProductDataModel>()), Times.Once);
}
[Test]
public void UpdateProduct_CorrectRecord_Test()
{
//Arrange
var flag = false;
var record = new ProductDataModel(Guid.NewGuid().ToString(), "name", ProductType.Accessory, Guid.NewGuid().ToString(), 10, false);
_productStorageContract.Setup(x => x.UpdElement(It.IsAny<ProductDataModel>()))
.Callback((ProductDataModel x) =>
{
flag = x.Id == record.Id && x.ProductName == record.ProductName && x.ProductType == record.ProductType &&
x.ManufacturerId == record.ManufacturerId && x.Price == record.Price && x.IsDeleted == record.IsDeleted;
});
//Act
_productBusinessLogicContract.UpdateProduct(record);
//Assert
_productStorageContract.Verify(x => x.UpdElement(It.IsAny<ProductDataModel>()), Times.Once);
Assert.That(flag);
}
[Test]
public void UpdateProduct_RecordWithIncorrectData_ThrowException_Test()
{
//Arrange
_productStorageContract.Setup(x => x.UpdElement(It.IsAny<ProductDataModel>())).Throws(new ElementNotFoundException(""));
//Act&Assert
Assert.That(() => _productBusinessLogicContract.UpdateProduct(new(Guid.NewGuid().ToString(), "name", ProductType.Accessory, Guid.NewGuid().ToString(), 10, false)), Throws.TypeOf<ElementNotFoundException>());
_productStorageContract.Verify(x => x.UpdElement(It.IsAny<ProductDataModel>()), Times.Once);
}
[Test]
public void UpdateProduct_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_productStorageContract.Setup(x => x.UpdElement(It.IsAny<ProductDataModel>())).Throws(new ElementExistsException("Data", "Data"));
//Act&Assert
Assert.That(() => _productBusinessLogicContract.UpdateProduct(new(Guid.NewGuid().ToString(), "anme", ProductType.Accessory, Guid.NewGuid().ToString(), 10, false)), Throws.TypeOf<ElementExistsException>());
_productStorageContract.Verify(x => x.UpdElement(It.IsAny<ProductDataModel>()), Times.Once);
}
[Test]
public void UpdateProduct_NullRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _productBusinessLogicContract.UpdateProduct(null), Throws.TypeOf<ArgumentNullException>());
_productStorageContract.Verify(x => x.UpdElement(It.IsAny<ProductDataModel>()), Times.Never);
}
[Test]
public void UpdateProduct_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _productBusinessLogicContract.UpdateProduct(new ProductDataModel("id", "name", ProductType.Accessory, Guid.NewGuid().ToString(), 10, false)), Throws.TypeOf<ValidationException>());
_productStorageContract.Verify(x => x.UpdElement(It.IsAny<ProductDataModel>()), Times.Never);
}
[Test]
public void UpdateProduct_StorageThrowError_ThrowException_Test()
{
//Arrange
_productStorageContract.Setup(x => x.UpdElement(It.IsAny<ProductDataModel>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _productBusinessLogicContract.UpdateProduct(new(Guid.NewGuid().ToString(), "name", ProductType.Accessory, Guid.NewGuid().ToString(), 10, false)), Throws.TypeOf<StorageException>());
_productStorageContract.Verify(x => x.UpdElement(It.IsAny<ProductDataModel>()), Times.Once);
}
[Test]
public void DeleteProduct_CorrectRecord_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
var flag = false;
_productStorageContract.Setup(x => x.DelElement(It.Is((string x) => x == id))).Callback(() => { flag = true; });
//Act
_productBusinessLogicContract.DeleteProduct(id);
//Assert
_productStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
Assert.That(flag);
}
[Test]
public void DeleteProduct_RecordWithIncorrectId_ThrowException_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
_productStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new ElementNotFoundException(id));
//Act&Assert
Assert.That(() => _productBusinessLogicContract.DeleteProduct(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_productStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
}
[Test]
public void DeleteProduct_IdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _productBusinessLogicContract.DeleteProduct(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _productBusinessLogicContract.DeleteProduct(string.Empty), Throws.TypeOf<ArgumentNullException>());
_productStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Never);
}
[Test]
public void DeleteProduct_IdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _productBusinessLogicContract.DeleteProduct("id"), Throws.TypeOf<ValidationException>());
_productStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Never);
}
[Test]
public void DeleteProduct_StorageThrowError_ThrowException_Test()
{
//Arrange
_productStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _productBusinessLogicContract.DeleteProduct(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_productStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
}
}

View File

@@ -0,0 +1,346 @@
using CatHasPawsBusinessLogic.Implementations;
using CatHasPawsContratcs.DataModels;
using CatHasPawsContratcs.Enums;
using CatHasPawsContratcs.Exceptions;
using CatHasPawsContratcs.StoragesContracts;
using Microsoft.Extensions.Logging;
using Moq;
namespace CatHasPawsTests.BusinessLogicsContractsTests;
[TestFixture]
internal class SalaryBusinessLogicContractTests
{
private SalaryBusinessLogicContract _salaryBusinessLogicContract;
private Mock<ISalaryStorageContract> _salaryStorageContract;
private Mock<ISaleStorageContract> _saleStorageContract;
private Mock<IPostStorageContract> _postStorageContract;
private Mock<IWorkerStorageContract> _workerStorageContract;
[OneTimeSetUp]
public void OneTimeSetUp()
{
_salaryStorageContract = new Mock<ISalaryStorageContract>();
_saleStorageContract = new Mock<ISaleStorageContract>();
_postStorageContract = new Mock<IPostStorageContract>();
_workerStorageContract = new Mock<IWorkerStorageContract>();
_salaryBusinessLogicContract = new SalaryBusinessLogicContract(_salaryStorageContract.Object,
_saleStorageContract.Object, _postStorageContract.Object, _workerStorageContract.Object, new Mock<ILogger>().Object);
}
[SetUp]
public void SetUp()
{
_salaryStorageContract.Reset();
_saleStorageContract.Reset();
_postStorageContract.Reset();
_workerStorageContract.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 GetAllSalariesByWorker_ReturnListOfRecords_Test()
{
//Arrange
var startDate = DateTime.UtcNow;
var endDate = DateTime.UtcNow.AddDays(1);
var workerId = 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.GetAllSalariesByPeriodByWorker(startDate, endDate, workerId);
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.EquivalentTo(listOriginal));
_salaryStorageContract.Verify(x => x.GetList(startDate, endDate, workerId), Times.Once);
}
[Test]
public void GetAllSalariesByWorker_ReturnEmptyList_Test()
{
//Arrange
_salaryStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>())).Returns([]);
//Act
var list = _salaryBusinessLogicContract.GetAllSalariesByPeriodByWorker(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 GetAllSalariesByWorker_IncorrectDates_ThrowException_Test()
{
//Arrange
var dateTime = DateTime.UtcNow;
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.GetAllSalariesByPeriodByWorker(dateTime, dateTime, Guid.NewGuid().ToString()), Throws.TypeOf<IncorrectDatesException>());
Assert.That(() => _salaryBusinessLogicContract.GetAllSalariesByPeriodByWorker(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 GetAllSalariesByWorker_WorkerIdIsNUllOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.GetAllSalariesByPeriodByWorker(DateTime.UtcNow, DateTime.UtcNow.AddDays(1), null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _salaryBusinessLogicContract.GetAllSalariesByPeriodByWorker(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 GetAllSalariesByWorker_WorkerIdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.GetAllSalariesByPeriodByWorker(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 GetAllSalariesByWorker_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.GetAllSalariesByPeriodByWorker(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 GetAllSalariesByWorker_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.GetAllSalariesByPeriodByWorker(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 workerId = 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(), workerId, null, saleSum, DiscountType.None, 0, false, [])]);
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Assistant, postSalary, true, DateTime.UtcNow));
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Returns([new WorkerDataModel(workerId, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)]);
var sum = 0.0;
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 worker1Id = Guid.NewGuid().ToString();
var worker2Id = Guid.NewGuid().ToString();
var worker3Id = Guid.NewGuid().ToString();
var list = new List<WorkerDataModel>() {
new(worker1Id, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false),
new(worker2Id, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false),
new(worker3Id, "Test", 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(), worker1Id, null, 1, DiscountType.None, 0, false, []),
new SaleDataModel(Guid.NewGuid().ToString(), worker1Id, null, 1, DiscountType.None, 0, false, []),
new SaleDataModel(Guid.NewGuid().ToString(), worker2Id, null, 1, DiscountType.None, 0, false, []),
new SaleDataModel(Guid.NewGuid().ToString(), worker3Id, null, 1, DiscountType.None, 0, false, []),
new SaleDataModel(Guid.NewGuid().ToString(), worker3Id, null, 1, DiscountType.None, 0, false, [])]);
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Assistant, 2000, true, DateTime.UtcNow));
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Returns(list);
//Act
_salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow);
//Assert
_salaryStorageContract.Verify(x => x.AddElement(It.IsAny<SalaryDataModel>()), Times.Exactly(list.Count));
}
[Test]
public void CalculateSalaryByMounth_WithoitSalesByWorker_Test()
{
//Arrange
var postSalary = 2000.0;
var workerId = 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.Assistant, postSalary, true, DateTime.UtcNow));
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Returns([new WorkerDataModel(workerId, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)]);
var sum = 0.0;
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 workerId = Guid.NewGuid().ToString();
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Assistant, 2000, true, DateTime.UtcNow));
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Returns([new WorkerDataModel(workerId, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)]);
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow), Throws.TypeOf<NullListException>());
}
[Test]
public void CalculateSalaryByMounth_PostStorageReturnNull_ThrowException_Test()
{
//Arrange
var workerId = 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(), workerId, null, 200, DiscountType.None, 0, false, [])]);
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Returns([new WorkerDataModel(workerId, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)]);
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow), Throws.TypeOf<NullListException>());
}
[Test]
public void CalculateSalaryByMounth_WorkerStorageReturnNull_ThrowException_Test()
{
//Arrange
var workerId = 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(), workerId, null, 200, DiscountType.None, 0, false, [])]);
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Assistant, 2000, true, DateTime.UtcNow));
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow), Throws.TypeOf<NullListException>());
}
[Test]
public void CalculateSalaryByMounth_SaleStorageThrowException_ThrowException_Test()
{
//Arrange
var workerId = 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.Assistant, 2000, true, DateTime.UtcNow));
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Returns([new WorkerDataModel(workerId, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)]);
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow), Throws.TypeOf<StorageException>());
}
[Test]
public void CalculateSalaryByMounth_PostStorageThrowException_ThrowException_Test()
{
//Arrange
var workerId = 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(), workerId, null, 200, DiscountType.None, 0, false, [])]);
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Throws(new StorageException(new InvalidOperationException()));
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Returns([new WorkerDataModel(workerId, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)]);
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow), Throws.TypeOf<StorageException>());
}
[Test]
public void CalculateSalaryByMounth_WorkerStorageThrowException_ThrowException_Test()
{
//Arrange
var workerId = 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(), workerId, null, 200, DiscountType.None, 0, false, [])]);
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Assistant, 2000, true, DateTime.UtcNow));
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow), Throws.TypeOf<StorageException>());
}
}

View File

@@ -0,0 +1,500 @@
using CatHasPawsBusinessLogic.Implementations;
using CatHasPawsContratcs.DataModels;
using CatHasPawsContratcs.Enums;
using CatHasPawsContratcs.Exceptions;
using CatHasPawsContratcs.StoragesContracts;
using Microsoft.Extensions.Logging;
using Moq;
namespace CatHasPawsTests.BusinessLogicsContractsTests;
[TestFixture]
internal class SaleBusinessLogicContractTests
{
private SaleBusinessLogicContract _saleBusinessLogicContract;
private Mock<ISaleStorageContract> _saleStorageContract;
[OneTimeSetUp]
public void OneTimeSetUp()
{
_saleStorageContract = new Mock<ISaleStorageContract>();
_saleBusinessLogicContract = new SaleBusinessLogicContract(_saleStorageContract.Object, new Mock<ILogger>().Object);
}
[SetUp]
public void SetUp()
{
_saleStorageContract.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 SaleProductDataModel(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 GetAllSalesByWorkerByPeriod_ReturnListOfRecords_Test()
{
//Arrange
var date = DateTime.UtcNow;
var workerId = Guid.NewGuid().ToString();
var listOriginal = new List<SaleDataModel>()
{
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, DiscountType.None, 0, false,
[new SaleProductDataModel(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.GetAllSalesByWorkerByPeriod(workerId, 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), workerId, null, null), Times.Once);
}
[Test]
public void GetAllSalesByWorkerByPeriod_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.GetAllSalesByWorkerByPeriod(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 GetAllSalesByWorkerByPeriod_IncorrectDates_ThrowException_Test()
{
//Arrange
var date = DateTime.UtcNow;
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByWorkerByPeriod(Guid.NewGuid().ToString(), date, date), Throws.TypeOf<IncorrectDatesException>());
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByWorkerByPeriod(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 GetAllSalesByWorkerByPeriod_WorkerIdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByWorkerByPeriod(null, DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByWorkerByPeriod(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 GetAllSalesByWorkerByPeriod_WorkerIdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByWorkerByPeriod("workerId", 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 GetAllSalesByWorkerByPeriod_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByWorkerByPeriod(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 GetAllSalesByWorkerByPeriod_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.GetAllSalesByWorkerByPeriod(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 GetAllSalesByBuyerByPeriod_ReturnListOfRecords_Test()
{
//Arrange
var date = DateTime.UtcNow;
var buyerId = Guid.NewGuid().ToString();
var listOriginal = new List<SaleDataModel>()
{
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, DiscountType.None, 0, false,
[new SaleProductDataModel(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.GetAllSalesByBuyerByPeriod(buyerId, 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, buyerId, null), Times.Once);
}
[Test]
public void GetAllSalesByBuyerByPeriod_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.GetAllSalesByBuyerByPeriod(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 GetAllSalesByBuyerByPeriod_IncorrectDates_ThrowException_Test()
{
//Arrange
var date = DateTime.UtcNow;
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByBuyerByPeriod(Guid.NewGuid().ToString(), date, date), Throws.TypeOf<IncorrectDatesException>());
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByBuyerByPeriod(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 GetAllSalesByBuyerByPeriod_BuyerIdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByBuyerByPeriod(null, DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByBuyerByPeriod(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 GetAllSalesByBuyerByPeriod_BuyerIdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByBuyerByPeriod("buyerId", 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 GetAllSalesByBuyerByPeriod_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByBuyerByPeriod(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 GetAllSalesByBuyerByPeriod_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.GetAllSalesByBuyerByPeriod(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 GetAllSalesByProductByPeriod_ReturnListOfRecords_Test()
{
//Arrange
var date = DateTime.UtcNow;
var productId = Guid.NewGuid().ToString();
var listOriginal = new List<SaleDataModel>()
{
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, DiscountType.None, 0, false,
[new SaleProductDataModel(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.GetAllSalesByProductByPeriod(productId, 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, productId), Times.Once);
}
[Test]
public void GetAllSalesByProductByPeriod_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.GetAllSalesByProductByPeriod(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 GetAllSalesByProductByPeriod_IncorrectDates_ThrowException_Test()
{
//Arrange
var date = DateTime.UtcNow;
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByProductByPeriod(Guid.NewGuid().ToString(), date, date), Throws.TypeOf<IncorrectDatesException>());
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByProductByPeriod(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 GetAllSalesByProductByPeriod_ProductIdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByProductByPeriod(null, DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByProductByPeriod(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 GetAllSalesByProductByPeriod_ProductIdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByProductByPeriod("productId", 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 GetAllSalesByProductByPeriod_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByProductByPeriod(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 GetAllSalesByProductByPeriod_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.GetAllSalesByProductByPeriod(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 SaleProductDataModel(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 SaleProductDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]);
_saleStorageContract.Setup(x => x.AddElement(It.IsAny<SaleDataModel>()))
.Callback((SaleDataModel x) =>
{
flag = x.Id == record.Id && x.WorkerId == record.WorkerId && x.BuyerId == record.BuyerId &&
x.SaleDate == record.SaleDate && x.Sum == record.Sum && x.DiscountType == record.DiscountType &&
x.Discount == record.Discount && x.IsCancel == record.IsCancel && x.Products.Count == record.Products.Count &&
x.Products.First().ProductId == record.Products.First().ProductId &&
x.Products.First().SaleId == record.Products.First().SaleId &&
x.Products.First().Count == record.Products.First().Count;
});
//Act
_saleBusinessLogicContract.InsertSale(record);
//Assert
_saleStorageContract.Verify(x => x.AddElement(It.IsAny<SaleDataModel>()), Times.Once);
Assert.That(flag);
}
[Test]
public void InsertSale_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_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 SaleProductDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<ElementExistsException>());
_saleStorageContract.Verify(x => x.AddElement(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
_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 SaleProductDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<StorageException>());
_saleStorageContract.Verify(x => x.AddElement(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,557 @@
using CatHasPawsBusinessLogic.Implementations;
using CatHasPawsContratcs.DataModels;
using CatHasPawsContratcs.Exceptions;
using CatHasPawsContratcs.StoragesContracts;
using Microsoft.Extensions.Logging;
using Moq;
namespace CatHasPawsTests.BusinessLogicsContractsTests;
[TestFixture]
internal class WorkerBusinessLogicContractTests
{
private WorkerBusinessLogicContract _workerBusinessLogicContract;
private Mock<IWorkerStorageContract> _workerStorageContract;
[OneTimeSetUp]
public void OneTimeSetUp()
{
_workerStorageContract = new Mock<IWorkerStorageContract>();
_workerBusinessLogicContract = new WorkerBusinessLogicContract(_workerStorageContract.Object, new Mock<ILogger>().Object);
}
[SetUp]
public void SetUp()
{
_workerStorageContract.Reset();
}
[Test]
public void GetAllWorkers_ReturnListOfRecords_Test()
{
//Arrange
var listOriginal = new List<WorkerDataModel>()
{
new(Guid.NewGuid().ToString(), "fio 1", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false),
new(Guid.NewGuid().ToString(), "fio 2", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, true),
new(Guid.NewGuid().ToString(), "fio 3", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false),
};
_workerStorageContract.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 = _workerBusinessLogicContract.GetAllWorkers(true);
var list = _workerBusinessLogicContract.GetAllWorkers(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));
});
_workerStorageContract.Verify(x => x.GetList(true, null, null, null, null, null), Times.Once);
_workerStorageContract.Verify(x => x.GetList(false, null, null, null, null, null), Times.Once);
}
[Test]
public void GetAllWorkers_ReturnEmptyList_Test()
{
//Arrange
_workerStorageContract.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 = _workerBusinessLogicContract.GetAllWorkers(true);
var list = _workerBusinessLogicContract.GetAllWorkers(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));
});
_workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), null, null, null, null, null), Times.Exactly(2));
}
[Test]
public void GetAllWorkers_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.GetAllWorkers(It.IsAny<bool>()), Throws.TypeOf<NullListException>());
_workerStorageContract.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 GetAllWorkers_StorageThrowError_ThrowException_Test()
{
//Arrange
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.GetAllWorkers(It.IsAny<bool>()), Throws.TypeOf<StorageException>());
_workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), null, null, null, null, null), Times.Once);
}
[Test]
public void GetAllWorkersByPost_ReturnListOfRecords_Test()
{
//Arrange
var postId = Guid.NewGuid().ToString();
var listOriginal = new List<WorkerDataModel>()
{
new(Guid.NewGuid().ToString(), "fio 1", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false),
new(Guid.NewGuid().ToString(), "fio 2", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, true),
new(Guid.NewGuid().ToString(), "fio 3", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false),
};
_workerStorageContract.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 = _workerBusinessLogicContract.GetAllWorkersByPost(postId, true);
var list = _workerBusinessLogicContract.GetAllWorkersByPost(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));
});
_workerStorageContract.Verify(x => x.GetList(true, postId, null, null, null, null), Times.Once);
_workerStorageContract.Verify(x => x.GetList(false, postId, null, null, null, null), Times.Once);
}
[Test]
public void GetAllWorkersByPost_ReturnEmptyList_Test()
{
//Arrange
_workerStorageContract.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 = _workerBusinessLogicContract.GetAllWorkersByPost(Guid.NewGuid().ToString(), true);
var list = _workerBusinessLogicContract.GetAllWorkersByPost(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));
});
_workerStorageContract.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 GetAllWorkersByPost_PostIdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.GetAllWorkersByPost(null, It.IsAny<bool>()), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _workerBusinessLogicContract.GetAllWorkersByPost(string.Empty, It.IsAny<bool>()), Throws.TypeOf<ArgumentNullException>());
_workerStorageContract.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 GetAllWorkersByPost_PostIdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.GetAllWorkersByPost("postId", It.IsAny<bool>()), Throws.TypeOf<ValidationException>());
_workerStorageContract.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 GetAllWorkersByPost_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.GetAllWorkersByPost(Guid.NewGuid().ToString(), It.IsAny<bool>()), Throws.TypeOf<NullListException>());
_workerStorageContract.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 GetAllWorkersByPost_StorageThrowError_ThrowException_Test()
{
//Arrange
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.GetAllWorkersByPost(Guid.NewGuid().ToString(), It.IsAny<bool>()), Throws.TypeOf<StorageException>());
_workerStorageContract.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 GetAllWorkersByBirthDate_ReturnListOfRecords_Test()
{
//Arrange
var date = DateTime.UtcNow;
var listOriginal = new List<WorkerDataModel>()
{
new(Guid.NewGuid().ToString(), "fio 1", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false),
new(Guid.NewGuid().ToString(), "fio 2", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, true),
new(Guid.NewGuid().ToString(), "fio 3", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false),
};
_workerStorageContract.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 = _workerBusinessLogicContract.GetAllWorkersByBirthDate(date, date.AddDays(1), true);
var list = _workerBusinessLogicContract.GetAllWorkersByBirthDate(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));
});
_workerStorageContract.Verify(x => x.GetList(true, null, date, date.AddDays(1), null, null), Times.Once);
_workerStorageContract.Verify(x => x.GetList(false, null, date, date.AddDays(1), null, null), Times.Once);
}
[Test]
public void GetAllWorkersByBirthDate_ReturnEmptyList_Test()
{
//Arrange
_workerStorageContract.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 = _workerBusinessLogicContract.GetAllWorkersByBirthDate(DateTime.UtcNow, DateTime.UtcNow.AddDays(1), true);
var list = _workerBusinessLogicContract.GetAllWorkers(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));
});
_workerStorageContract.Verify(x => x.GetList(true, null, It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), null, null), Times.Once);
_workerStorageContract.Verify(x => x.GetList(false, null, It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), null, null), Times.Once);
}
[Test]
public void GetAllWorkersByBirthDate_IncorrectDates_ThrowException_Test()
{
//Arrange
var date = DateTime.UtcNow;
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.GetAllWorkersByBirthDate(date, date, It.IsAny<bool>()), Throws.TypeOf<IncorrectDatesException>());
Assert.That(() => _workerBusinessLogicContract.GetAllWorkersByBirthDate(date, date.AddSeconds(-1), It.IsAny<bool>()), Throws.TypeOf<IncorrectDatesException>());
_workerStorageContract.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 GetAllWorkersByBirthDate_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.GetAllWorkersByBirthDate(DateTime.UtcNow, DateTime.UtcNow.AddDays(1), It.IsAny<bool>()), Throws.TypeOf<NullListException>());
_workerStorageContract.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 GetAllWorkersByBirthDate_StorageThrowError_ThrowException_Test()
{
//Arrange
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.GetAllWorkersByBirthDate(DateTime.UtcNow, DateTime.UtcNow.AddDays(1), It.IsAny<bool>()), Throws.TypeOf<StorageException>());
_workerStorageContract.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 GetAllWorkersByEmploymentDate_ReturnListOfRecords_Test()
{
//Arrange
var date = DateTime.UtcNow;
var listOriginal = new List<WorkerDataModel>()
{
new(Guid.NewGuid().ToString(), "fio 1", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false),
new(Guid.NewGuid().ToString(), "fio 2", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, true),
new(Guid.NewGuid().ToString(), "fio 3", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false),
};
_workerStorageContract.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 = _workerBusinessLogicContract.GetAllWorkersByEmploymentDate(date, date.AddDays(1), true);
var list = _workerBusinessLogicContract.GetAllWorkersByEmploymentDate(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));
});
_workerStorageContract.Verify(x => x.GetList(true, null, null, null, date, date.AddDays(1)), Times.Once);
_workerStorageContract.Verify(x => x.GetList(false, null, null, null, date, date.AddDays(1)), Times.Once);
}
[Test]
public void GetAllWorkersByEmploymentDate_ReturnEmptyList_Test()
{
//Arrange
_workerStorageContract.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 = _workerBusinessLogicContract.GetAllWorkersByEmploymentDate(DateTime.UtcNow, DateTime.UtcNow.AddDays(1), true);
var list = _workerBusinessLogicContract.GetAllWorkersByEmploymentDate(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));
});
_workerStorageContract.Verify(x => x.GetList(true, null, null, null, It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Once);
_workerStorageContract.Verify(x => x.GetList(false, null, null, null, It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Once);
}
[Test]
public void GetAllWorkersByEmploymentDate_IncorrectDates_ThrowException_Test()
{
//Arrange
var date = DateTime.UtcNow;
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.GetAllWorkersByEmploymentDate(date, date, It.IsAny<bool>()), Throws.TypeOf<IncorrectDatesException>());
Assert.That(() => _workerBusinessLogicContract.GetAllWorkersByEmploymentDate(date, date.AddSeconds(-1), It.IsAny<bool>()), Throws.TypeOf<IncorrectDatesException>());
_workerStorageContract.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 GetAllWorkersByEmploymentDate_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.GetAllWorkersByEmploymentDate(DateTime.UtcNow, DateTime.UtcNow.AddDays(1), It.IsAny<bool>()), Throws.TypeOf<NullListException>());
_workerStorageContract.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 GetAllWorkersByEmploymentDate_StorageThrowError_ThrowException_Test()
{
//Arrange
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.GetAllWorkersByEmploymentDate(DateTime.UtcNow, DateTime.UtcNow.AddDays(1), It.IsAny<bool>()), Throws.TypeOf<StorageException>());
_workerStorageContract.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 GetWorkerByData_GetById_ReturnRecord_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
var record = new WorkerDataModel(id, "fio", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false);
_workerStorageContract.Setup(x => x.GetElementById(id)).Returns(record);
//Act
var element = _workerBusinessLogicContract.GetWorkerByData(id);
//Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.Id, Is.EqualTo(id));
_workerStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetWorkerByData_GetByFio_ReturnRecord_Test()
{
//Arrange
var fio = "fio";
var record = new WorkerDataModel(Guid.NewGuid().ToString(), fio, Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false);
_workerStorageContract.Setup(x => x.GetElementByFIO(fio)).Returns(record);
//Act
var element = _workerBusinessLogicContract.GetWorkerByData(fio);
//Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.FIO, Is.EqualTo(fio));
_workerStorageContract.Verify(x => x.GetElementByFIO(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetWorkerByData_EmptyData_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.GetWorkerByData(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _workerBusinessLogicContract.GetWorkerByData(string.Empty), Throws.TypeOf<ArgumentNullException>());
_workerStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Never);
_workerStorageContract.Verify(x => x.GetElementByFIO(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetWorkerByData_GetById_NotFoundRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.GetWorkerByData(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_workerStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
_workerStorageContract.Verify(x => x.GetElementByFIO(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetWorkerByData_GetByFio_NotFoundRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.GetWorkerByData("fio"), Throws.TypeOf<ElementNotFoundException>());
_workerStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Never);
_workerStorageContract.Verify(x => x.GetElementByFIO(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetWorkerByData_StorageThrowError_ThrowException_Test()
{
//Arrange
_workerStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
_workerStorageContract.Setup(x => x.GetElementByFIO(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.GetWorkerByData(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
Assert.That(() => _workerBusinessLogicContract.GetWorkerByData("fio"), Throws.TypeOf<StorageException>());
_workerStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
_workerStorageContract.Verify(x => x.GetElementByFIO(It.IsAny<string>()), Times.Once);
}
[Test]
public void InsertWorker_CorrectRecord_Test()
{
//Arrange
var flag = false;
var record = new WorkerDataModel(Guid.NewGuid().ToString(), "fio", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false);
_workerStorageContract.Setup(x => x.AddElement(It.IsAny<WorkerDataModel>()))
.Callback((WorkerDataModel 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
_workerBusinessLogicContract.InsertWorker(record);
//Assert
_workerStorageContract.Verify(x => x.AddElement(It.IsAny<WorkerDataModel>()), Times.Once);
Assert.That(flag);
}
[Test]
public void InsertWorker_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_workerStorageContract.Setup(x => x.AddElement(It.IsAny<WorkerDataModel>())).Throws(new ElementExistsException("Data", "Data"));
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.InsertWorker(new(Guid.NewGuid().ToString(), "fio", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false)), Throws.TypeOf<ElementExistsException>());
_workerStorageContract.Verify(x => x.AddElement(It.IsAny<WorkerDataModel>()), Times.Once);
}
[Test]
public void InsertWorker_NullRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.InsertWorker(null), Throws.TypeOf<ArgumentNullException>());
_workerStorageContract.Verify(x => x.AddElement(It.IsAny<WorkerDataModel>()), Times.Never);
}
[Test]
public void InsertWorker_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.InsertWorker(new WorkerDataModel("id", "fio", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false)), Throws.TypeOf<ValidationException>());
_workerStorageContract.Verify(x => x.AddElement(It.IsAny<WorkerDataModel>()), Times.Never);
}
[Test]
public void InsertWorker_StorageThrowError_ThrowException_Test()
{
//Arrange
_workerStorageContract.Setup(x => x.AddElement(It.IsAny<WorkerDataModel>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.InsertWorker(new(Guid.NewGuid().ToString(), "fio", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false)), Throws.TypeOf<StorageException>());
_workerStorageContract.Verify(x => x.AddElement(It.IsAny<WorkerDataModel>()), Times.Once);
}
[Test]
public void UpdateWorker_CorrectRecord_Test()
{
//Arrange
var flag = false;
var record = new WorkerDataModel(Guid.NewGuid().ToString(), "fio", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false);
_workerStorageContract.Setup(x => x.UpdElement(It.IsAny<WorkerDataModel>()))
.Callback((WorkerDataModel 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
_workerBusinessLogicContract.UpdateWorker(record);
//Assert
_workerStorageContract.Verify(x => x.UpdElement(It.IsAny<WorkerDataModel>()), Times.Once);
Assert.That(flag);
}
[Test]
public void UpdateWorker_RecordWithIncorrectData_ThrowException_Test()
{
//Arrange
_workerStorageContract.Setup(x => x.UpdElement(It.IsAny<WorkerDataModel>())).Throws(new ElementNotFoundException(""));
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.UpdateWorker(new(Guid.NewGuid().ToString(), "fio", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false)), Throws.TypeOf<ElementNotFoundException>());
_workerStorageContract.Verify(x => x.UpdElement(It.IsAny<WorkerDataModel>()), Times.Once);
}
[Test]
public void UpdateWorker_NullRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.UpdateWorker(null), Throws.TypeOf<ArgumentNullException>());
_workerStorageContract.Verify(x => x.UpdElement(It.IsAny<WorkerDataModel>()), Times.Never);
}
[Test]
public void UpdateWorker_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.UpdateWorker(new WorkerDataModel("id", "fio", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false)), Throws.TypeOf<ValidationException>());
_workerStorageContract.Verify(x => x.UpdElement(It.IsAny<WorkerDataModel>()), Times.Never);
}
[Test]
public void UpdateWorker_StorageThrowError_ThrowException_Test()
{
//Arrange
_workerStorageContract.Setup(x => x.UpdElement(It.IsAny<WorkerDataModel>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.UpdateWorker(new(Guid.NewGuid().ToString(), "fio", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false)), Throws.TypeOf<StorageException>());
_workerStorageContract.Verify(x => x.UpdElement(It.IsAny<WorkerDataModel>()), Times.Once);
}
[Test]
public void DeleteWorker_CorrectRecord_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
var flag = false;
_workerStorageContract.Setup(x => x.DelElement(It.Is((string x) => x == id))).Callback(() => { flag = true; });
//Act
_workerBusinessLogicContract.DeleteWorker(id);
//Assert
_workerStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
Assert.That(flag);
}
[Test]
public void DeleteWorker_RecordWithIncorrectId_ThrowException_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
_workerStorageContract.Setup(x => x.DelElement(It.Is((string x) => x != id))).Throws(new ElementNotFoundException(id));
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.DeleteWorker(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_workerStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
}
[Test]
public void DeleteWorker_IdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.DeleteWorker(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _workerBusinessLogicContract.DeleteWorker(string.Empty), Throws.TypeOf<ArgumentNullException>());
_workerStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Never);
}
[Test]
public void DeleteWorker_IdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.DeleteWorker("id"), Throws.TypeOf<ValidationException>());
_workerStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Never);
}
[Test]
public void DeleteWorker_StorageThrowError_ThrowException_Test()
{
//Arrange
_workerStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.DeleteWorker(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_workerStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
}
}

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.11.1" />
<PackageReference Include="Moq" Version="4.20.72" />
<PackageReference Include="NUnit" Version="4.2.2" />
<PackageReference Include="NUnit.Analyzers" Version="4.3.0" />
<PackageReference Include="NUnit3TestAdapter" Version="4.6.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\CatHasPawsBusinessLogic\CatHasPawsBusinessLogic.csproj" />
<ProjectReference Include="..\CatHasPawsContratcs\CatHasPawsContratcs.csproj" />
<ProjectReference Include="..\CatHasPawsDatabase\CatHasPawsDatabase.csproj" />
</ItemGroup>
<ItemGroup>
<Using Include="NUnit.Framework" />
</ItemGroup>
</Project>

View File

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

View File

@@ -0,0 +1,54 @@
using CatHasPawsContratcs.DataModels;
using CatHasPawsContratcs.Exceptions;
namespace CatHasPawsTests.DataModelsTests;
[TestFixture]
internal class ManufacturerDataModelTests
{
[Test]
public void IdIsNullEmptyTest()
{
var manufacturer = CreateDataModel(null, "name");
Assert.That(() => manufacturer.Validate(), Throws.TypeOf<ValidationException>());
manufacturer = CreateDataModel(string.Empty, "name");
Assert.That(() => manufacturer.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void IdIsNotGuidTest()
{
var manufacturer = CreateDataModel("id", "name");
Assert.That(() => manufacturer.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void ManufacturerNameIsNullOrEmptyTest()
{
var manufacturer = CreateDataModel(Guid.NewGuid().ToString(), null);
Assert.That(() => manufacturer.Validate(), Throws.TypeOf<ValidationException>());
manufacturer = CreateDataModel(Guid.NewGuid().ToString(), string.Empty);
Assert.That(() => manufacturer.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void AllFieldsIsCorrectTest()
{
var manufacturerId = Guid.NewGuid().ToString();
var manufacturerName = "name";
var prevManufacturerName = "prevManufacturerName";
var prevPrevManufacturerName = "prevPrevManufacturerName";
var manufacturer = CreateDataModel(manufacturerId, manufacturerName, prevManufacturerName, prevPrevManufacturerName);
Assert.That(() => manufacturer.Validate(), Throws.Nothing);
Assert.Multiple(() =>
{
Assert.That(manufacturer.Id, Is.EqualTo(manufacturerId));
Assert.That(manufacturer.ManufacturerName, Is.EqualTo(manufacturerName));
Assert.That(manufacturer.PrevManufacturerName, Is.EqualTo(prevManufacturerName));
Assert.That(manufacturer.PrevPrevManufacturerName, Is.EqualTo(prevPrevManufacturerName));
});
}
private static ManufacturerDataModel CreateDataModel(string? id, string? manufacturerName, string? prevManufacturerName = null, string? prevPrevManufacturerName = null) =>
new(id, manufacturerName, prevManufacturerName, prevPrevManufacturerName);
}

View File

@@ -0,0 +1,75 @@
using CatHasPawsContratcs.DataModels;
using CatHasPawsContratcs.Enums;
using CatHasPawsContratcs.Exceptions;
namespace CatHasPawsTests.DataModelsTests;
[TestFixture]
internal class PostDataModelTests
{
[Test]
public void IdIsNullOrEmptyTest()
{
var post = CreateDataModel(null, "name", PostType.Assistant, 10, true, DateTime.UtcNow);
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
post = CreateDataModel(string.Empty, "name", PostType.Assistant, 10, true, DateTime.UtcNow);
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void IdIsNotGuidTest()
{
var post = CreateDataModel("id", "name", PostType.Assistant, 10, true, DateTime.UtcNow);
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void PostNameIsEmptyTest()
{
var manufacturer = CreateDataModel(Guid.NewGuid().ToString(), null, PostType.Assistant, 10, true, DateTime.UtcNow);
Assert.That(() => manufacturer.Validate(), Throws.TypeOf<ValidationException>());
manufacturer = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, PostType.Assistant, 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.Assistant, 0, true, DateTime.UtcNow);
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
post = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.Assistant, -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.Assistant;
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,91 @@
using CatHasPawsContratcs.DataModels;
using CatHasPawsContratcs.Enums;
using CatHasPawsContratcs.Exceptions;
namespace CatHasPawsTests.DataModelsTests;
[TestFixture]
internal class ProductDataModelTests
{
[Test]
public void IdIsNullOrEmptyTest()
{
var product = CreateDataModel(null, "name", ProductType.Accessory, Guid.NewGuid().ToString(), 10, false);
Assert.That(() => product.Validate(), Throws.TypeOf<ValidationException>());
product = CreateDataModel(string.Empty, "name", ProductType.Accessory, Guid.NewGuid().ToString(), 10, false);
Assert.That(() => product.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void IdIsNotGuidTest()
{
var product = CreateDataModel("id", "name", ProductType.Accessory, Guid.NewGuid().ToString(), 10, false);
Assert.That(() => product.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void ProductNameIsEmptyTest()
{
var product = CreateDataModel(Guid.NewGuid().ToString(), null, ProductType.Accessory, Guid.NewGuid().ToString(), 10, false);
Assert.That(() => product.Validate(), Throws.TypeOf<ValidationException>());
product = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, ProductType.Accessory, Guid.NewGuid().ToString(), 10, false);
Assert.That(() => product.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void ProductTypeIsNoneTest()
{
var product = CreateDataModel(Guid.NewGuid().ToString(), null, ProductType.None, Guid.NewGuid().ToString(), 10, false);
Assert.That(() => product.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void ManufacturerIdIsNullOrEmptyTest()
{
var product = CreateDataModel(Guid.NewGuid().ToString(), "name", ProductType.Accessory, null, 10, false);
Assert.That(() => product.Validate(), Throws.TypeOf<ValidationException>());
product = CreateDataModel(Guid.NewGuid().ToString(), "name", ProductType.Accessory, string.Empty, 10, false);
Assert.That(() => product.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void ManufacturerIdIsNotGuidTest()
{
var product = CreateDataModel(Guid.NewGuid().ToString(), "name", ProductType.Accessory, "manufacturerId", 10, false);
Assert.That(() => product.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void PriceIsLessOrZeroTest()
{
var product = CreateDataModel(Guid.NewGuid().ToString(), "name", ProductType.Accessory, Guid.NewGuid().ToString(), 0, false);
Assert.That(() => product.Validate(), Throws.TypeOf<ValidationException>());
product = CreateDataModel(Guid.NewGuid().ToString(), "name", ProductType.Accessory, Guid.NewGuid().ToString(), -10, false);
Assert.That(() => product.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void AllFieldsIsCorrectTest()
{
var productId = Guid.NewGuid().ToString();
var productName = "name";
var productType = ProductType.Accessory;
var productManufacturerId = Guid.NewGuid().ToString();
var productPrice = 10;
var productIsDelete = false;
var product = CreateDataModel(productId, productName, productType, productManufacturerId, productPrice, productIsDelete);
Assert.That(() => product.Validate(), Throws.Nothing);
Assert.Multiple(() =>
{
Assert.That(product.Id, Is.EqualTo(productId));
Assert.That(product.ProductName, Is.EqualTo(productName));
Assert.That(product.ProductType, Is.EqualTo(productType));
Assert.That(product.ManufacturerId, Is.EqualTo(productManufacturerId));
Assert.That(product.Price, Is.EqualTo(productPrice));
Assert.That(product.IsDeleted, Is.EqualTo(productIsDelete));
});
}
private static ProductDataModel CreateDataModel(string? id, string? productName, ProductType productType, string? manufacturerId, double price, bool isDeleted) =>
new(id, productName, productType, manufacturerId, price, isDeleted);
}

View File

@@ -0,0 +1,52 @@
using CatHasPawsContratcs.DataModels;
using CatHasPawsContratcs.Exceptions;
namespace CatHasPawsTests.DataModelsTests;
[TestFixture]
internal class ProductHistoryDataModelTests
{
[Test]
public void ProductIdIsNullOrEmptyTest()
{
var product = CreateDataModel(null, 10);
Assert.That(() => product.Validate(), Throws.TypeOf<ValidationException>());
product = CreateDataModel(string.Empty, 10);
Assert.That(() => product.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void ProductIdIsNotGuidTest()
{
var product = CreateDataModel("id", 10);
Assert.That(() => product.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void OldPriceIsLessOrZeroTest()
{
var product = CreateDataModel(Guid.NewGuid().ToString(), 0);
Assert.That(() => product.Validate(), Throws.TypeOf<ValidationException>());
product = CreateDataModel(Guid.NewGuid().ToString(), -10);
Assert.That(() => product.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void AllFieldsIsCorrectTest()
{
var productId = Guid.NewGuid().ToString();
var oldPrice = 10;
var productHistory = CreateDataModel(productId, oldPrice);
Assert.That(() => productHistory.Validate(), Throws.Nothing);
Assert.Multiple(() =>
{
Assert.That(productHistory.ProductId, Is.EqualTo(productId));
Assert.That(productHistory.OldPrice, Is.EqualTo(oldPrice));
Assert.That(productHistory.ChangeDate, Is.LessThan(DateTime.UtcNow));
Assert.That(productHistory.ChangeDate, Is.GreaterThan(DateTime.UtcNow.AddMinutes(-1)));
});
}
private static ProductHistoryDataModel CreateDataModel(string? productId, double oldPrice) =>
new(productId, oldPrice);
}

View File

@@ -0,0 +1,52 @@
using CatHasPawsContratcs.DataModels;
using CatHasPawsContratcs.Exceptions;
namespace CatHasPawsTests.DataModelsTests;
[TestFixture]
internal class SalaryDataModelTests
{
[Test]
public void WorkerIdIsEmptyTest()
{
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 WorkerIdIsNotGuidTest()
{
var salary = CreateDataModel("workerId", DateTime.Now, 10);
Assert.That(() => salary.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void PriceIsLessOrZeroTest()
{
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 workerId = Guid.NewGuid().ToString();
var salaryDate = DateTime.Now.AddDays(-3).AddMinutes(-5);
var workerSalary = 10;
var salary = CreateDataModel(workerId, salaryDate, workerSalary);
Assert.That(() => salary.Validate(), Throws.Nothing);
Assert.Multiple(() =>
{
Assert.That(salary.WorkerId, Is.EqualTo(workerId));
Assert.That(salary.SalaryDate, Is.EqualTo(salaryDate));
Assert.That(salary.Salary, Is.EqualTo(workerSalary));
});
}
private static SalaryDataModel CreateDataModel(string? workerId, DateTime salaryDate, double workerSalary) =>
new(workerId, salaryDate, workerSalary);
}

View File

@@ -0,0 +1,97 @@
using CatHasPawsContratcs.DataModels;
using CatHasPawsContratcs.Enums;
using CatHasPawsContratcs.Exceptions;
namespace CatHasPawsTests.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 WorkerIdIsNullOrEmptyTest()
{
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 WorkerIdIsNotGuidTest()
{
var sale = CreateDataModel(Guid.NewGuid().ToString(), "workerId", Guid.NewGuid().ToString(), 10, DiscountType.OnSale, 10, false, CreateSubDataModel());
Assert.That(() => sale.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void BuyerIdIsNotGuidTest()
{
var sale = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), "buyerId", 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 ProductsIsNullOrEmptyTest()
{
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 workerId = Guid.NewGuid().ToString();
var buyerId = Guid.NewGuid().ToString();
var sum = 10;
var discountType = DiscountType.Certificate;
var discount = 1;
var isCancel = true;
var products = CreateSubDataModel();
var sale = CreateDataModel(saleId, workerId, buyerId, sum, discountType, discount, isCancel, products);
Assert.That(() => sale.Validate(), Throws.Nothing);
Assert.Multiple(() =>
{
Assert.That(sale.Id, Is.EqualTo(saleId));
Assert.That(sale.WorkerId, Is.EqualTo(workerId));
Assert.That(sale.BuyerId, Is.EqualTo(buyerId));
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.Products, Is.EquivalentTo(products));
});
}
private static SaleDataModel CreateDataModel(string? id, string? workerId, string? buyerId, double sum, DiscountType discountType, double discount, bool isCancel, List<SaleProductDataModel>? products) =>
new(id, workerId, buyerId, sum, discountType, discount, isCancel, products);
private static List<SaleProductDataModel> CreateSubDataModel()
=> [new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 1)];
}

View File

@@ -0,0 +1,68 @@
using CatHasPawsContratcs.DataModels;
using CatHasPawsContratcs.Exceptions;
namespace CatHasPawsTests.DataModelsTests;
[TestFixture]
internal class SaleProductDataModelTests
{
[Test]
public void SaleIdIsNullOrEmptyTest()
{
var saleProduct = CreateDataModel(null, Guid.NewGuid().ToString(), 10);
Assert.That(() => saleProduct.Validate(), Throws.TypeOf<ValidationException>());
saleProduct = CreateDataModel(string.Empty, Guid.NewGuid().ToString(), 10);
Assert.That(() => saleProduct.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 ProductIdIsNullOrEmptyTest()
{
var saleProduct = CreateDataModel(Guid.NewGuid().ToString(), null, 10);
Assert.That(() => saleProduct.Validate(), Throws.TypeOf<ValidationException>());
saleProduct = CreateDataModel(string.Empty, Guid.NewGuid().ToString(), 10);
Assert.That(() => saleProduct.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void ProductIdIsNotGuidTest()
{
var saleProduct = CreateDataModel(Guid.NewGuid().ToString(), "productId", 10);
Assert.That(() => saleProduct.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void CountIsLessOrZeroTest()
{
var saleProduct = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 0);
Assert.That(() => saleProduct.Validate(), Throws.TypeOf<ValidationException>());
saleProduct = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), -10);
Assert.That(() => saleProduct.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void AllFieldsIsCorrectTest()
{
var saleId = Guid.NewGuid().ToString();
var productId = Guid.NewGuid().ToString();
var count = 10;
var saleProduct = CreateDataModel(saleId, productId, count);
Assert.That(() => saleProduct.Validate(), Throws.Nothing);
Assert.Multiple(() =>
{
Assert.That(saleProduct.SaleId, Is.EqualTo(saleId));
Assert.That(saleProduct.ProductId, Is.EqualTo(productId));
Assert.That(saleProduct.Count, Is.EqualTo(count));
});
}
private static SaleProductDataModel CreateDataModel(string? saleId, string? productId, int count) =>
new(saleId, productId, count);
}

View File

@@ -0,0 +1,90 @@
using CatHasPawsContratcs.DataModels;
using CatHasPawsContratcs.Exceptions;
namespace CatHasPawsTests.DataModelsTests;
[TestFixture]
internal class WorkerDataModelTests
{
[Test]
public void IdIsNullOrEmptyTest()
{
var worker = CreateDataModel(null, "fio", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18), DateTime.Now, false);
Assert.That(() => worker.Validate(), Throws.TypeOf<ValidationException>());
worker = CreateDataModel(string.Empty, "fio", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18), DateTime.Now, false);
Assert.That(() => worker.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void IdIsNotGuidTest()
{
var worker = CreateDataModel("id", "fio", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18), DateTime.Now, false);
Assert.That(() => worker.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void FIOIsNullOrEmptyTest()
{
var worker = CreateDataModel(Guid.NewGuid().ToString(), null, Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18), DateTime.Now, false);
Assert.That(() => worker.Validate(), Throws.TypeOf<ValidationException>());
worker = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18), DateTime.Now, false);
Assert.That(() => worker.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void PostIdIsNullOrEmptyTest()
{
var worker = CreateDataModel(Guid.NewGuid().ToString(), "fio", null, DateTime.Now.AddYears(-18), DateTime.Now, false);
Assert.That(() => worker.Validate(), Throws.TypeOf<ValidationException>());
worker = CreateDataModel(Guid.NewGuid().ToString(), "fio", string.Empty, DateTime.Now.AddYears(-18), DateTime.Now, false);
Assert.That(() => worker.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void PostIdIsNotGuidTest()
{
var worker = CreateDataModel(Guid.NewGuid().ToString(), "fio", "postId", DateTime.Now.AddYears(-18), DateTime.Now, false);
Assert.That(() => worker.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void BirthDateIsNotCorrectTest()
{
var worker = CreateDataModel(Guid.NewGuid().ToString(), "fio", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(1), DateTime.Now, false);
Assert.That(() => worker.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void BirthDateAndEmploymentDateIsNotCorrectTest()
{
var worker = CreateDataModel(Guid.NewGuid().ToString(), "fio", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18), DateTime.Now.AddYears(-18).AddDays(-1), false);
Assert.That(() => worker.Validate(), Throws.TypeOf<ValidationException>());
worker = CreateDataModel(Guid.NewGuid().ToString(), "fio", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18), DateTime.Now.AddYears(-16), false);
Assert.That(() => worker.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void AllFieldsIsCorrectTest()
{
var workerId = Guid.NewGuid().ToString();
var fio = "fio";
var postId = Guid.NewGuid().ToString();
var birthDate = DateTime.Now.AddYears(-16).AddDays(-1);
var employmentDate = DateTime.Now;
var isDelete = false;
var worker = CreateDataModel(workerId, fio, postId, birthDate, employmentDate, isDelete);
Assert.That(() => worker.Validate(), Throws.Nothing);
Assert.Multiple(() =>
{
Assert.That(worker.Id, Is.EqualTo(workerId));
Assert.That(worker.FIO, Is.EqualTo(fio));
Assert.That(worker.PostId, Is.EqualTo(postId));
Assert.That(worker.BirthDate, Is.EqualTo(birthDate));
Assert.That(worker.EmploymentDate, Is.EqualTo(employmentDate));
Assert.That(worker.IsDeleted, Is.EqualTo(isDelete));
});
}
private static WorkerDataModel CreateDataModel(string? id, string? fio, string? postId, DateTime birthDate, DateTime employmentDate, bool isDeleted) =>
new(id, fio, postId, birthDate, employmentDate, isDeleted);
}

View File

@@ -0,0 +1,9 @@
using CatHasPawsContratcs.Infrastructure;
namespace CatHasPawsTests.Infrastructure;
internal class ConfigurationDatabaseTest : IConfigurationDatabase
{
public string ConnectionString =>
"Host=127.0.0.1;Port=5432;Database=CatHasPawsTest;Username=postgres;Password=postgres;";
}

View File

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

View File

@@ -0,0 +1,212 @@
using CatHasPawsContratcs.DataModels;
using CatHasPawsContratcs.Enums;
using CatHasPawsContratcs.Exceptions;
using CatHasPawsDatabase.Implementations;
using CatHasPawsDatabase.Models;
using Microsoft.EntityFrameworkCore;
namespace CatHasPawsTests.StoragesContracts;
[TestFixture]
internal class BuyerStorageContractTests : BaseStorageContractTest
{
private BuyerStorageContract _buyerStorageContract;
[SetUp]
public void SetUp()
{
_buyerStorageContract = new BuyerStorageContract(CatHasPawsDbContext);
}
[TearDown]
public void TearDown()
{
CatHasPawsDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Sales\" CASCADE;");
CatHasPawsDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Workers\" CASCADE;");
CatHasPawsDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Buyers\" CASCADE;");
}
[Test]
public void Try_GetList_WhenHaveRecords_Test()
{
var buyer = InsertBuyerToDatabaseAndReturn(Guid.NewGuid().ToString(), phoneNumber: "+5-555-555-55-55");
InsertBuyerToDatabaseAndReturn(Guid.NewGuid().ToString(), phoneNumber: "+6-666-666-66-66");
InsertBuyerToDatabaseAndReturn(Guid.NewGuid().ToString(), phoneNumber: "+7-777-777-77-77");
var list = _buyerStorageContract.GetList();
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(3));
AssertElement(list.First(x => x.Id == buyer.Id), buyer);
}
[Test]
public void Try_GetList_WhenNoRecords_Test()
{
var list = _buyerStorageContract.GetList();
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.Empty);
}
[Test]
public void Try_GetElementById_WhenHaveRecord_Test()
{
var buyer = InsertBuyerToDatabaseAndReturn(Guid.NewGuid().ToString());
AssertElement(_buyerStorageContract.GetElementById(buyer.Id), buyer);
}
[Test]
public void Try_GetElementById_WhenNoRecord_Test()
{
InsertBuyerToDatabaseAndReturn(Guid.NewGuid().ToString());
Assert.That(() => _buyerStorageContract.GetElementById(Guid.NewGuid().ToString()), Is.Null);
}
[Test]
public void Try_GetElementByFIO_WhenHaveRecord_Test()
{
var buyer = InsertBuyerToDatabaseAndReturn(Guid.NewGuid().ToString());
AssertElement(_buyerStorageContract.GetElementByFIO(buyer.FIO), buyer);
}
[Test]
public void Try_GetElementByFIO_WhenNoRecord_Test()
{
InsertBuyerToDatabaseAndReturn(Guid.NewGuid().ToString());
Assert.That(() => _buyerStorageContract.GetElementByFIO("New Fio"), Is.Null);
}
[Test]
public void Try_GetElementByPhoneNumber_WhenHaveRecord_Test()
{
var buyer = InsertBuyerToDatabaseAndReturn(Guid.NewGuid().ToString());
AssertElement(_buyerStorageContract.GetElementByPhoneNumber(buyer.PhoneNumber), buyer);
}
[Test]
public void Try_GetElementByPhoneNumber_WhenNoRecord_Test()
{
InsertBuyerToDatabaseAndReturn(Guid.NewGuid().ToString());
Assert.That(() => _buyerStorageContract.GetElementByPhoneNumber("+8-888-888-88-88"), Is.Null);
}
[Test]
public void Try_AddElement_Test()
{
var buyer = CreateModel(Guid.NewGuid().ToString());
_buyerStorageContract.AddElement(buyer);
AssertElement(GetBuyerFromDatabase(buyer.Id), buyer);
}
[Test]
public void Try_AddElement_WhenHaveRecordWithSameId_Test()
{
var buyer = CreateModel(Guid.NewGuid().ToString(), "New Fio", "+5-555-555-55-55", 500);
InsertBuyerToDatabaseAndReturn(buyer.Id);
Assert.That(() => _buyerStorageContract.AddElement(buyer), Throws.TypeOf<ElementExistsException>());
}
[Test]
public void Try_AddElement_WhenHaveRecordWithSamePhoneNumber_Test()
{
var buyer = CreateModel(Guid.NewGuid().ToString(), "New Fio", "+5-555-555-55-55", 500);
InsertBuyerToDatabaseAndReturn(Guid.NewGuid().ToString(), phoneNumber: buyer.PhoneNumber);
Assert.That(() => _buyerStorageContract.AddElement(buyer), Throws.TypeOf<ElementExistsException>());
}
[Test]
public void Try_UpdElement_Test()
{
var buyer = CreateModel(Guid.NewGuid().ToString(), "New Fio", "+5-555-555-55-55", 500);
InsertBuyerToDatabaseAndReturn(buyer.Id);
_buyerStorageContract.UpdElement(buyer);
AssertElement(GetBuyerFromDatabase(buyer.Id), buyer);
}
[Test]
public void Try_UpdElement_WhenNoRecordWithThisId_Test()
{
Assert.That(() => _buyerStorageContract.UpdElement(CreateModel(Guid.NewGuid().ToString())), Throws.TypeOf<ElementNotFoundException>());
}
[Test]
public void Try_UpdElement_WhenHaveRecordWithSamePhoneNumber_Test()
{
var buyer = CreateModel(Guid.NewGuid().ToString(), "New Fio", "+5-555-555-55-55", 500);
InsertBuyerToDatabaseAndReturn(buyer.Id, phoneNumber: "+7-777-777-77-77");
InsertBuyerToDatabaseAndReturn(Guid.NewGuid().ToString(), phoneNumber: buyer.PhoneNumber);
Assert.That(() => _buyerStorageContract.UpdElement(buyer), Throws.TypeOf<ElementExistsException>());
}
[Test]
public void Try_DelElement_Test()
{
var buyer = InsertBuyerToDatabaseAndReturn(Guid.NewGuid().ToString());
_buyerStorageContract.DelElement(buyer.Id);
var element = GetBuyerFromDatabase(buyer.Id);
Assert.That(element, Is.Null);
}
[Test]
public void Try_DelElement_WhenHaveSalesByThisBuyer_Test()
{
var buyer = InsertBuyerToDatabaseAndReturn(Guid.NewGuid().ToString());
var workerId = Guid.NewGuid().ToString();
CatHasPawsDbContext.Workers.Add(new Worker() { Id = workerId, FIO = "test", PostId = Guid.NewGuid().ToString() });
CatHasPawsDbContext.Sales.Add(new Sale() { Id = Guid.NewGuid().ToString(), WorkerId = workerId, BuyerId = buyer.Id, Sum = 10, DiscountType = DiscountType.None, Discount = 0 });
CatHasPawsDbContext.Sales.Add(new Sale() { Id = Guid.NewGuid().ToString(), WorkerId = workerId, BuyerId = buyer.Id, Sum = 10, DiscountType = DiscountType.None, Discount = 0 });
CatHasPawsDbContext.SaveChanges();
var salesBeforeDelete = CatHasPawsDbContext.Sales.Where(x => x.BuyerId == buyer.Id).ToArray();
_buyerStorageContract.DelElement(buyer.Id);
var element = GetBuyerFromDatabase(buyer.Id);
var salesAfterDelete = CatHasPawsDbContext.Sales.Where(x => x.BuyerId == buyer.Id).ToArray();
Assert.Multiple(() =>
{
Assert.That(element, Is.Null);
Assert.That(salesBeforeDelete, Has.Length.EqualTo(2));
Assert.That(salesAfterDelete, Is.Empty);
Assert.That(CatHasPawsDbContext.Sales.Count(), Is.EqualTo(2));
});
}
[Test]
public void Try_DelElement_WhenNoRecordWithThisId_Test()
{
Assert.That(() => _buyerStorageContract.DelElement(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
}
private Buyer InsertBuyerToDatabaseAndReturn(string id, string fio = "test", string phoneNumber = "+7-777-777-77-77", double discountSize = 10)
{
var buyer = new Buyer() { Id = id, FIO = fio, PhoneNumber = phoneNumber, DiscountSize = discountSize };
CatHasPawsDbContext.Buyers.Add(buyer);
CatHasPawsDbContext.SaveChanges();
return buyer;
}
private static void AssertElement(BuyerDataModel? actual, Buyer 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 BuyerDataModel CreateModel(string id, string fio = "test", string phoneNumber = "+7-777-777-77-77", double discountSize = 10)
=> new(id, fio, phoneNumber, discountSize);
private Buyer? GetBuyerFromDatabase(string id) => CatHasPawsDbContext.Buyers.FirstOrDefault(x => x.Id == id);
private static void AssertElement(Buyer? actual, BuyerDataModel 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,207 @@
using CatHasPawsContratcs.DataModels;
using CatHasPawsContratcs.Exceptions;
using CatHasPawsDatabase.Implementations;
using CatHasPawsDatabase.Models;
using Microsoft.EntityFrameworkCore;
namespace CatHasPawsTests.StoragesContracts;
[TestFixture]
internal class ManufacturerStorageContractTests : BaseStorageContractTest
{
private ManufacturerStorageContract _manufacturerStorageContract;
[SetUp]
public void SetUp()
{
_manufacturerStorageContract = new ManufacturerStorageContract(CatHasPawsDbContext);
}
[TearDown]
public void TearDown()
{
CatHasPawsDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Products\" CASCADE;");
CatHasPawsDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Manufacturers\" CASCADE;");
}
[Test]
public void Try_GetList_WhenHaveRecords_Test()
{
var manufacturer = InsertManufacturerToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 1");
InsertManufacturerToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 2");
InsertManufacturerToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 3");
var list = _manufacturerStorageContract.GetList();
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(3));
AssertElement(list.First(x => x.Id == manufacturer.Id), manufacturer);
}
[Test]
public void Try_GetList_WhenNoRecords_Test()
{
var list = _manufacturerStorageContract.GetList();
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.Empty);
}
[Test]
public void Try_GetElementById_WhenHaveRecord_Test()
{
var manufacturer = InsertManufacturerToDatabaseAndReturn(Guid.NewGuid().ToString());
AssertElement(_manufacturerStorageContract.GetElementById(manufacturer.Id), manufacturer);
}
[Test]
public void Try_GetElementById_WhenNoRecord_Test()
{
InsertManufacturerToDatabaseAndReturn(Guid.NewGuid().ToString());
Assert.That(() => _manufacturerStorageContract.GetElementById(Guid.NewGuid().ToString()), Is.Null);
}
[Test]
public void Try_GetElementByName_WhenHaveRecord_Test()
{
var manufacturer = InsertManufacturerToDatabaseAndReturn(Guid.NewGuid().ToString());
AssertElement(_manufacturerStorageContract.GetElementByName(manufacturer.ManufacturerName), manufacturer);
}
[Test]
public void Try_GetElementByName_WhenNoRecord_Test()
{
InsertManufacturerToDatabaseAndReturn(Guid.NewGuid().ToString());
Assert.That(() => _manufacturerStorageContract.GetElementByName("name"), Is.Null);
}
[Test]
public void Try_GetElementByOldName_WhenHaveRecord_Test()
{
var manufacturer = InsertManufacturerToDatabaseAndReturn(Guid.NewGuid().ToString());
AssertElement(_manufacturerStorageContract.GetElementByOldName(manufacturer.PrevManufacturerName!), manufacturer);
AssertElement(_manufacturerStorageContract.GetElementByOldName(manufacturer.PrevPrevManufacturerName!), manufacturer);
}
[Test]
public void Try_GetElementByOldName_WhenNoRecord_Test()
{
InsertManufacturerToDatabaseAndReturn(Guid.NewGuid().ToString());
Assert.That(() => _manufacturerStorageContract.GetElementByOldName("name"), Is.Null);
}
[Test]
public void Try_AddElement_Test()
{
var manufacturer = CreateModel(Guid.NewGuid().ToString());
_manufacturerStorageContract.AddElement(manufacturer);
AssertElement(GetManufacturerFromDatabase(manufacturer.Id), manufacturer);
}
[Test]
public void Try_AddElement_WhenHaveRecordWithSameId_Test()
{
var manufacturer = CreateModel(Guid.NewGuid().ToString(), "name unique");
InsertManufacturerToDatabaseAndReturn(manufacturer.Id);
Assert.That(() => _manufacturerStorageContract.AddElement(manufacturer), Throws.TypeOf<ElementExistsException>());
}
[Test]
public void Try_AddElement_WhenHaveRecordWithSameManufacturerName_Test()
{
var manufacturer = CreateModel(Guid.NewGuid().ToString(), "name unique");
InsertManufacturerToDatabaseAndReturn(Guid.NewGuid().ToString(), manufacturerName: manufacturer.ManufacturerName);
Assert.That(() => _manufacturerStorageContract.AddElement(manufacturer), Throws.TypeOf<ElementExistsException>());
}
[Test]
public void Try_UpdElement_Test()
{
var manufacturer = CreateModel(Guid.NewGuid().ToString(), "name new", "test", "prev");
InsertManufacturerToDatabaseAndReturn(manufacturer.Id, manufacturerName: manufacturer.PrevManufacturerName!, prevManufacturerName: manufacturer.PrevPrevManufacturerName!);
_manufacturerStorageContract.UpdElement(CreateModel(manufacturer.Id, "name new", "some name", "some name"));
AssertElement(GetManufacturerFromDatabase(manufacturer.Id), manufacturer);
}
[Test]
public void Try_UpdElement_WhenNoChangeManufacturerName_Test()
{
var manufacturer = CreateModel(Guid.NewGuid().ToString(), "name new", "test", "prev");
InsertManufacturerToDatabaseAndReturn(manufacturer.Id, manufacturerName: manufacturer.ManufacturerName!, prevManufacturerName: manufacturer.PrevManufacturerName!, prevPrevManufacturerName: manufacturer.PrevPrevManufacturerName!);
_manufacturerStorageContract.UpdElement(manufacturer);
AssertElement(GetManufacturerFromDatabase(manufacturer.Id), manufacturer);
}
[Test]
public void Try_UpdElement_WhenNoRecordWithThisId_Test()
{
Assert.That(() => _manufacturerStorageContract.UpdElement(CreateModel(Guid.NewGuid().ToString())), Throws.TypeOf<ElementNotFoundException>());
}
[Test]
public void Try_UpdElement_WhenHaveRecordWithSameManufacturerName_Test()
{
var manufacturer = CreateModel(Guid.NewGuid().ToString(), "name unique");
InsertManufacturerToDatabaseAndReturn(manufacturer.Id, manufacturerName: "some name");
InsertManufacturerToDatabaseAndReturn(Guid.NewGuid().ToString(), manufacturerName: manufacturer.ManufacturerName);
Assert.That(() => _manufacturerStorageContract.UpdElement(manufacturer), Throws.TypeOf<ElementExistsException>());
}
[Test]
public void Try_DelElement_WhenNoProducts_Test()
{
var manufacturer = InsertManufacturerToDatabaseAndReturn(Guid.NewGuid().ToString());
_manufacturerStorageContract.DelElement(manufacturer.Id);
var element = GetManufacturerFromDatabase(manufacturer.Id);
Assert.That(element, Is.Null);
}
[Test]
public void Try_DelElement_WhenHaveProducts_Test()
{
var manufacturer = InsertManufacturerToDatabaseAndReturn(Guid.NewGuid().ToString());
CatHasPawsDbContext.Products.Add(new Product() { Id = Guid.NewGuid().ToString(), ProductName = "name", ManufacturerId = manufacturer.Id, Price = 10, IsDeleted = false });
CatHasPawsDbContext.SaveChanges();
Assert.That(() => _manufacturerStorageContract.DelElement(manufacturer.Id), Throws.TypeOf<StorageException>());
}
[Test]
public void Try_DelElement_WhenNoRecordWithThisId_Test()
{
Assert.That(() => _manufacturerStorageContract.DelElement(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
}
private Manufacturer InsertManufacturerToDatabaseAndReturn(string id, string manufacturerName = "test", string prevManufacturerName = "prev", string prevPrevManufacturerName = "prevPrev")
{
var manufacturer = new Manufacturer() { Id = id, ManufacturerName = manufacturerName, PrevManufacturerName = prevManufacturerName, PrevPrevManufacturerName = prevPrevManufacturerName };
CatHasPawsDbContext.Manufacturers.Add(manufacturer);
CatHasPawsDbContext.SaveChanges();
return manufacturer;
}
private static void AssertElement(ManufacturerDataModel? actual, Manufacturer expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.Id, Is.EqualTo(expected.Id));
Assert.That(actual.ManufacturerName, Is.EqualTo(expected.ManufacturerName));
Assert.That(actual.PrevManufacturerName, Is.EqualTo(expected.PrevManufacturerName));
Assert.That(actual.PrevPrevManufacturerName, Is.EqualTo(expected.PrevPrevManufacturerName));
});
}
private static ManufacturerDataModel CreateModel(string id, string manufacturerName = "test", string prevManufacturerName = "prev", string prevPrevManufacturerName = "prevPrev")
=> new(id, manufacturerName, prevManufacturerName, prevPrevManufacturerName);
private Manufacturer? GetManufacturerFromDatabase(string id) => CatHasPawsDbContext.Manufacturers.FirstOrDefault(x => x.Id == id);
private static void AssertElement(Manufacturer? actual, ManufacturerDataModel expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.Id, Is.EqualTo(expected.Id));
Assert.That(actual.ManufacturerName, Is.EqualTo(expected.ManufacturerName));
Assert.That(actual.PrevManufacturerName, Is.EqualTo(expected.PrevManufacturerName));
Assert.That(actual.PrevPrevManufacturerName, Is.EqualTo(expected.PrevPrevManufacturerName));
});
}
}

View File

@@ -0,0 +1,317 @@
using CatHasPawsContratcs.DataModels;
using CatHasPawsContratcs.Enums;
using CatHasPawsContratcs.Exceptions;
using CatHasPawsDatabase.Implementations;
using CatHasPawsDatabase.Models;
using Microsoft.EntityFrameworkCore;
namespace CatHasPawsTests.StoragesContracts;
[TestFixture]
internal class PostStorageContractTests : BaseStorageContractTest
{
private PostStorageContract _postStorageContract;
[SetUp]
public void SetUp()
{
_postStorageContract = new PostStorageContract(CatHasPawsDbContext);
}
[TearDown]
public void TearDown()
{
CatHasPawsDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Posts\" CASCADE;");
}
[Test]
public void Try_GetList_WhenHaveRecords_Test()
{
var post = InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 1");
InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 2");
InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 3");
var list = _postStorageContract.GetList();
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(3));
AssertElement(list.First(x => x.Id == post.PostId), post);
}
[Test]
public void Try_GetList_WhenNoRecords_Test()
{
var list = _postStorageContract.GetList();
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.Empty);
}
[Test]
public void Try_GetList_OnlyActual_Test()
{
InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 1", isActual: true);
InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 2", isActual: true);
InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 3", isActual: false);
var list = _postStorageContract.GetList(onlyActual: true);
Assert.That(list, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(list, Has.Count.EqualTo(2));
Assert.That(!list.Any(x => !x.IsActual));
});
}
[Test]
public void Try_GetList_IncludeNoActual_Test()
{
InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 1", isActual: true);
InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 2", isActual: true);
InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 3", isActual: false);
var list = _postStorageContract.GetList(onlyActual: false);
Assert.That(list, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(list, Has.Count.EqualTo(3));
Assert.That(list.Count(x => x.IsActual), Is.EqualTo(2));
Assert.That(list.Count(x => !x.IsActual), Is.EqualTo(1));
});
}
[Test]
public void Try_GetPostWithHistory_WhenHaveRecords_Test()
{
var postId = Guid.NewGuid().ToString();
InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 1", isActual: true);
InsertPostToDatabaseAndReturn(postId, "name 2", isActual: true);
InsertPostToDatabaseAndReturn(postId, "name 2", isActual: false);
var list = _postStorageContract.GetPostWithHistory(postId);
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(2));
}
[Test]
public void Try_GetPostWithHistory_WhenNoRecords_Test()
{
var postId = Guid.NewGuid().ToString();
InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 1", isActual: true);
InsertPostToDatabaseAndReturn(postId, "name 2", isActual: true);
InsertPostToDatabaseAndReturn(postId, "name 2", isActual: false);
var list = _postStorageContract.GetPostWithHistory(Guid.NewGuid().ToString());
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
}
[Test]
public void Try_GetElementById_WhenHaveRecord_Test()
{
var post = InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString());
AssertElement(_postStorageContract.GetElementById(post.PostId), post);
}
[Test]
public void Try_GetElementById_WhenNoRecord_Test()
{
InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString());
Assert.That(() => _postStorageContract.GetElementById(Guid.NewGuid().ToString()), Is.Null);
}
[Test]
public void Try_GetElementById_WhenRecordHasDeleted_Test()
{
var post = InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), isActual: false);
Assert.That(() => _postStorageContract.GetElementById(post.PostId), Is.Null);
}
[Test]
public void Try_GetElementById_WhenTrySearchById_Test()
{
var post = InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString());
Assert.That(() => _postStorageContract.GetElementById(post.Id), Is.Null);
}
[Test]
public void Try_GetElementByName_WhenHaveRecord_Test()
{
var post = InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString());
AssertElement(_postStorageContract.GetElementByName(post.PostName), post);
}
[Test]
public void Try_GetElementByName_WhenNoRecord_Test()
{
InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString());
Assert.That(() => _postStorageContract.GetElementByName("name"), Is.Null);
}
[Test]
public void Try_GetElementByName_WhenRecordHasDeleted_Test()
{
var post = InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), isActual: false);
Assert.That(() => _postStorageContract.GetElementById(post.PostName), Is.Null);
}
[Test]
public void Try_AddElement_Test()
{
var post = CreateModel(Guid.NewGuid().ToString(), isActual: true);
_postStorageContract.AddElement(post);
AssertElement(GetPostFromDatabaseByPostId(post.Id), post);
}
[Test]
public void Try_AddElement_WhenActualIsFalse_Test()
{
var post = CreateModel(Guid.NewGuid().ToString(), isActual: false);
Assert.That(() => _postStorageContract.AddElement(post), Throws.Nothing);
AssertElement(GetPostFromDatabaseByPostId(post.Id), CreateModel(post.Id, isActual: true));
}
[Test]
public void Try_AddElement_WhenHaveRecordWithSameName_Test()
{
var post = CreateModel(Guid.NewGuid().ToString(), "name unique", isActual: true);
InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), postName: post.PostName, isActual: true);
Assert.That(() => _postStorageContract.AddElement(post), Throws.TypeOf<ElementExistsException>());
}
[Test]
public void Try_AddElement_WhenHaveRecordWithSamePostIdAndActualIsTrue_Test()
{
var post = CreateModel(Guid.NewGuid().ToString(), isActual: true);
InsertPostToDatabaseAndReturn(post.Id, isActual: true);
Assert.That(() => _postStorageContract.AddElement(post), Throws.TypeOf<ElementExistsException>());
}
[Test]
public void Try_UpdElement_Test()
{
var post = CreateModel(Guid.NewGuid().ToString());
InsertPostToDatabaseAndReturn(post.Id, isActual: true);
_postStorageContract.UpdElement(post);
var posts = CatHasPawsDbContext.Posts.Where(x => x.PostId == post.Id).OrderByDescending(x => x.ChangeDate);
Assert.That(posts.Count(), Is.EqualTo(2));
AssertElement(posts.First(), CreateModel(post.Id, isActual: true));
AssertElement(posts.Last(), CreateModel(post.Id, isActual: false));
}
[Test]
public void Try_UpdElement_WhenActualIsFalse_Test()
{
var post = CreateModel(Guid.NewGuid().ToString(), isActual: false);
InsertPostToDatabaseAndReturn(post.Id, isActual: true);
_postStorageContract.UpdElement(post);
AssertElement(GetPostFromDatabaseByPostId(post.Id), CreateModel(post.Id, isActual: true));
}
[Test]
public void Try_UpdElement_WhenNoRecordWithThisId_Test()
{
Assert.That(() => _postStorageContract.UpdElement(CreateModel(Guid.NewGuid().ToString())), Throws.TypeOf<ElementNotFoundException>());
}
[Test]
public void Try_UpdElement_WhenHaveRecordWithSameName_Test()
{
var post = CreateModel(Guid.NewGuid().ToString(), "New Name");
InsertPostToDatabaseAndReturn(post.Id, postName: "name");
InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), postName: post.PostName);
Assert.That(() => _postStorageContract.UpdElement(post), Throws.TypeOf<ElementExistsException>());
}
[Test]
public void Try_UpdElement_WhenRecordWasDeleted_Test()
{
var post = CreateModel(Guid.NewGuid().ToString());
InsertPostToDatabaseAndReturn(post.Id, isActual: false);
Assert.That(() => _postStorageContract.UpdElement(post), Throws.TypeOf<ElementDeletedException>());
}
[Test]
public void Try_DelElement_Test()
{
var post = InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), isActual: true);
_postStorageContract.DelElement(post.PostId);
var element = GetPostFromDatabaseByPostId(post.PostId);
Assert.Multiple(() =>
{
Assert.That(element, Is.Not.Null);
Assert.That(!element!.IsActual);
});
}
[Test]
public void Try_DelElement_WhenNoRecordWithThisId_Test()
{
Assert.That(() => _postStorageContract.DelElement(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
}
[Test]
public void Try_DelElement_WhenRecordWasDeleted_Test()
{
var post = InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), isActual: false);
Assert.That(() => _postStorageContract.DelElement(post.PostId), Throws.TypeOf<ElementDeletedException>());
}
[Test]
public void Try_ResElement_Test()
{
var post = InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), isActual: false);
_postStorageContract.ResElement(post.PostId);
var element = GetPostFromDatabaseByPostId(post.PostId);
Assert.Multiple(() =>
{
Assert.That(element, Is.Not.Null);
Assert.That(element!.IsActual);
});
}
[Test]
public void Try_ResElement_WhenNoRecordWithThisId_Test()
{
Assert.That(() => _postStorageContract.ResElement(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
}
[Test]
public void Try_ResElement_WhenRecordNotWasDeleted_Test()
{
var post = InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), isActual: true);
Assert.That(() => _postStorageContract.ResElement(post.PostId), Throws.Nothing);
}
private Post InsertPostToDatabaseAndReturn(string id, string postName = "test", PostType postType = PostType.Assistant, double salary = 10, bool isActual = true, DateTime? changeDate = null)
{
var post = new Post() { Id = Guid.NewGuid().ToString(), PostId = id, PostName = postName, PostType = postType, Salary = salary, IsActual = isActual, ChangeDate = changeDate ?? DateTime.UtcNow };
CatHasPawsDbContext.Posts.Add(post);
CatHasPawsDbContext.SaveChanges();
return post;
}
private static void AssertElement(PostDataModel? actual, Post expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.Id, Is.EqualTo(expected.PostId));
Assert.That(actual.PostName, Is.EqualTo(expected.PostName));
Assert.That(actual.PostType, Is.EqualTo(expected.PostType));
Assert.That(actual.Salary, Is.EqualTo(expected.Salary));
Assert.That(actual.IsActual, Is.EqualTo(expected.IsActual));
});
}
private static PostDataModel CreateModel(string postId, string postName = "test", PostType postType = PostType.Assistant, double salary = 10, bool isActual = false, DateTime? changeDate = null)
=> new(postId, postName, postType, salary, isActual, changeDate ?? DateTime.UtcNow);
private Post? GetPostFromDatabaseByPostId(string id) => CatHasPawsDbContext.Posts.Where(x => x.PostId == id).OrderByDescending(x => x.ChangeDate).FirstOrDefault();
private static void AssertElement(Post? actual, PostDataModel expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.PostId, Is.EqualTo(expected.Id));
Assert.That(actual.PostName, Is.EqualTo(expected.PostName));
Assert.That(actual.PostType, Is.EqualTo(expected.PostType));
Assert.That(actual.Salary, Is.EqualTo(expected.Salary));
Assert.That(actual.IsActual, Is.EqualTo(expected.IsActual));
});
}
}

View File

@@ -0,0 +1,351 @@
using CatHasPawsContratcs.DataModels;
using CatHasPawsContratcs.Enums;
using CatHasPawsContratcs.Exceptions;
using CatHasPawsDatabase.Implementations;
using CatHasPawsDatabase.Models;
using Microsoft.EntityFrameworkCore;
namespace CatHasPawsTests.StoragesContracts;
[TestFixture]
internal class ProductStorageContractTests : BaseStorageContractTest
{
private ProductStorageContract _productStorageContract;
private Manufacturer _manufacturer;
[SetUp]
public void SetUp()
{
_productStorageContract = new ProductStorageContract(CatHasPawsDbContext);
_manufacturer = InsertManufacturerToDatabaseAndReturn();
}
[TearDown]
public void TearDown()
{
CatHasPawsDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Products\" CASCADE;");
CatHasPawsDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Manufacturers\" CASCADE;");
}
[Test]
public void Try_GetList_WhenHaveRecords_Test()
{
var product = InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), _manufacturer.Id, "name 1");
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), _manufacturer.Id, "name 2");
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), _manufacturer.Id, "name 3");
var list = _productStorageContract.GetList();
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(3));
AssertElement(list.First(x => x.Id == product.Id), product);
}
[Test]
public void Try_GetList_WhenNoRecords_Test()
{
var list = _productStorageContract.GetList();
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.Empty);
}
[Test]
public void Try_GetList_OnlyActual_Test()
{
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), _manufacturer.Id, "name 1", isDeleted: true);
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), _manufacturer.Id, "name 2", isDeleted: false);
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), _manufacturer.Id, "name 3", isDeleted: false);
var list = _productStorageContract.GetList(onlyActive: true);
Assert.That(list, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(list, Has.Count.EqualTo(2));
Assert.That(!list.Any(x => x.IsDeleted));
});
}
[Test]
public void Try_GetList_IncludeNoActual_Test()
{
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), _manufacturer.Id, "name 1", isDeleted: true);
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), _manufacturer.Id, "name 2", isDeleted: true);
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), _manufacturer.Id, "name 3", isDeleted: false);
var list = _productStorageContract.GetList(onlyActive: false);
Assert.That(list, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(list, Has.Count.EqualTo(3));
Assert.That(list.Count(x => x.IsDeleted), Is.EqualTo(2));
Assert.That(list.Count(x => !x.IsDeleted), Is.EqualTo(1));
});
}
[Test]
public void Try_GetList_ByManufacturer_Test()
{
var manufacruer = InsertManufacturerToDatabaseAndReturn("name 2");
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), _manufacturer.Id, "name 1", isDeleted: true);
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), _manufacturer.Id, "name 2", isDeleted: false);
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), manufacruer.Id, "name 3", isDeleted: false);
var list = _productStorageContract.GetList(manufacturerId: _manufacturer.Id, onlyActive: false);
Assert.That(list, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(list, Has.Count.EqualTo(2));
Assert.That(list.All(x => x.ManufacturerId == _manufacturer.Id));
});
}
[Test]
public void Try_GetList_ByManufacturerOnlyActual_Test()
{
var manufacruer = InsertManufacturerToDatabaseAndReturn("name 2");
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), _manufacturer.Id, "name 1", isDeleted: true);
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), _manufacturer.Id, "name 2", isDeleted: false);
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), manufacruer.Id, "name 3", isDeleted: false);
var list = _productStorageContract.GetList(manufacturerId: _manufacturer.Id, onlyActive: true);
Assert.That(list, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(list, Has.Count.EqualTo(1));
Assert.That(list.All(x => x.ManufacturerId == _manufacturer.Id && !x.IsDeleted));
});
}
[Test]
public void Try_GetHistoryByProductId_WhenHaveRecords_Test()
{
var product = InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), _manufacturer.Id, "name 1");
InsertProductHistoryToDatabaseAndReturn(product.Id, 20, DateTime.UtcNow.AddDays(-1));
InsertProductHistoryToDatabaseAndReturn(product.Id, 30, DateTime.UtcNow.AddMinutes(-10));
InsertProductHistoryToDatabaseAndReturn(product.Id, 40, DateTime.UtcNow.AddDays(1));
var list = _productStorageContract.GetHistoryByProductId(product.Id);
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(3));
}
[Test]
public void Try_GetHistoryByProductId_WhenNoRecords_Test()
{
var product = InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), _manufacturer.Id, "name 1");
InsertProductHistoryToDatabaseAndReturn(product.Id, 20, DateTime.UtcNow.AddDays(-1));
InsertProductHistoryToDatabaseAndReturn(product.Id, 30, DateTime.UtcNow.AddMinutes(-10));
InsertProductHistoryToDatabaseAndReturn(product.Id, 40, DateTime.UtcNow.AddDays(1));
var list = _productStorageContract.GetHistoryByProductId(Guid.NewGuid().ToString());
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
}
[Test]
public void Try_GetElementById_WhenHaveRecord_Test()
{
var product = InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), _manufacturer.Id);
AssertElement(_productStorageContract.GetElementById(product.Id), product);
}
[Test]
public void Try_GetElementById_WhenNoRecord_Test()
{
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), _manufacturer.Id);
Assert.That(() => _productStorageContract.GetElementById(Guid.NewGuid().ToString()), Is.Null);
}
[Test]
public void Try_GetElementById_WhenRecordHasDeleted_Test()
{
var product = InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), _manufacturer.Id, isDeleted: true);
Assert.That(() => _productStorageContract.GetElementById(product.Id), Is.Null);
}
[Test]
public void Try_GetElementByName_WhenHaveRecord_Test()
{
var product = InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), _manufacturer.Id);
AssertElement(_productStorageContract.GetElementByName(product.ProductName), product);
}
[Test]
public void Try_GetElementByName_WhenNoRecord_Test()
{
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), _manufacturer.Id);
Assert.That(() => _productStorageContract.GetElementByName("name"), Is.Null);
}
[Test]
public void Try_GetElementByName_WhenRecordHasDeleted_Test()
{
var product = InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), _manufacturer.Id, isDeleted: true);
Assert.That(() => _productStorageContract.GetElementById(product.ProductName), Is.Null);
}
[Test]
public void Try_AddElement_Test()
{
var product = CreateModel(Guid.NewGuid().ToString(), _manufacturer.Id, isDeleted: false);
_productStorageContract.AddElement(product);
AssertElement(GetProductFromDatabaseById(product.Id), product);
}
[Test]
public void Try_AddElement_WhenIsDeletedIsTrue_Test()
{
var product = CreateModel(Guid.NewGuid().ToString(), _manufacturer.Id, isDeleted: true);
Assert.That(() => _productStorageContract.AddElement(product), Throws.Nothing);
AssertElement(GetProductFromDatabaseById(product.Id), CreateModel(product.Id, _manufacturer.Id, isDeleted: false));
}
[Test]
public void Try_AddElement_WhenHaveRecordWithSameId_Test()
{
var product = CreateModel(Guid.NewGuid().ToString(), _manufacturer.Id);
InsertProductToDatabaseAndReturn(product.Id, _manufacturer.Id, productName: "name unique");
Assert.That(() => _productStorageContract.AddElement(product), Throws.TypeOf<ElementExistsException>());
}
[Test]
public void Try_AddElement_WhenHaveRecordWithSameName_Test()
{
var product = CreateModel(Guid.NewGuid().ToString(), _manufacturer.Id, "name unique", isDeleted: false);
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), _manufacturer.Id, productName: product.ProductName, isDeleted: false);
Assert.That(() => _productStorageContract.AddElement(product), Throws.TypeOf<ElementExistsException>());
}
[Test]
public void Try_AddElement_WhenHaveRecordWithSameNameButOneWasDeleted_Test()
{
var product = CreateModel(Guid.NewGuid().ToString(), _manufacturer.Id, "name unique", isDeleted: false);
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), _manufacturer.Id, productName: product.ProductName, isDeleted: true);
Assert.That(() => _productStorageContract.AddElement(product), Throws.Nothing);
}
[Test]
public void Try_UpdElement_Test()
{
var product = CreateModel(Guid.NewGuid().ToString(), _manufacturer.Id, isDeleted: false);
InsertProductToDatabaseAndReturn(product.Id, _manufacturer.Id, isDeleted: false);
_productStorageContract.UpdElement(product);
AssertElement(GetProductFromDatabaseById(product.Id), product);
}
[Test]
public void Try_UpdElement_WhenIsDeletedIsTrue_Test()
{
var product = CreateModel(Guid.NewGuid().ToString(), _manufacturer.Id, isDeleted: true);
InsertProductToDatabaseAndReturn(product.Id, _manufacturer.Id, isDeleted: false);
_productStorageContract.UpdElement(product);
AssertElement(GetProductFromDatabaseById(product.Id), CreateModel(product.Id, _manufacturer.Id, isDeleted: false));
}
[Test]
public void Try_UpdElement_WhenNoRecordWithThisId_Test()
{
Assert.That(() => _productStorageContract.UpdElement(CreateModel(Guid.NewGuid().ToString(), _manufacturer.Id)), Throws.TypeOf<ElementNotFoundException>());
}
[Test]
public void Try_UpdElement_WhenHaveRecordWithSameName_Test()
{
var product = CreateModel(Guid.NewGuid().ToString(), _manufacturer.Id, "name unique", isDeleted: false);
InsertProductToDatabaseAndReturn(product.Id, _manufacturer.Id, productName: "name");
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), _manufacturer.Id, productName: product.ProductName);
Assert.That(() => _productStorageContract.UpdElement(product), Throws.TypeOf<ElementExistsException>());
}
[Test]
public void Try_UpdElement_WhenHaveRecordWithSameNameButOneWasDeleted_Test()
{
var product = CreateModel(Guid.NewGuid().ToString(), _manufacturer.Id, "name unique", isDeleted: false);
InsertProductToDatabaseAndReturn(product.Id, _manufacturer.Id, productName: "name");
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), _manufacturer.Id, productName: product.ProductName, isDeleted: true);
Assert.That(() => _productStorageContract.UpdElement(product), Throws.Nothing);
}
[Test]
public void Try_UpdElement_WhenRecordWasDeleted_Test()
{
var product = CreateModel(Guid.NewGuid().ToString(), _manufacturer.Id);
InsertProductToDatabaseAndReturn(product.Id, _manufacturer.Id, isDeleted: true);
Assert.That(() => _productStorageContract.UpdElement(product), Throws.TypeOf<ElementNotFoundException>());
}
[Test]
public void Try_DelElement_Test()
{
var product = InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), _manufacturer.Id, isDeleted: false);
_productStorageContract.DelElement(product.Id);
var element = GetProductFromDatabaseById(product.Id);
Assert.Multiple(() =>
{
Assert.That(element, Is.Not.Null);
Assert.That(element!.IsDeleted);
});
}
[Test]
public void Try_DelElement_WhenNoRecordWithThisId_Test()
{
Assert.That(() => _productStorageContract.DelElement(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
}
[Test]
public void Try_DelElement_WhenRecordWasDeleted_Test()
{
var product = InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), _manufacturer.Id, isDeleted: true);
Assert.That(() => _productStorageContract.DelElement(product.Id), Throws.TypeOf<ElementNotFoundException>());
}
private Manufacturer InsertManufacturerToDatabaseAndReturn(string manufacturerName = "name")
{
var manufacrurer = new Manufacturer() { Id = Guid.NewGuid().ToString(), ManufacturerName = manufacturerName };
CatHasPawsDbContext.Manufacturers.Add(manufacrurer);
CatHasPawsDbContext.SaveChanges();
return manufacrurer;
}
private Product InsertProductToDatabaseAndReturn(string id, string manufacturerId, string productName = "test", ProductType productType = ProductType.Feed, double price = 1, bool isDeleted = false)
{
var product = new Product() { Id = id, ManufacturerId = manufacturerId, ProductName = productName, ProductType = productType, Price = price, IsDeleted = isDeleted };
CatHasPawsDbContext.Products.Add(product);
CatHasPawsDbContext.SaveChanges();
return product;
}
private ProductHistory InsertProductHistoryToDatabaseAndReturn(string productId, double price, DateTime changeDate)
{
var productHistory = new ProductHistory() { Id = Guid.NewGuid().ToString(), ProductId = productId, OldPrice = price, ChangeDate = changeDate };
CatHasPawsDbContext.ProductHistories.Add(productHistory);
CatHasPawsDbContext.SaveChanges();
return productHistory;
}
private static void AssertElement(ProductDataModel? actual, Product expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.Id, Is.EqualTo(expected.Id));
Assert.That(actual.ManufacturerId, Is.EqualTo(expected.ManufacturerId));
Assert.That(actual.ProductName, Is.EqualTo(expected.ProductName));
Assert.That(actual.ProductType, Is.EqualTo(expected.ProductType));
Assert.That(actual.Price, Is.EqualTo(expected.Price));
Assert.That(actual.IsDeleted, Is.EqualTo(expected.IsDeleted));
});
}
private static ProductDataModel CreateModel(string id, string manufacturerId, string productName = "test", ProductType productType = ProductType.Feed, double price = 1, bool isDeleted = false)
=> new(id, productName, productType, manufacturerId, price, isDeleted);
private Product? GetProductFromDatabaseById(string id) => CatHasPawsDbContext.Products.FirstOrDefault(x => x.Id == id);
private static void AssertElement(Product? actual, ProductDataModel expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.Id, Is.EqualTo(expected.Id));
Assert.That(actual.ManufacturerId, Is.EqualTo(expected.ManufacturerId));
Assert.That(actual.ProductName, Is.EqualTo(expected.ProductName));
Assert.That(actual.ProductType, Is.EqualTo(expected.ProductType));
Assert.That(actual.Price, Is.EqualTo(expected.Price));
Assert.That(actual.IsDeleted, Is.EqualTo(expected.IsDeleted));
});
}
}

View File

@@ -0,0 +1,148 @@
using CatHasPawsContratcs.DataModels;
using CatHasPawsDatabase.Implementations;
using CatHasPawsDatabase.Models;
using Microsoft.EntityFrameworkCore;
namespace CatHasPawsTests.StoragesContracts;
[TestFixture]
internal class SalaryStorageContractTests : BaseStorageContractTest
{
private SalaryStorageContract _salaryStorageContract;
private Worker _worker;
[SetUp]
public void SetUp()
{
_salaryStorageContract = new SalaryStorageContract(CatHasPawsDbContext);
_worker = InsertWorkerToDatabaseAndReturn();
}
[TearDown]
public void TearDown()
{
CatHasPawsDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Salaries\" CASCADE;");
CatHasPawsDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Workers\" CASCADE;");
}
[Test]
public void Try_GetList_WhenHaveRecords_Test()
{
var salary = InsertSalaryToDatabaseAndReturn(_worker.Id, workerSalary: 100);
InsertSalaryToDatabaseAndReturn(_worker.Id);
InsertSalaryToDatabaseAndReturn(_worker.Id);
var list = _salaryStorageContract.GetList(DateTime.UtcNow.AddDays(-10), DateTime.UtcNow.AddDays(10));
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(3));
AssertElement(list.First(), salary);
}
[Test]
public void Try_GetList_WhenNoRecords_Test()
{
var list = _salaryStorageContract.GetList(DateTime.UtcNow.AddDays(-10), DateTime.UtcNow.AddDays(10));
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.Empty);
}
[Test]
public void Try_GetList_OnlyInDatePeriod_Test()
{
InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate: DateTime.UtcNow.AddDays(-2));
InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate: DateTime.UtcNow.AddDays(-1).AddMinutes(-5));
InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate: DateTime.UtcNow.AddDays(-1).AddMinutes(5));
InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate: DateTime.UtcNow.AddDays(1).AddMinutes(-5));
InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate: DateTime.UtcNow.AddDays(1).AddMinutes(5));
InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate: DateTime.UtcNow.AddDays(-2));
var list = _salaryStorageContract.GetList(DateTime.UtcNow.AddDays(-1), DateTime.UtcNow.AddDays(1));
Assert.That(list, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(list, Has.Count.EqualTo(2));
});
}
[Test]
public void Try_GetList_ByWorker_Test()
{
var worker = InsertWorkerToDatabaseAndReturn("name 2");
InsertSalaryToDatabaseAndReturn(_worker.Id);
InsertSalaryToDatabaseAndReturn(_worker.Id);
InsertSalaryToDatabaseAndReturn(worker.Id);
var list = _salaryStorageContract.GetList(DateTime.UtcNow.AddDays(-1), DateTime.UtcNow.AddDays(1), _worker.Id);
Assert.That(list, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(list, Has.Count.EqualTo(2));
Assert.That(list.All(x => x.WorkerId == _worker.Id));
});
}
[Test]
public void Try_GetList_ByWorkerOnlyInDatePeriod_Test()
{
var worker = InsertWorkerToDatabaseAndReturn("name 2");
InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate: DateTime.UtcNow.AddDays(-2));
InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate: DateTime.UtcNow.AddDays(-1).AddMinutes(5));
InsertSalaryToDatabaseAndReturn(worker.Id, salaryDate: DateTime.UtcNow.AddDays(-1).AddMinutes(5));
InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate: DateTime.UtcNow.AddDays(1).AddMinutes(-5));
InsertSalaryToDatabaseAndReturn(worker.Id, salaryDate: DateTime.UtcNow.AddDays(1).AddMinutes(-5));
InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate: DateTime.UtcNow.AddDays(-2));
var list = _salaryStorageContract.GetList(DateTime.UtcNow.AddDays(-1), DateTime.UtcNow.AddDays(1), _worker.Id);
Assert.That(list, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(list, Has.Count.EqualTo(2));
Assert.That(list.All(x => x.WorkerId == _worker.Id));
});
}
[Test]
public void Try_AddElement_Test()
{
var salary = CreateModel(_worker.Id);
_salaryStorageContract.AddElement(salary);
AssertElement(GetSalaryFromDatabaseByWorkerId(_worker.Id), salary);
}
private Worker InsertWorkerToDatabaseAndReturn(string workerFIO = "fio")
{
var worker = new Worker() { Id = Guid.NewGuid().ToString(), PostId = Guid.NewGuid().ToString(), FIO = workerFIO, IsDeleted = false };
CatHasPawsDbContext.Workers.Add(worker);
CatHasPawsDbContext.SaveChanges();
return worker;
}
private Salary InsertSalaryToDatabaseAndReturn(string workerId, double workerSalary = 1, DateTime? salaryDate = null)
{
var salary = new Salary() { WorkerId = workerId, WorkerSalary = workerSalary, SalaryDate = salaryDate ?? DateTime.UtcNow };
CatHasPawsDbContext.Salaries.Add(salary);
CatHasPawsDbContext.SaveChanges();
return salary;
}
private static void AssertElement(SalaryDataModel? actual, Salary expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.WorkerId, Is.EqualTo(expected.WorkerId));
Assert.That(actual.Salary, Is.EqualTo(expected.WorkerSalary));
});
}
private static SalaryDataModel CreateModel(string workerId, double workerSalary = 1, DateTime? salaryDate = null)
=> new(workerId, salaryDate ?? DateTime.UtcNow, workerSalary);
private Salary? GetSalaryFromDatabaseByWorkerId(string id) => CatHasPawsDbContext.Salaries.FirstOrDefault(x => x.WorkerId == id);
private static void AssertElement(Salary? actual, SalaryDataModel expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.WorkerId, Is.EqualTo(expected.WorkerId));
Assert.That(actual.WorkerSalary, Is.EqualTo(expected.Salary));
});
}
}

View File

@@ -0,0 +1,311 @@
using CatHasPawsContratcs.DataModels;
using CatHasPawsContratcs.Enums;
using CatHasPawsContratcs.Exceptions;
using CatHasPawsDatabase.Implementations;
using CatHasPawsDatabase.Models;
using Microsoft.EntityFrameworkCore;
namespace CatHasPawsTests.StoragesContracts;
[TestFixture]
internal class SaleStorageContractTests : BaseStorageContractTest
{
private SaleStorageContract _saletStorageContract;
private Buyer _buyer;
private Worker _worker;
private Product _product;
private Manufacturer _manufacturer;
[SetUp]
public void SetUp()
{
_saletStorageContract = new SaleStorageContract(CatHasPawsDbContext);
_manufacturer = InsertManufacturerToDatabaseAndReturn();
_buyer = InsertBuyerToDatabaseAndReturn();
_worker = InsertWorkerToDatabaseAndReturn();
_product = InsertProductToDatabaseAndReturn();
}
[TearDown]
public void TearDown()
{
CatHasPawsDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Sales\" CASCADE;");
CatHasPawsDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Buyers\" CASCADE;");
CatHasPawsDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Workers\" CASCADE;");
CatHasPawsDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Products\" CASCADE;");
CatHasPawsDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Manufacturers\" CASCADE;");
}
[Test]
public void Try_GetList_WhenHaveRecords_Test()
{
var sale = InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, products: [(_product.Id, 1)]);
InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, products: [(_product.Id, 5)]);
InsertSaleToDatabaseAndReturn(_worker.Id, null, products: [(_product.Id, 10)]);
var list = _saletStorageContract.GetList();
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(3));
AssertElement(list.First(x => x.Id == sale.Id), sale);
}
[Test]
public void Try_GetList_WhenNoRecords_Test()
{
var list = _saletStorageContract.GetList();
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.Empty);
}
[Test]
public void Try_GetList_ByPeriod_Test()
{
InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(-3), products: [(_product.Id, 1)]);
InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(3), products: [(_product.Id, 1)]);
InsertSaleToDatabaseAndReturn(_worker.Id, null, saleDate: DateTime.UtcNow.AddDays(1).AddMinutes(-3), products: [(_product.Id, 1)]);
InsertSaleToDatabaseAndReturn(_worker.Id, null, saleDate: DateTime.UtcNow.AddDays(1).AddMinutes(3), products: [(_product.Id, 1)]);
var list = _saletStorageContract.GetList(startDate: DateTime.UtcNow.AddDays(-1), endDate: DateTime.UtcNow.AddDays(1));
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(2));
}
[Test]
public void Try_GetList_ByWorkerId_Test()
{
var worker = InsertWorkerToDatabaseAndReturn("Other worker");
InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, products: [(_product.Id, 1)]);
InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, products: [(_product.Id, 1)]);
InsertSaleToDatabaseAndReturn(worker.Id, null, products: [(_product.Id, 1)]);
var list = _saletStorageContract.GetList(workerId: _worker.Id);
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(2));
Assert.That(list.All(x => x.WorkerId == _worker.Id));
}
[Test]
public void Try_GetList_ByBuyerId_Test()
{
var buyer = InsertBuyerToDatabaseAndReturn("Other fio", "+8-888-888-88-88");
InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, products: [(_product.Id, 1)]);
InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, products: [(_product.Id, 1)]);
InsertSaleToDatabaseAndReturn(_worker.Id, buyer.Id, products: [(_product.Id, 1)]);
InsertSaleToDatabaseAndReturn(_worker.Id, null, products: [(_product.Id, 1)]);
var list = _saletStorageContract.GetList(buyerId: _buyer.Id);
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(2));
Assert.That(list.All(x => x.BuyerId == _buyer.Id));
}
[Test]
public void Try_GetList_ByProductId_Test()
{
var product = InsertProductToDatabaseAndReturn("Other name");
InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, products: [(_product.Id, 5)]);
InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, products: [(_product.Id, 1), (product.Id, 4)]);
InsertSaleToDatabaseAndReturn(_worker.Id, null, products: [(product.Id, 1)]);
InsertSaleToDatabaseAndReturn(_worker.Id, null, products: [(product.Id, 1), (_product.Id, 1)]);
var list = _saletStorageContract.GetList(productId: _product.Id);
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(3));
Assert.That(list.All(x => x.Products.Any(y => y.ProductId == _product.Id)));
}
[Test]
public void Try_GetList_ByAllParameters_Test()
{
var worker = InsertWorkerToDatabaseAndReturn("Other worker");
var buyer = InsertBuyerToDatabaseAndReturn("Other fio", "+8-888-888-88-88");
var product = InsertProductToDatabaseAndReturn("Other name");
InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(-3), products: [(_product.Id, 1)]);
InsertSaleToDatabaseAndReturn(worker.Id, null, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(3), products: [(_product.Id, 1)]);
InsertSaleToDatabaseAndReturn(worker.Id, _buyer.Id, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(3), products: [(_product.Id, 1)]);
InsertSaleToDatabaseAndReturn(worker.Id, _buyer.Id, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(3), products: [(product.Id, 1)]);
InsertSaleToDatabaseAndReturn(_worker.Id, buyer.Id, saleDate: DateTime.UtcNow.AddDays(1).AddMinutes(-3), products: [(_product.Id, 1)]);
InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, saleDate: DateTime.UtcNow.AddDays(1).AddMinutes(-3), products: [(product.Id, 1)]);
InsertSaleToDatabaseAndReturn(worker.Id, null, saleDate: DateTime.UtcNow.AddDays(1).AddMinutes(-3), products: [(_product.Id, 1)]);
var list = _saletStorageContract.GetList(startDate: DateTime.UtcNow.AddDays(-1), endDate: DateTime.UtcNow.AddDays(1), workerId: _worker.Id, buyerId: _buyer.Id, productId: product.Id);
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(1));
}
[Test]
public void Try_GetElementById_WhenHaveRecord_Test()
{
var sale = InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, products: [(_product.Id, 1)]);
AssertElement(_saletStorageContract.GetElementById(sale.Id), sale);
}
[Test]
public void Try_GetElementById_WhenNoRecord_Test()
{
InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, products: [(_product.Id, 1)]);
Assert.That(() => _saletStorageContract.GetElementById(Guid.NewGuid().ToString()), Is.Null);
}
[Test]
public void Try_GetElementById_WhenRecordHasCanceled_Test()
{
var sale = InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, products: [(_product.Id, 1)], isCancel: true);
AssertElement(_saletStorageContract.GetElementById(sale.Id), sale);
}
[Test]
public void Try_AddElement_Test()
{
var sale = CreateModel(Guid.NewGuid().ToString(), _worker.Id, _buyer.Id, 1, DiscountType.RegularCustomer, 1, false, [_product.Id]);
_saletStorageContract.AddElement(sale);
AssertElement(GetSaleFromDatabaseById(sale.Id), sale);
}
[Test]
public void Try_AddElement_WhenIsDeletedIsTrue_Test()
{
var sale = CreateModel(Guid.NewGuid().ToString(), _worker.Id, _buyer.Id, 1, DiscountType.RegularCustomer, 1, true, [_product.Id]);
Assert.That(() => _saletStorageContract.AddElement(sale), Throws.Nothing);
AssertElement(GetSaleFromDatabaseById(sale.Id), CreateModel(sale.Id, _worker.Id, _buyer.Id, 1, DiscountType.RegularCustomer, 1, false, [_product.Id]));
}
[Test]
public void Try_DelElement_Test()
{
var sale = InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, products: [(_product.Id, 1)], isCancel: false);
_saletStorageContract.DelElement(sale.Id);
var element = GetSaleFromDatabaseById(sale.Id);
Assert.Multiple(() =>
{
Assert.That(element, Is.Not.Null);
Assert.That(element!.IsCancel);
});
}
[Test]
public void Try_DelElement_WhenNoRecordWithThisId_Test()
{
Assert.That(() => _saletStorageContract.DelElement(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
}
[Test]
public void Try_DelElement_WhenRecordWasCanceled_Test()
{
var sale = InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, products: [(_product.Id, 1)], isCancel: true);
Assert.That(() => _saletStorageContract.DelElement(sale.Id), Throws.TypeOf<ElementDeletedException>());
}
private Buyer InsertBuyerToDatabaseAndReturn(string fio = "test", string phoneNumber = "+7-777-777-77-77")
{
var buyer = new Buyer() { Id = Guid.NewGuid().ToString(), FIO = fio, PhoneNumber = phoneNumber, DiscountSize = 10 };
CatHasPawsDbContext.Buyers.Add(buyer);
CatHasPawsDbContext.SaveChanges();
return buyer;
}
private Worker InsertWorkerToDatabaseAndReturn(string fio = "test")
{
var worker = new Worker() { Id = Guid.NewGuid().ToString(), FIO = fio, PostId = Guid.NewGuid().ToString() };
CatHasPawsDbContext.Workers.Add(worker);
CatHasPawsDbContext.SaveChanges();
return worker;
}
private Manufacturer InsertManufacturerToDatabaseAndReturn()
{
var manufacrurer = new Manufacturer() { Id = Guid.NewGuid().ToString(), ManufacturerName = "name" };
CatHasPawsDbContext.Manufacturers.Add(manufacrurer);
CatHasPawsDbContext.SaveChanges();
return manufacrurer;
}
private Product InsertProductToDatabaseAndReturn(string productName = "test", ProductType productType = ProductType.Feed, double price = 1, bool isDeleted = false)
{
var product = new Product() { Id = Guid.NewGuid().ToString(), ManufacturerId = _manufacturer.Id, ProductName = productName, ProductType = productType, Price = price, IsDeleted = isDeleted };
CatHasPawsDbContext.Products.Add(product);
CatHasPawsDbContext.SaveChanges();
return product;
}
private Sale InsertSaleToDatabaseAndReturn(string workerId, string? buyerId, DateTime? saleDate = null, double sum = 1, DiscountType discountType = DiscountType.OnSale, double discount = 0, bool isCancel = false, List<(string, int)>? products = null)
{
var sale = new Sale() { WorkerId = workerId, BuyerId = buyerId, SaleDate = saleDate ?? DateTime.UtcNow, Sum = sum, DiscountType = discountType, Discount = discount, IsCancel = isCancel, SaleProducts = [] };
if (products is not null)
{
foreach (var elem in products)
{
sale.SaleProducts.Add(new SaleProduct { ProductId = elem.Item1, SaleId = sale.Id, Count = elem.Item2 });
}
}
CatHasPawsDbContext.Sales.Add(sale);
CatHasPawsDbContext.SaveChanges();
return sale;
}
private static void AssertElement(SaleDataModel? actual, Sale expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.Id, Is.EqualTo(expected.Id));
Assert.That(actual.WorkerId, Is.EqualTo(expected.WorkerId));
Assert.That(actual.BuyerId, Is.EqualTo(expected.BuyerId));
Assert.That(actual.DiscountType, Is.EqualTo(expected.DiscountType));
Assert.That(actual.Discount, Is.EqualTo(expected.Discount));
Assert.That(actual.IsCancel, Is.EqualTo(expected.IsCancel));
});
if (expected.SaleProducts is not null)
{
Assert.That(actual.Products, Is.Not.Null);
Assert.That(actual.Products, Has.Count.EqualTo(expected.SaleProducts.Count));
for (int i = 0; i < actual.Products.Count; ++i)
{
Assert.Multiple(() =>
{
Assert.That(actual.Products[i].ProductId, Is.EqualTo(expected.SaleProducts[i].ProductId));
Assert.That(actual.Products[i].Count, Is.EqualTo(expected.SaleProducts[i].Count));
});
}
}
else
{
Assert.That(actual.Products, Is.Null);
}
}
private static SaleDataModel CreateModel(string id, string workerId, string? buyerId, double sum, DiscountType discountType, double discount, bool isCancel, List<string> productIds)
{
var products = productIds.Select(x => new SaleProductDataModel(id, x, 1)).ToList();
return new(id, workerId, buyerId, sum, discountType, discount, isCancel, products);
}
private Sale? GetSaleFromDatabaseById(string id) => CatHasPawsDbContext.Sales.Include(x => x.SaleProducts).FirstOrDefault(x => x.Id == id);
private static void AssertElement(Sale? actual, SaleDataModel expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.Id, Is.EqualTo(expected.Id));
Assert.That(actual.WorkerId, Is.EqualTo(expected.WorkerId));
Assert.That(actual.BuyerId, Is.EqualTo(expected.BuyerId));
Assert.That(actual.DiscountType, Is.EqualTo(expected.DiscountType));
Assert.That(actual.Discount, Is.EqualTo(expected.Discount));
Assert.That(actual.IsCancel, Is.EqualTo(expected.IsCancel));
});
if (expected.Products is not null)
{
Assert.That(actual.SaleProducts, Is.Not.Null);
Assert.That(actual.SaleProducts, Has.Count.EqualTo(expected.Products.Count));
for (int i = 0; i < actual.SaleProducts.Count; ++i)
{
Assert.Multiple(() =>
{
Assert.That(actual.SaleProducts[i].ProductId, Is.EqualTo(expected.Products[i].ProductId));
Assert.That(actual.SaleProducts[i].Count, Is.EqualTo(expected.Products[i].Count));
});
}
}
else
{
Assert.That(actual.SaleProducts, Is.Null);
}
}
}

View File

@@ -0,0 +1,225 @@
using CatHasPawsContratcs.DataModels;
using CatHasPawsContratcs.Exceptions;
using CatHasPawsDatabase.Implementations;
using CatHasPawsDatabase.Models;
using Microsoft.EntityFrameworkCore;
namespace CatHasPawsTests.StoragesContracts;
[TestFixture]
internal class WorkerStorageContractTests : BaseStorageContractTest
{
private WorkerStorageContract _workerStorageContract;
[SetUp]
public void SetUp()
{
_workerStorageContract = new WorkerStorageContract(CatHasPawsDbContext);
}
[TearDown]
public void TearDown()
{
CatHasPawsDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Workers\" CASCADE;");
}
[Test]
public void Try_GetList_WhenHaveRecords_Test()
{
var worker = InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 1");
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 2");
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 3");
var list = _workerStorageContract.GetList();
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(3));
AssertElement(list.First(), worker);
}
[Test]
public void Try_GetList_WhenNoRecords_Test()
{
var list = _workerStorageContract.GetList();
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.Empty);
}
[Test]
public void Try_GetList_ByPostId_Test()
{
var postId = Guid.NewGuid().ToString();
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 1", postId);
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 2", postId);
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 3");
var list = _workerStorageContract.GetList(postId: postId);
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(2));
Assert.That(list.All(x => x.PostId == postId));
}
[Test]
public void Try_GetList_ByBirthDate_Test()
{
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 1", birthDate: DateTime.UtcNow.AddYears(-25));
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 2", birthDate: DateTime.UtcNow.AddYears(-21));
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 3", birthDate: DateTime.UtcNow.AddYears(-20));
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 4", birthDate: DateTime.UtcNow.AddYears(-19));
var list = _workerStorageContract.GetList(fromBirthDate: DateTime.UtcNow.AddYears(-21).AddMinutes(-1), toBirthDate: DateTime.UtcNow.AddYears(-20).AddMinutes(1));
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(2));
}
[Test]
public void Try_GetList_ByEmploymentDate_Test()
{
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 1", employmentDate: DateTime.UtcNow.AddDays(-2));
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 2", employmentDate: DateTime.UtcNow.AddDays(-1));
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 3", employmentDate: DateTime.UtcNow.AddDays(1));
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 4", employmentDate: DateTime.UtcNow.AddDays(2));
var list = _workerStorageContract.GetList(fromEmploymentDate: DateTime.UtcNow.AddDays(-1).AddMinutes(-1), toEmploymentDate: DateTime.UtcNow.AddDays(1).AddMinutes(1));
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(2));
}
[Test]
public void Try_GetList_ByAllParameters_Test()
{
var postId = Guid.NewGuid().ToString();
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 1", postId, birthDate: DateTime.UtcNow.AddYears(-25), employmentDate: DateTime.UtcNow.AddDays(-2));
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 2", postId, birthDate: DateTime.UtcNow.AddYears(-22), employmentDate: DateTime.UtcNow.AddDays(-1));
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 3", postId, birthDate: DateTime.UtcNow.AddYears(-21), employmentDate: DateTime.UtcNow.AddDays(-1));
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 4", birthDate: DateTime.UtcNow.AddYears(-20), employmentDate: DateTime.UtcNow.AddDays(1));
var list = _workerStorageContract.GetList(postId: postId, fromBirthDate: DateTime.UtcNow.AddYears(-21).AddMinutes(-1), toBirthDate: DateTime.UtcNow.AddYears(-20).AddMinutes(1), fromEmploymentDate: DateTime.UtcNow.AddDays(-1).AddMinutes(-1), toEmploymentDate: DateTime.UtcNow.AddDays(1).AddMinutes(1));
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(1));
}
[Test]
public void Try_GetElementById_WhenHaveRecord_Test()
{
var worker = InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString());
AssertElement(_workerStorageContract.GetElementById(worker.Id), worker);
}
[Test]
public void Try_GetElementById_WhenNoRecord_Test()
{
Assert.That(() => _workerStorageContract.GetElementById(Guid.NewGuid().ToString()), Is.Null);
}
[Test]
public void Try_GetElementByFIO_WhenHaveRecord_Test()
{
var worker = InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString());
AssertElement(_workerStorageContract.GetElementByFIO(worker.FIO), worker);
}
[Test]
public void Try_GetElementByFIO_WhenNoRecord_Test()
{
Assert.That(() => _workerStorageContract.GetElementByFIO("New Fio"), Is.Null);
}
[Test]
public void Try_AddElement_Test()
{
var worker = CreateModel(Guid.NewGuid().ToString());
_workerStorageContract.AddElement(worker);
AssertElement(GetWorkerFromDatabase(worker.Id), worker);
}
[Test]
public void Try_AddElement_WhenHaveRecordWithSameId_Test()
{
var worker = CreateModel(Guid.NewGuid().ToString());
InsertWorkerToDatabaseAndReturn(worker.Id);
Assert.That(() => _workerStorageContract.AddElement(worker), Throws.TypeOf<ElementExistsException>());
}
[Test]
public void Try_UpdElement_Test()
{
var worker = CreateModel(Guid.NewGuid().ToString(), "New Fio");
InsertWorkerToDatabaseAndReturn(worker.Id);
_workerStorageContract.UpdElement(worker);
AssertElement(GetWorkerFromDatabase(worker.Id), worker);
}
[Test]
public void Try_UpdElement_WhenNoRecordWithThisId_Test()
{
Assert.That(() => _workerStorageContract.UpdElement(CreateModel(Guid.NewGuid().ToString())), Throws.TypeOf<ElementNotFoundException>());
}
[Test]
public void Try_UpdElement_WhenNoRecordWasDeleted_Test()
{
var worker = CreateModel(Guid.NewGuid().ToString());
InsertWorkerToDatabaseAndReturn(worker.Id, isDeleted: true);
Assert.That(() => _workerStorageContract.UpdElement(worker), Throws.TypeOf<ElementNotFoundException>());
}
[Test]
public void Try_DelElement_Test()
{
var worker = InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString());
_workerStorageContract.DelElement(worker.Id);
var element = GetWorkerFromDatabase(worker.Id);
Assert.That(element, Is.Not.Null);
Assert.That(element.IsDeleted);
}
[Test]
public void Try_DelElement_WhenNoRecordWithThisId_Test()
{
Assert.That(() => _workerStorageContract.DelElement(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
}
[Test]
public void Try_DelElement_WhenNoRecordWasDeleted_Test()
{
var worker = CreateModel(Guid.NewGuid().ToString());
InsertWorkerToDatabaseAndReturn(worker.Id, isDeleted: true);
Assert.That(() => _workerStorageContract.DelElement(worker.Id), Throws.TypeOf<ElementNotFoundException>());
}
private Worker InsertWorkerToDatabaseAndReturn(string id, string fio = "test", string? postId = null, DateTime? birthDate = null, DateTime? employmentDate = null, bool isDeleted = false)
{
var worker = new Worker() { Id = id, FIO = fio, PostId = postId ?? Guid.NewGuid().ToString(), BirthDate = birthDate ?? DateTime.UtcNow.AddYears(-20), EmploymentDate = employmentDate ?? DateTime.UtcNow, IsDeleted = isDeleted };
CatHasPawsDbContext.Workers.Add(worker);
CatHasPawsDbContext.SaveChanges();
return worker;
}
private static void AssertElement(WorkerDataModel? actual, Worker expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.Id, Is.EqualTo(expected.Id));
Assert.That(actual.PostId, Is.EqualTo(expected.PostId));
Assert.That(actual.FIO, Is.EqualTo(expected.FIO));
Assert.That(actual.BirthDate, Is.EqualTo(expected.BirthDate));
Assert.That(actual.EmploymentDate, Is.EqualTo(expected.EmploymentDate));
Assert.That(actual.IsDeleted, Is.EqualTo(expected.IsDeleted));
});
}
private static WorkerDataModel CreateModel(string id, string fio = "fio", string? postId = null, DateTime? birthDate = null, DateTime? employmentDate = null, bool isDeleted = false) =>
new(id, fio, postId ?? Guid.NewGuid().ToString(), birthDate ?? DateTime.UtcNow.AddYears(-20), employmentDate ?? DateTime.UtcNow, isDeleted);
private Worker? GetWorkerFromDatabase(string id) => CatHasPawsDbContext.Workers.FirstOrDefault(x => x.Id == id);
private static void AssertElement(Worker? actual, WorkerDataModel expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.Id, Is.EqualTo(expected.Id));
Assert.That(actual.PostId, Is.EqualTo(expected.PostId));
Assert.That(actual.FIO, Is.EqualTo(expected.FIO));
Assert.That(actual.BirthDate, Is.EqualTo(expected.BirthDate));
Assert.That(actual.EmploymentDate, Is.EqualTo(expected.EmploymentDate));
Assert.That(actual.IsDeleted, Is.EqualTo(expected.IsDeleted));
});
}
}

View File

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

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.12.35527.113 d17.12
VisualStudioVersion = 17.12.35527.113
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CatHasPawsContratcs", "CatHasPawsContratcs\CatHasPawsContratcs.csproj", "{26AF44BA-F11C-4F69-9815-5F7218D3E779}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CatHasPawsTests", "CatHasPawsTests\CatHasPawsTests.csproj", "{18708BC0-17A1-4F6D-98FD-CECE1BDE3D92}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CatHasPawsBusinessLogic", "CatHasPawsBusinessLogic\CatHasPawsBusinessLogic.csproj", "{42EEABA6-5F1B-4552-8DDF-9974A2B89BCF}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CatHasPawsDatabase", "CatHasPawsDatabase\CatHasPawsDatabase.csproj", "{54BFB74B-3DA5-47C7-BF70-E8F6C3FFA334}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@@ -15,6 +21,18 @@ Global
{26AF44BA-F11C-4F69-9815-5F7218D3E779}.Debug|Any CPU.Build.0 = Debug|Any CPU
{26AF44BA-F11C-4F69-9815-5F7218D3E779}.Release|Any CPU.ActiveCfg = Release|Any CPU
{26AF44BA-F11C-4F69-9815-5F7218D3E779}.Release|Any CPU.Build.0 = Release|Any CPU
{18708BC0-17A1-4F6D-98FD-CECE1BDE3D92}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{18708BC0-17A1-4F6D-98FD-CECE1BDE3D92}.Debug|Any CPU.Build.0 = Debug|Any CPU
{18708BC0-17A1-4F6D-98FD-CECE1BDE3D92}.Release|Any CPU.ActiveCfg = Release|Any CPU
{18708BC0-17A1-4F6D-98FD-CECE1BDE3D92}.Release|Any CPU.Build.0 = Release|Any CPU
{42EEABA6-5F1B-4552-8DDF-9974A2B89BCF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{42EEABA6-5F1B-4552-8DDF-9974A2B89BCF}.Debug|Any CPU.Build.0 = Debug|Any CPU
{42EEABA6-5F1B-4552-8DDF-9974A2B89BCF}.Release|Any CPU.ActiveCfg = Release|Any CPU
{42EEABA6-5F1B-4552-8DDF-9974A2B89BCF}.Release|Any CPU.Build.0 = Release|Any CPU
{54BFB74B-3DA5-47C7-BF70-E8F6C3FFA334}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{54BFB74B-3DA5-47C7-BF70-E8F6C3FFA334}.Debug|Any CPU.Build.0 = Debug|Any CPU
{54BFB74B-3DA5-47C7-BF70-E8F6C3FFA334}.Release|Any CPU.ActiveCfg = Release|Any CPU
{54BFB74B-3DA5-47C7-BF70-E8F6C3FFA334}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE