2 Commits
lab_1 ... lab_3

Author SHA1 Message Date
bbccb79ebb lab_3 2025-03-19 11:24:57 +04:00
1b4f72f67f lab 2 work 2025-03-18 20:05:36 +04:00
59 changed files with 4457 additions and 12 deletions

View File

@@ -0,0 +1,17 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging" Version="9.0.2" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\DaisiesContracts\DaisiesContracts.csproj" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,115 @@
using DaisiesContracts.BusinessLogicsContracts;
using DaisiesContracts.DataModels;
using DaisiesContracts.Exceptions;
using DaisiesContracts.Extensions;
using DaisiesContracts.StoragesContracts;
using Microsoft.Extensions.Logging;
using System.Text.Json;
namespace DaisiesBusinessLogic.Implementations;
public class BouquetBusinessLogicContract(IBouquetStorageContract bouquetStorageContract, ILogger logger) : IBouquetBusinessLogicContract
{
private readonly ILogger _logger = logger;
private readonly IBouquetStorageContract _bouquetStorageContract = bouquetStorageContract;
public void CancelBouquet(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");
}
_bouquetStorageContract.DelElement(id);
}
public List<BouquetDataModel> GetAllBouquetsByCustomerByPeriod(string customerId, DateTime fromDate, DateTime toDate)
{
_logger.LogInformation("GetAllSales params: {customerId}, {fromDate}, {toDate}", customerId, fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate);
}
if (customerId.IsEmpty())
{
throw new ArgumentNullException(nameof(customerId));
}
if (!customerId.IsGuid())
{
throw new ValidationException("The value in the field customerId is not a unique identifier.");
}
return _bouquetStorageContract.GetList(fromDate, toDate, customerId: customerId) ?? throw new NullListException();
}
public List<BouquetDataModel> GetAllBouquetsByEmployeerByPeriod(string employeerId, DateTime fromDate, DateTime toDate)
{
_logger.LogInformation("GetAllSales params: {employeerId}, {fromDate}, {toDate}", employeerId, fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate);
}
if (employeerId.IsEmpty())
{
throw new ArgumentNullException(nameof(employeerId));
}
if (!employeerId.IsGuid())
{
throw new ValidationException("The value in the field employeerId is not a unique identifier.");
}
return _bouquetStorageContract.GetList(fromDate, toDate, employeeId: employeerId) ?? throw new NullListException();
}
public List<BouquetDataModel> GetAllBouquetsByFlowerByPeriod(string flowerId, DateTime fromDate, DateTime toDate)
{
_logger.LogInformation("GetAllSales params: {flowerId}, {fromDate}, {toDate}", flowerId, fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate);
}
if (flowerId.IsEmpty())
{
throw new ArgumentNullException(nameof(flowerId));
}
if (!flowerId.IsGuid())
{
throw new ValidationException("The value in the field flowerId is not a unique identifier.");
}
return _bouquetStorageContract.GetList(fromDate, toDate, flowerId: flowerId) ?? throw new NullListException();
}
public List<BouquetDataModel> GetAllBouquetsByPeriod(DateTime fromDate, DateTime toDate)
{
_logger.LogInformation("GetAllSales params: {fromDate}, {toDate}", fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate);
}
return _bouquetStorageContract.GetList(fromDate, toDate) ?? throw new NullListException();
}
public BouquetDataModel GetBouquetByData(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 _bouquetStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data);
}
public void InsertBouquet(BouquetDataModel bouquetDataModel)
{
_logger.LogInformation("New data: {json}", JsonSerializer.Serialize(bouquetDataModel));
ArgumentNullException.ThrowIfNull(bouquetDataModel);
bouquetDataModel.Validate();
_bouquetStorageContract.AddElement(bouquetDataModel);
}
}

View File

@@ -0,0 +1,70 @@
using DaisiesContracts.BusinessLogicsContracts;
using DaisiesContracts.DataModels;
using DaisiesContracts.Exceptions;
using DaisiesContracts.Extensions;
using DaisiesContracts.StoragesContracts;
using Microsoft.Extensions.Logging;
using System.Text.Json;
using System.Text.RegularExpressions;
namespace DaisiesBusinessLogic.Implementations;
public class CustomerBusinessLogicContract(ICustomerStorageContract customerStorageContract, ILogger logger) : ICustomerBusinessLogicContract
{
private readonly ILogger _logger = logger;
private readonly ICustomerStorageContract _customerStorageContract = customerStorageContract;
public void DeleteCustomer(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");
}
_customerStorageContract.DelElement(id);
}
public List<CustomerDataModel> GetAllCustomers()
{
_logger.LogInformation("GetAllCustomers");
return _customerStorageContract.GetList() ?? throw new NullListException();
}
public CustomerDataModel GetCustomerByData(string data)
{
_logger.LogInformation("Get element by data: {data}", data);
if (data.IsEmpty())
{
throw new ArgumentNullException(nameof(data));
}
if (data.IsGuid())
{
return _customerStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data);
}
if (Regex.IsMatch(data, @"^((8|\+7)[\- ]?)?(\(?\d{3}\)?[\- ]?)?[\d\- ]{7,10}$"))
{
return _customerStorageContract.GetElementByPhoneNumber(data) ?? throw new ElementNotFoundException(data);
}
return _customerStorageContract.GetElementByFullName(data) ?? throw new ElementNotFoundException(data);
}
public void InsertCustomer(CustomerDataModel customerDataModel)
{
_logger.LogInformation("New data: {json}", JsonSerializer.Serialize(customerDataModel));
ArgumentNullException.ThrowIfNull(customerDataModel);
customerDataModel.Validate();
_customerStorageContract.AddElement(customerDataModel);
}
public void UpdateCustomer(CustomerDataModel customerDataModel)
{
_logger.LogInformation("Update data: {json}", JsonSerializer.Serialize(customerDataModel));
ArgumentNullException.ThrowIfNull(customerDataModel);
customerDataModel.Validate();
_customerStorageContract.UpdElement(customerDataModel);
}
}

View File

@@ -0,0 +1,61 @@
using DaisiesContracts.BusinessLogicsContracts;
using DaisiesContracts.DataModels;
using DaisiesContracts.Exceptions;
using DaisiesContracts.Extensions;
using DaisiesContracts.StoragesContracts;
using Microsoft.Extensions.Logging;
namespace DaisiesBusinessLogic.Implementations;
public class CustomerDiscountBusinessLogicContract(ICustomerDiscountStorageContract customerDiscountStorageContract, IBouquetStorageContract bouquetStorageContract, ICustomerStorageContract customerStorageContract, ILogger logger) : ICustomerDiscountBusinessLogicContract
{
private readonly ILogger _logger = logger;
private readonly ICustomerDiscountStorageContract _customerDiscountStorageContract = customerDiscountStorageContract;
private readonly ICustomerStorageContract _customerStorageContract = customerStorageContract;
private readonly IBouquetStorageContract _bouquetStorageContract = bouquetStorageContract;
public void CalculateDiscountByMounth(DateTime date)
{
_logger.LogInformation("CalculateDiscountByMounth: {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 customers = _customerStorageContract.GetList() ?? throw new NullListException();
foreach (var customer in customers)
{
var sales = _bouquetStorageContract.GetList(startDate, finishDate, customerId: customer.Id)?.Sum(x => x.Items.Count) ??
throw new NullListException();
var salary = sales * 0.1 > 100 ? 100 : sales * 0.1;
_logger.LogDebug("The customer {customerId} was paid a salary of {salary}", customer.Id, salary);
_customerDiscountStorageContract.AddElement(new CustomerDiscountDataModel(customer.Id, DateTime.UtcNow, (decimal)salary));
}
}
public List<CustomerDiscountDataModel> GetAllDiscountsByPeriod(DateTime fromDate, DateTime toDate)
{
_logger.LogInformation("GetAllDiscounts params: {fromDate}, {toDate}", fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate);
}
return _customerDiscountStorageContract.GetList(fromDate, toDate) ?? throw new NullListException();
}
public List<CustomerDiscountDataModel> GetAllDiscountsByPeriodByCustomer(DateTime fromDate, DateTime toDate, string customerId)
{
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate);
}
if (customerId.IsEmpty())
{
throw new ArgumentNullException(nameof(customerId));
}
if (!customerId.IsGuid())
{
throw new ValidationException("The value in the field customerId is not a unique identifier.");
}
_logger.LogInformation("GetAllDiscounts params: {fromDate}, {toDate}, {workerId}", fromDate, toDate, customerId);
return _customerDiscountStorageContract.GetList(fromDate, toDate, customerId) ?? throw new NullListException();
}
}

View File

@@ -0,0 +1,75 @@
using DaisiesContracts.BusinessLogicsContracts;
using DaisiesContracts.DataModels;
using DaisiesContracts.Exceptions;
using DaisiesContracts.Extensions;
using DaisiesContracts.StoragesContracts;
using Microsoft.Extensions.Logging;
using System.Text.Json;
namespace DaisiesBusinessLogic.Implementations;
public class EmployeeBusinessLogicContract(IEmployeeStorageContract employeeStorageContract, ILogger logger) : IEmployeeBusinessLogicContract
{
private readonly ILogger _logger = logger;
private readonly IEmployeeStorageContract _employeeStorageContract = employeeStorageContract;
public void DeleteEmployeer(string id)
{
_logger.LogInformation("Delete by id: {id}", id);
if (id.IsEmpty())
{
throw new ArgumentNullException(nameof(id));
}
if (!id.IsGuid())
{
throw new ValidationException("Id is not a unique identifier");
}
_employeeStorageContract.DelElement(id);
}
public List<EmployeeDataModel> GetAllEmployeers(bool onlyActive = true)
{
_logger.LogInformation("GetAllEmployeers params: {onlyActive}", onlyActive);
return _employeeStorageContract.GetList(onlyActive) ?? throw new NullListException();
}
public List<EmployeeDataModel> GetAllEmployeersByEmploymentDate(DateTime fromDate, DateTime toDate, bool onlyActive = true)
{
_logger.LogInformation("GetAllEmployeers params: {onlyActive}, {fromDate}, {toDate}", onlyActive, fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate);
}
return _employeeStorageContract.GetList(onlyActive, fromEmploymentDate: fromDate, toEmploymentDate: toDate) ?? throw new NullListException();
}
public EmployeeDataModel GetEmployeerByData(string data)
{
_logger.LogInformation("Get element by data: {data}", data);
if (data.IsEmpty())
{
throw new ArgumentNullException(nameof(data));
}
if (data.IsGuid())
{
return _employeeStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data);
}
return _employeeStorageContract.GetElementByFullName(data) ?? throw new ElementNotFoundException(data);
}
public void InsertEmployeer(EmployeeDataModel employeeDataModel)
{
_logger.LogInformation("New data: {json}", JsonSerializer.Serialize(employeeDataModel));
ArgumentNullException.ThrowIfNull(employeeDataModel);
employeeDataModel.Validate();
_employeeStorageContract.AddElement(employeeDataModel);
}
public void UpdateEmployeer(EmployeeDataModel employeeDataModel)
{
_logger.LogInformation("Update data: {json}", JsonSerializer.Serialize(employeeDataModel));
ArgumentNullException.ThrowIfNull(employeeDataModel);
employeeDataModel.Validate();
_employeeStorageContract.UpdElement(employeeDataModel);
}
}

View File

@@ -0,0 +1,65 @@
using DaisiesContracts.BusinessLogicsContracts;
using DaisiesContracts.DataModels;
using DaisiesContracts.Exceptions;
using DaisiesContracts.Extensions;
using DaisiesContracts.StoragesContracts;
using Microsoft.Extensions.Logging;
using System.Text.Json;
namespace DaisiesBusinessLogic.Implementations;
public class FlowerBusinessLogicContract(IFlowerStorageContract flowerStorageContract, ILogger logger) : IFlowerBusinessLogicContract
{
private readonly ILogger _logger = logger;
private readonly IFlowerStorageContract _flowerStorageContract = flowerStorageContract;
public void DeleteFlower(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");
}
_flowerStorageContract.DelElement(id);
}
public List<FlowerDataModel> GetAllFlowers(bool onlyActive = true)
{
_logger.LogInformation("GetAllFlowers params: {onlyActive}", onlyActive);
return _flowerStorageContract.GetList() ?? throw new NullListException();
}
public FlowerDataModel GetFlowerByData(string data)
{
_logger.LogInformation("Get element by data: {data}", data);
if (data.IsEmpty())
{
throw new ArgumentNullException(nameof(data));
}
if (data.IsGuid())
{
return _flowerStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data);
}
return _flowerStorageContract.GetElementByName(data) ?? throw new ElementNotFoundException(data);
}
public void InsertFlower(FlowerDataModel flowerDataModel)
{
_logger.LogInformation("New data: {json}", JsonSerializer.Serialize(flowerDataModel));
ArgumentNullException.ThrowIfNull(flowerDataModel);
flowerDataModel.Validate();
_flowerStorageContract.AddElement(flowerDataModel);
}
public void UpdateFlower(FlowerDataModel flowerDataModel)
{
_logger.LogInformation("Update data: {json}", JsonSerializer.Serialize(flowerDataModel));
ArgumentNullException.ThrowIfNull(flowerDataModel);
flowerDataModel.Validate();
_flowerStorageContract.UpdElement(flowerDataModel);
}
}

View File

@@ -0,0 +1,20 @@
using DaisiesContracts.DataModels;
namespace DaisiesContracts.BusinessLogicsContracts;
public interface IBouquetBusinessLogicContract
{
List<BouquetDataModel> GetAllBouquetsByPeriod(DateTime fromDate, DateTime toDate);
List<BouquetDataModel> GetAllBouquetsByEmployeerByPeriod(string employeerId, DateTime fromDate, DateTime toDate);
List<BouquetDataModel> GetAllBouquetsByCustomerByPeriod(string customerId, DateTime fromDate, DateTime toDate);
List<BouquetDataModel> GetAllBouquetsByFlowerByPeriod(string flowerId, DateTime fromDate, DateTime toDate);
BouquetDataModel GetBouquetByData(string data);
void InsertBouquet(BouquetDataModel bouquetDataModel);
void CancelBouquet(string id);
}

View File

@@ -0,0 +1,16 @@
using DaisiesContracts.DataModels;
namespace DaisiesContracts.BusinessLogicsContracts;
public interface ICustomerBusinessLogicContract
{
List<CustomerDataModel> GetAllCustomers();
CustomerDataModel GetCustomerByData(string data);
void InsertCustomer(CustomerDataModel customerDataModel);
void UpdateCustomer(CustomerDataModel customerDataModel);
void DeleteCustomer(string id);
}

View File

@@ -0,0 +1,12 @@
using DaisiesContracts.DataModels;
namespace DaisiesContracts.BusinessLogicsContracts;
public interface ICustomerDiscountBusinessLogicContract
{
List<CustomerDiscountDataModel> GetAllDiscountsByPeriod(DateTime fromDate, DateTime toDate);
List<CustomerDiscountDataModel> GetAllDiscountsByPeriodByCustomer(DateTime fromDate, DateTime toDate, string customerId);
void CalculateDiscountByMounth(DateTime date);
}

View File

@@ -0,0 +1,18 @@
using DaisiesContracts.DataModels;
namespace DaisiesContracts.BusinessLogicsContracts;
public interface IEmployeeBusinessLogicContract
{
List<EmployeeDataModel> GetAllEmployeers(bool onlyActive = true);
List<EmployeeDataModel> GetAllEmployeersByEmploymentDate(DateTime fromDate, DateTime toDate, bool onlyActive = true);
EmployeeDataModel GetEmployeerByData(string data);
void InsertEmployeer(EmployeeDataModel employeeDataModel);
void UpdateEmployeer(EmployeeDataModel employeeDataModel);
void DeleteEmployeer(string id);
}

View File

@@ -0,0 +1,16 @@
using DaisiesContracts.DataModels;
namespace DaisiesContracts.BusinessLogicsContracts;
public interface IFlowerBusinessLogicContract
{
List<FlowerDataModel> GetAllFlowers(bool onlyActive = true);
FlowerDataModel GetFlowerByData(string data);
void InsertFlower(FlowerDataModel flowerDataModel);
void UpdateFlower(FlowerDataModel flowerDataModel);
void DeleteFlower(string id);
}

View File

@@ -4,13 +4,18 @@ using DaisiesContracts.Infrastructure;
namespace DaisiesContracts.DataModels;
public class BouquetItemDataModel(string flowerId, int quantity) : IValidation
public class BouquetItemDataModel(string bouquetId, string flowerId, int quantity) : IValidation
{
public string BouquetId { get; private set; } = bouquetId;
public string FlowerId { get; private set; } = flowerId;
public int Quantity { get; private set; } = quantity;
public void Validate()
{
if (BouquetId.IsEmpty())
throw new ValidationException("Bouquet Id пустой");
if (!BouquetId.IsGuid())
throw new ValidationException("Bouquet Id не является валидным GUID");
if (FlowerId.IsEmpty())
throw new ValidationException("Flower Id пустой");
if (!FlowerId.IsGuid())

View File

@@ -5,7 +5,7 @@ using System.Text.RegularExpressions;
namespace DaisiesContracts.DataModels;
public class CustomerDataModel(string id, string fullName, string phoneNumber, decimal discount, DateTime registrationDate) : IValidation
public class CustomerDataModel(string id, string fullName, string phoneNumber, DateTime registrationDate) : IValidation
{
public string Id { get; private set; } = id;
public string FullName { get; private set; } = fullName;

View File

@@ -0,0 +1,26 @@
using DaisiesContracts.Exceptions;
using DaisiesContracts.Extensions;
using DaisiesContracts.Infrastructure;
namespace DaisiesContracts.DataModels;
public class CustomerDiscountDataModel(string customerId, DateTime discountDateTime, decimal discount) : IValidation
{
public string Id { get; private set; } = Guid.NewGuid().ToString();
public string CustomerId { get; private set; } = customerId;
public DateTime DiscountDateTime { get; private set; } = discountDateTime;
/// <summary>
/// Скидка в процентах (от 0 до 100)
/// </summary>
public decimal Discount { get; private set; } = discount;
public void Validate()
{
if (CustomerId.IsEmpty())
throw new ValidationException("Customer Id пустой");
if (!CustomerId.IsGuid())
throw new ValidationException("Customer Id не является валидным GUID");
if (Discount < 0 || Discount > 100)
throw new ValidationException("Скидка должна быть в диапазоне от 0 до 100");
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,16 @@
using DaisiesContracts.DataModels;
namespace DaisiesContracts.StoragesContracts;
public interface IBouquetStorageContract
{
List<BouquetDataModel> GetList(DateTime? startDate = null, DateTime? endDate = null, string? employeeId = null, string? customerId = null, string? flowerId = null);
List<BouquetHistoryDataModel> GetHistoryByBouquetId(string bouquetId);
BouquetDataModel? GetElementById(string id);
void AddElement(BouquetDataModel bouquetDataModel);
void DelElement(string id);
}

View File

@@ -0,0 +1,10 @@
using DaisiesContracts.DataModels;
namespace DaisiesContracts.StoragesContracts;
public interface ICustomerDiscountStorageContract
{
List<CustomerDiscountDataModel> GetList(DateTime startDate, DateTime endDate, string? customerId = null);
void AddElement(CustomerDiscountDataModel customerDiscountDataModel);
}

View File

@@ -0,0 +1,20 @@
using DaisiesContracts.DataModels;
namespace DaisiesContracts.StoragesContracts;
public interface ICustomerStorageContract
{
List<CustomerDataModel> GetList();
CustomerDataModel? GetElementById(string id);
CustomerDataModel? GetElementByPhoneNumber(string phoneNumber);
CustomerDataModel? GetElementByFullName(string fullName);
void AddElement(CustomerDataModel customerDataModel);
void UpdElement(CustomerDataModel customerDataModel);
void DelElement(string id);
}

View File

@@ -0,0 +1,18 @@
using DaisiesContracts.DataModels;
namespace DaisiesContracts.StoragesContracts;
public interface IEmployeeStorageContract
{
List<EmployeeDataModel> GetList(bool onlyActive = true, DateTime? fromEmploymentDate = null, DateTime? toEmploymentDate = null);
EmployeeDataModel? GetElementById(string id);
EmployeeDataModel? GetElementByFullName(string fullName);
void AddElement(EmployeeDataModel employeeDataModel);
void UpdElement(EmployeeDataModel employeeDataModel);
void DelElement(string id);
}

View File

@@ -0,0 +1,18 @@
using DaisiesContracts.DataModels;
namespace DaisiesContracts.StoragesContracts;
public interface IFlowerStorageContract
{
List<FlowerDataModel> GetList();
FlowerDataModel? GetElementById(string id);
FlowerDataModel? GetElementByName(string name);
void AddElement(FlowerDataModel flowerDataModel);
void UpdElement(FlowerDataModel flowerDataModel);
void DelElement(string id);
}

View File

@@ -0,0 +1,19 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="AutoMapper" Version="14.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="9.0.3" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="9.0.4" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\DaisiesContracts\DaisiesContracts.csproj" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,37 @@
using DaisiesDatabase.Models;
using Microsoft.EntityFrameworkCore;
using DaisiesContracts.Infrastrcuture;
namespace DaisiesDatabase;
public class DaisiesDbContext(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<Customer>().HasIndex(x => x.PhoneNumber).IsUnique();
modelBuilder.Entity<Flower>().HasIndex(x => x.Name).IsUnique();
modelBuilder.Entity<BouquetItem>().HasKey(x => new
{
x.BouquetId,
x.FlowerId
});
}
public DbSet<Employee> Employeers { get; set; }
public DbSet<Flower> Flowers { get; set; }
public DbSet<BouquetHistory> BouquetHistories { get; set; }
public DbSet<Customer> Customers { get; set; }
public DbSet<CustomerDiscount> CustomerDiscounts { get; set; }
public DbSet<Bouquet> Bouquets { get; set; }
public DbSet<BouquetItem> BouquetItems { get; set; }
}

View File

@@ -0,0 +1,120 @@
using AutoMapper;
using DaisiesContracts.DataModels;
using DaisiesContracts.Exceptions;
using DaisiesContracts.StoragesContracts;
using DaisiesDatabase.Models;
using Microsoft.EntityFrameworkCore;
namespace DaisiesDatabase.Implementations;
public class BouquetStorageContract : IBouquetStorageContract
{
private readonly DaisiesDbContext _dbContext;
private readonly Mapper _mapper;
public BouquetStorageContract(DaisiesDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<BouquetItem, BouquetItemDataModel>();
cfg.CreateMap<BouquetItemDataModel, BouquetItem>();
cfg.CreateMap<Bouquet, BouquetDataModel>();
cfg.CreateMap<BouquetDataModel, Bouquet>().ForMember(x => x.Items, x => x.MapFrom(src => src.Items));
cfg.CreateMap<BouquetHistory, BouquetHistoryDataModel>();
});
_mapper = new Mapper(config);
}
public void AddElement(BouquetDataModel bouquetDataModel)
{
try
{
_dbContext.Bouquets.Add(_mapper.Map<Bouquet>(bouquetDataModel));
_dbContext.SaveChanges();
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void DelElement(string id)
{
try
{
var element = GetOrderById(id) ?? throw new ElementNotFoundException(id);
_dbContext.Bouquets.Remove(element);
_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);
}
}
public BouquetDataModel? GetElementById(string id)
{
try
{
return _mapper.Map<BouquetDataModel>(GetOrderById(id));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public List<BouquetHistoryDataModel> GetHistoryByBouquetId(string bouquetId)
{
try
{
return [.. _dbContext.BouquetHistories.Where(x => x.BouquetId == bouquetId).OrderByDescending(x => x.ChangeDate).Select(x => _mapper.Map<BouquetHistoryDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public List<BouquetDataModel> GetList(DateTime? startDate = null, DateTime? endDate = null, string? employeeId = null, string? customerId = null, string? flowerId = null)
{
try
{
var query = _dbContext.Bouquets.Include(x => x.Items).AsQueryable();
if (startDate is not null && endDate is not null)
{
query = query.Where(x => x.CompositionDate >= startDate && x.CompositionDate < endDate);
}
if (employeeId is not null)
{
query = query.Where(x => x.EmployeeId == employeeId);
}
if (customerId is not null)
{
query = query.Where(x => x.CustomerId == customerId);
}
if (flowerId is not null)
{
query = query.Where(x => x.Items!.Any(y => y.FlowerId == flowerId));
}
return [.. query.Select(x => _mapper.Map<BouquetDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
private Bouquet? GetOrderById(string id) => _dbContext.Bouquets.FirstOrDefault(x => x.Id == id);
}

View File

@@ -0,0 +1,58 @@
using AutoMapper;
using DaisiesContracts.DataModels;
using DaisiesContracts.Exceptions;
using DaisiesContracts.StoragesContracts;
using DaisiesDatabase.Models;
using CustomerDiscount = DaisiesDatabase.Models.CustomerDiscount;
namespace DaisiesDatabase.Implementations;
public class CustomerDiscountStorageContract : ICustomerDiscountStorageContract
{
private readonly DaisiesDbContext _dbContext;
private readonly Mapper _mapper;
public CustomerDiscountStorageContract(DaisiesDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<CustomerDiscount, CustomerDiscountDataModel>();
cfg.CreateMap<CustomerDiscountDataModel, CustomerDiscount>()
.ForMember(dest => dest.Discount, opt => opt.MapFrom(src => src.Discount));
});
_mapper = new Mapper(config);
}
public void AddElement(CustomerDiscountDataModel customerDiscountDataModel)
{
try
{
_dbContext.CustomerDiscounts.Add(_mapper.Map<CustomerDiscount>(customerDiscountDataModel));
_dbContext.SaveChanges();
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public List<CustomerDiscountDataModel> GetList(DateTime startDate, DateTime endDate, string? customerId = null)
{
try
{
var query = _dbContext.CustomerDiscounts.Where(x => x.DiscountDateTime >= startDate && x.DiscountDateTime <= endDate);
if (customerId is not null)
{
query = query.Where(x => x.CustomerId == customerId);
}
return [.. query.Select(x => _mapper.Map<CustomerDiscountDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
}

View File

@@ -0,0 +1,145 @@
using AutoMapper;
using DaisiesContracts.DataModels;
using DaisiesContracts.Exceptions;
using DaisiesContracts.StoragesContracts;
using DaisiesDatabase.Models;
using Microsoft.EntityFrameworkCore;
using Npgsql;
namespace DaisiesDatabase.Implementations;
public class CustomerStorageContract : ICustomerStorageContract
{
private readonly DaisiesDbContext _dbContext;
private readonly Mapper _mapper;
public CustomerStorageContract(DaisiesDbContext dbContext)
{
_dbContext = dbContext;
var configuration = new MapperConfiguration(cfg => cfg.AddMaps(typeof(Customer)));
_mapper = new Mapper(configuration);
}
public void AddElement(CustomerDataModel customerDataModel)
{
try
{
_dbContext.Customers.Add(_mapper.Map<Customer>(customerDataModel));
_dbContext.SaveChanges();
}
catch (InvalidOperationException ex) when (ex.TargetSite?.Name == "ThrowIdentityConflict")
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("Id", customerDataModel.Id);
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Customers_PhoneNumber" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("PhoneNumber", customerDataModel.PhoneNumber);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void DelElement(string id)
{
try
{
var element = GetCustomerById(id) ?? throw new ElementNotFoundException(id);
_dbContext.Customers.Remove(element);
_dbContext.SaveChanges();
}
catch (ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public CustomerDataModel? GetElementByFullName(string fullName)
{
try
{
return
_mapper.Map<CustomerDataModel>(_dbContext.Customers.FirstOrDefault(x => x.FullName == fullName));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public CustomerDataModel? GetElementById(string id)
{
try
{
return _mapper.Map<CustomerDataModel>(GetCustomerById(id));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public CustomerDataModel? GetElementByPhoneNumber(string phoneNumber)
{
try
{
return
_mapper.Map<CustomerDataModel>(_dbContext.Customers.FirstOrDefault(x => x.PhoneNumber == phoneNumber));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public List<CustomerDataModel> GetList()
{
try
{
var query = _dbContext.Customers.AsQueryable();
return [.. query.Select(x => _mapper.Map<CustomerDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void UpdElement(CustomerDataModel customerDataModel)
{
try
{
var element = GetCustomerById(customerDataModel.Id) ?? throw new ElementNotFoundException(customerDataModel.Id);
_dbContext.Customers.Update(_mapper.Map(customerDataModel, element));
_dbContext.SaveChanges();
}
catch (ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
private Customer? GetCustomerById(string id) => _dbContext.Customers.FirstOrDefault(x => x.Id == id);
}

View File

@@ -0,0 +1,131 @@
using AutoMapper;
using DaisiesContracts.DataModels;
using DaisiesContracts.Exceptions;
using DaisiesContracts.StoragesContracts;
using DaisiesDatabase.Models;
namespace DaisiesDatabase.Implementations;
public class EmployeeStorageContract : IEmployeeStorageContract
{
private readonly DaisiesDbContext _dbContext;
private readonly Mapper _mapper;
public EmployeeStorageContract(DaisiesDbContext dbContext)
{
_dbContext = dbContext;
var configuration = new MapperConfiguration(cfg => cfg.AddMaps(typeof(Employee)));
_mapper = new Mapper(configuration);
}
public void AddElement(EmployeeDataModel employeeDataModel)
{
try
{
_dbContext.Employeers.Add(_mapper.Map<Employee>(employeeDataModel));
_dbContext.SaveChanges();
}
catch (InvalidOperationException ex) when (ex.TargetSite?.Name == "ThrowIdentityConflict")
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("Id", employeeDataModel.Id);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void DelElement(string id)
{
try
{
var element = GetWorkerById(id) ?? throw new ElementNotFoundException(id);
element.IsActive = false;
_dbContext.SaveChanges();
}
catch (ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public EmployeeDataModel? GetElementByFullName(string fullName)
{
try
{
return _mapper.Map<EmployeeDataModel>(_dbContext.Employeers.FirstOrDefault(x => x.FullName == fullName));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public EmployeeDataModel? GetElementById(string id)
{
try
{
return _mapper.Map<EmployeeDataModel>(GetWorkerById(id));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public List<EmployeeDataModel> GetList(bool onlyActive = true, DateTime? fromEmploymentDate = null, DateTime? toEmploymentDate = null)
{
try
{
var query = _dbContext.Employeers.AsQueryable();
if (onlyActive)
{
query = query.Where(x => x.IsActive);
}
if (fromEmploymentDate is not null && toEmploymentDate is not null)
{
query = query.Where(x => x.EmploymentDate >= fromEmploymentDate && x.EmploymentDate <= toEmploymentDate);
}
return [.. query.Select(x => _mapper.Map<EmployeeDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void UpdElement(EmployeeDataModel employeeDataModel)
{
try
{
var element = GetWorkerById(employeeDataModel.Id) ?? throw new ElementNotFoundException(employeeDataModel.Id);
_dbContext.Employeers.Update(_mapper.Map(employeeDataModel, element));
_dbContext.SaveChanges();
}
catch (ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
private Employee? GetWorkerById(string id) => _dbContext.Employeers.FirstOrDefault(x => x.Id == id && x.IsActive);
}

View File

@@ -0,0 +1,147 @@
using AutoMapper;
using DaisiesContracts.DataModels;
using DaisiesContracts.Exceptions;
using DaisiesContracts.StoragesContracts;
using DaisiesDatabase.Models;
using Microsoft.EntityFrameworkCore;
using Npgsql;
namespace DaisiesDatabase.Implementations;
public class FlowerStorageContract : IFlowerStorageContract
{
private readonly DaisiesDbContext _dbContext;
private readonly Mapper _mapper;
public FlowerStorageContract(DaisiesDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Flower, FlowerDataModel>();
cfg.CreateMap<FlowerDataModel, Flower>();
});
_mapper = new Mapper(config);
}
public void AddElement(FlowerDataModel flowerDataModel)
{
try
{
_dbContext.Flowers.Add(_mapper.Map<Flower>(flowerDataModel));
_dbContext.SaveChanges();
}
catch (InvalidOperationException ex) when (ex.TargetSite?.Name == "ThrowIdentityConflict")
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("Id", flowerDataModel.Id);
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Flowers_Name" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("Name", flowerDataModel.Name);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void DelElement(string id)
{
try
{
var element = GetFlowerById(id) ?? throw new ElementNotFoundException(id);
_dbContext.Flowers.Remove(element);
_dbContext.SaveChanges();
}
catch (ElementNotFoundException ex)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public FlowerDataModel? GetElementById(string id)
{
try
{
return _mapper.Map<FlowerDataModel>(GetFlowerById(id));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public FlowerDataModel? GetElementByName(string name)
{
try
{
return _mapper.Map<FlowerDataModel>(_dbContext.Flowers.FirstOrDefault(x => x.Name == name));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public List<FlowerDataModel> GetList()
{
try
{
var query = _dbContext.Flowers.AsQueryable();
return [.. query.Select(x => _mapper.Map<FlowerDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void UpdElement(FlowerDataModel flowerDataModel)
{
try
{
var transaction = _dbContext.Database.BeginTransaction();
try
{
var element = GetFlowerById(flowerDataModel.Id) ?? throw new ElementNotFoundException(flowerDataModel.Id);
_dbContext.Flowers.Update(_mapper.Map(flowerDataModel, element));
_dbContext.SaveChanges();
transaction.Commit();
}
catch
{
transaction.Rollback();
throw;
}
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Flowers_Name" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("Name", flowerDataModel.Name);
}
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 Flower? GetFlowerById(string id) => _dbContext.Flowers.FirstOrDefault(x => x.Id == id);
}

View File

@@ -0,0 +1,23 @@
using DaisiesContracts.Enums;
using System.ComponentModel.DataAnnotations.Schema;
using System.Xml.Linq;
namespace DaisiesDatabase.Models;
public class Bouquet
{
public required string Id { get; set; }
public required string EmployeeId { get; set; }
public required string CustomerId { get; set; }
public required string Name { get; set; }
public DateTime CompositionDate { get; set; }
public BouquetType Type { get; set; }
public Employee? Employee { get; set; }
public Customer? Customer { get; set; }
[ForeignKey("BouquetId")]
public List<BouquetItem>? Items { get; set; }
[ForeignKey("BouquetId")]
public List<BouquetHistory>? BouquetHistories { get; set; }
}

View File

@@ -0,0 +1,10 @@
namespace DaisiesDatabase.Models;
public class BouquetHistory
{
public required string Id { get; set; }
public required string BouquetId { get; set; }
public required string OldName { get; set; }
public DateTime ChangeDate { get; set; }
public Bouquet? Bouquet { get; set; }
}

View File

@@ -0,0 +1,11 @@
namespace DaisiesDatabase.Models;
public class BouquetItem
{
public required string Id { get; set; }
public required string BouquetId { get; set; }
public required string FlowerId { get; set; }
public int Quantity { get; set; }
public Bouquet? Bouquet { get; set; }
public Flower? Flower { get; set; }
}

View File

@@ -0,0 +1,19 @@
using AutoMapper;
using DaisiesContracts.DataModels;
using System.ComponentModel.DataAnnotations.Schema;
namespace DaisiesDatabase.Models;
[AutoMap(typeof(CustomerDataModel), ReverseMap = true)]
public class Customer
{
public required string Id { get; set; }
public required string FullName { get; set; }
public required string PhoneNumber { get; set; }
public DateTime RegistrationDate { get; set; }
[ForeignKey("CustomerId")]
public List<Bouquet>? Bouquets { get; set; }
[ForeignKey("CustomerId")]
public List<CustomerDiscount>? CustomerDiscounts { get; set; }
}

View File

@@ -0,0 +1,10 @@
namespace DaisiesDatabase.Models;
public class CustomerDiscount
{
public required string Id { get; set; }
public required string CustomerId { get; set; }
public DateTime DiscountDateTime { get; set; }
public decimal Discount { get; set; }
public Customer? Customer { get; set; }
}

View File

@@ -0,0 +1,19 @@
using AutoMapper;
using DaisiesContracts.DataModels;
using DaisiesContracts.Enums;
using System.ComponentModel.DataAnnotations.Schema;
namespace DaisiesDatabase.Models;
[AutoMap(typeof(EmployeeDataModel), ReverseMap = true)]
public class Employee
{
public required string Id { get; set; }
public required string FullName { get; set; }
public EmployeeRole Role { get; set; }
public DateTime EmploymentDate { get; set; }
public bool IsActive { get; set; }
[ForeignKey("EmployeeId")]
public List<Bouquet>? Bouquets { get; set; }
}

View File

@@ -0,0 +1,13 @@
using System.ComponentModel.DataAnnotations.Schema;
namespace DaisiesDatabase.Models;
public class Flower
{
public required string Id { get; set; }
public required string Name { get; set; }
public decimal Price { get; set; }
[ForeignKey("FlowerId")]
public List<BouquetItem>? Items { get; set; }
}

View File

@@ -5,7 +5,11 @@ VisualStudioVersion = 17.8.34330.188
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DaisiesContracts", "DaisiesContracts\DaisiesContracts.csproj", "{C15353B7-699C-458E-B22F-AF50B4F7D36B}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DaisiesTests", "DaisiesTests\DaisiesTests.csproj", "{6DFD5D72-7970-4ED5-864F-2D53F404F4F7}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DaisiesTests", "DaisiesTests\DaisiesTests.csproj", "{6DFD5D72-7970-4ED5-864F-2D53F404F4F7}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DaisiesBusinessLogic", "DaisiesBusinessLogic\DaisiesBusinessLogic.csproj", "{006545EC-4A37-43DF-AE7F-4120BC98B2E2}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DaisiesDatabase", "DaisiesDatabase\DaisiesDatabase.csproj", "{DF72C23E-F834-464D-B25F-6D841F77C2BB}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
@@ -21,6 +25,14 @@ Global
{6DFD5D72-7970-4ED5-864F-2D53F404F4F7}.Debug|Any CPU.Build.0 = Debug|Any CPU
{6DFD5D72-7970-4ED5-864F-2D53F404F4F7}.Release|Any CPU.ActiveCfg = Release|Any CPU
{6DFD5D72-7970-4ED5-864F-2D53F404F4F7}.Release|Any CPU.Build.0 = Release|Any CPU
{006545EC-4A37-43DF-AE7F-4120BC98B2E2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{006545EC-4A37-43DF-AE7F-4120BC98B2E2}.Debug|Any CPU.Build.0 = Debug|Any CPU
{006545EC-4A37-43DF-AE7F-4120BC98B2E2}.Release|Any CPU.ActiveCfg = Release|Any CPU
{006545EC-4A37-43DF-AE7F-4120BC98B2E2}.Release|Any CPU.Build.0 = Release|Any CPU
{DF72C23E-F834-464D-B25F-6D841F77C2BB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{DF72C23E-F834-464D-B25F-6D841F77C2BB}.Debug|Any CPU.Build.0 = Debug|Any CPU
{DF72C23E-F834-464D-B25F-6D841F77C2BB}.Release|Any CPU.ActiveCfg = Release|Any CPU
{DF72C23E-F834-464D-B25F-6D841F77C2BB}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE

View File

@@ -0,0 +1,501 @@
using DaisiesContracts.BusinessLogicsContracts;
using DaisiesContracts.Exceptions;
using DaisiesBusinessLogic.Implementations;
using Moq;
using DaisiesContracts.StoragesContracts;
using Microsoft.Extensions.Logging;
using DaisiesContracts.DataModels;
using DaisiesContracts.Enums;
namespace DaisiesTests.BusinessLogicsContractsTests;
[TestFixture]
internal class BouquetBusinessLogicContractTests
{
private BouquetBusinessLogicContract _saleBusinessLogicContract;
private Mock<IBouquetStorageContract> _saleStorageContract;
[OneTimeSetUp]
public void OneTimeSetUp()
{
_saleStorageContract = new Mock<IBouquetStorageContract>();
_saleBusinessLogicContract = new BouquetBusinessLogicContract(_saleStorageContract.Object, new Mock<ILogger>().Object);
}
[SetUp]
public void SetUp()
{
_saleStorageContract.Reset();
}
[Test]
public void GetAllBouquetsByPeriod_ReturnListOfRecords_Test()
{
//Arrange
var date = DateTime.UtcNow;
var listOriginal = new List<BouquetDataModel>()
{
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), "name1", DateTime.UtcNow, BouquetType.Special,
[new BouquetItemDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]),
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), "name1", DateTime.UtcNow, BouquetType.Special, []),
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), "name1", DateTime.UtcNow, BouquetType.Special, []),
};
_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.GetAllBouquetsByPeriod(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 GetAllBouquetsByPeriod_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.GetAllBouquetsByPeriod(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 GetAllBouquetsByPeriod_IncorrectDates_ThrowException_Test()
{
//Arrange
var date = DateTime.UtcNow;
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllBouquetsByPeriod(date, date), Throws.TypeOf<IncorrectDatesException>());
Assert.That(() => _saleBusinessLogicContract.GetAllBouquetsByPeriod(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 GetAllBouquetsByPeriod_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllBouquetsByPeriod(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 GetAllBouquetsByPeriod_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.GetAllBouquetsByPeriod(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 GetAllBouquetsByEmployeerByPeriod_ReturnListOfRecords_Test()
{
//Arrange
var date = DateTime.UtcNow;
var workerId = Guid.NewGuid().ToString();
var listOriginal = new List<BouquetDataModel>()
{
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), "name1", DateTime.UtcNow, BouquetType.Special,
[new BouquetItemDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]),
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), "name1", DateTime.UtcNow, BouquetType.Special, []),
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), "name1", DateTime.UtcNow, BouquetType.Special, []),
};
_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.GetAllBouquetsByEmployeerByPeriod(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 GetAllBouquetsByEmployeerByPeriod_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.GetAllBouquetsByEmployeerByPeriod(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 GetAllBouquetsByEmployeerByPeriod_IncorrectDates_ThrowException_Test()
{
//Arrange
var date = DateTime.UtcNow;
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllBouquetsByEmployeerByPeriod(Guid.NewGuid().ToString(), date, date), Throws.TypeOf<IncorrectDatesException>());
Assert.That(() => _saleBusinessLogicContract.GetAllBouquetsByEmployeerByPeriod(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 GetAllBouquetsByEmployeerByPeriod_WorkerIdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllBouquetsByEmployeerByPeriod(null, DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _saleBusinessLogicContract.GetAllBouquetsByEmployeerByPeriod(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 GetAllBouquetsByEmployeerByPeriod_WorkerIdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllBouquetsByEmployeerByPeriod("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 GetAllBouquetsByEmployeerByPeriod_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllBouquetsByEmployeerByPeriod(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 GetAllBouquetsByEmployeerByPeriod_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.GetAllBouquetsByEmployeerByPeriod(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 GetAllBouquetsByCustomerByPeriod_ReturnListOfRecords_Test()
{
//Arrange
var date = DateTime.UtcNow;
var buyerId = Guid.NewGuid().ToString();
var listOriginal = new List<BouquetDataModel>()
{
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), "name1", DateTime.UtcNow, BouquetType.Special,
[new BouquetItemDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]),
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), "name1", DateTime.UtcNow, BouquetType.Special, []),
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), "name1", DateTime.UtcNow, BouquetType.Special, []),
};
_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.GetAllBouquetsByCustomerByPeriod(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 GetAllBouquetsByCustomerByPeriod_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.GetAllBouquetsByCustomerByPeriod(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 GetAllBouquetsByCustomerByPeriod_IncorrectDates_ThrowException_Test()
{
//Arrange
var date = DateTime.UtcNow;
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllBouquetsByCustomerByPeriod(Guid.NewGuid().ToString(), date, date), Throws.TypeOf<IncorrectDatesException>());
Assert.That(() => _saleBusinessLogicContract.GetAllBouquetsByCustomerByPeriod(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 GetAllBouquetsByCustomerByPeriod_BuyerIdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllBouquetsByCustomerByPeriod(null, DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _saleBusinessLogicContract.GetAllBouquetsByCustomerByPeriod(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 GetAllBouquetsByCustomerByPeriod_BuyerIdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllBouquetsByCustomerByPeriod("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 GetAllBouquetsByCustomerByPeriod_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllBouquetsByCustomerByPeriod(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 GetAllBouquetsByCustomerByPeriod_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.GetAllBouquetsByCustomerByPeriod(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 GetAllBouquetsByFlowerByPeriod_ReturnListOfRecords_Test()
{
//Arrange
var date = DateTime.UtcNow;
var productId = Guid.NewGuid().ToString();
var listOriginal = new List<BouquetDataModel>()
{
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), "name1", DateTime.UtcNow, BouquetType.Special,
[new BouquetItemDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]),
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), "name1", DateTime.UtcNow, BouquetType.Special, []),
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), "name1", DateTime.UtcNow, BouquetType.Special, []),
};
_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.GetAllBouquetsByFlowerByPeriod(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 GetAllBouquetsByFlowerByPeriod_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.GetAllBouquetsByFlowerByPeriod(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 GetAllBouquetsByFlowerByPeriod_IncorrectDates_ThrowException_Test()
{
//Arrange
var date = DateTime.UtcNow;
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllBouquetsByFlowerByPeriod(Guid.NewGuid().ToString(), date, date), Throws.TypeOf<IncorrectDatesException>());
Assert.That(() => _saleBusinessLogicContract.GetAllBouquetsByFlowerByPeriod(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 GetAllBouquetsByFlowerByPeriod_ProductIdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllBouquetsByFlowerByPeriod(null, DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _saleBusinessLogicContract.GetAllBouquetsByFlowerByPeriod(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 GetAllBouquetsByFlowerByPeriod_ProductIdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllBouquetsByFlowerByPeriod("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 GetAllBouquetsByFlowerByPeriod_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllBouquetsByFlowerByPeriod(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 GetAllBouquetsByFlowerByPeriod_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.GetAllBouquetsByFlowerByPeriod(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 GetBouquetByData_GetById_ReturnRecord_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
var record = new BouquetDataModel(id, Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), "Name1", DateTime.UtcNow, BouquetType.Special,
[new BouquetItemDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]);
_saleStorageContract.Setup(x => x.GetElementById(id)).Returns(record);
//Act
var element = _saleBusinessLogicContract.GetBouquetByData(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 GetBouquetByData_EmptyData_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetBouquetByData(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _saleBusinessLogicContract.GetBouquetByData(string.Empty), Throws.TypeOf<ArgumentNullException>());
_saleStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetBouquetByData_IdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetBouquetByData("saleId"), Throws.TypeOf<ValidationException>());
_saleStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetBouquetByData_GetById_NotFoundRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetBouquetByData(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_saleStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetBouquetByData_StorageThrowError_ThrowException_Test()
{
//Arrange
_saleStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetBouquetByData(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_saleStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void InsertBouquet_CorrectRecord_Test()
{
//Arrange
var flag = false;
var record = new BouquetDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), "Name1", DateTime.UtcNow, BouquetType.Special,
[new BouquetItemDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]);
_saleStorageContract.Setup(x => x.AddElement(It.IsAny<BouquetDataModel>()))
.Callback((BouquetDataModel x) =>
{
flag = x.Id == record.Id && x.EmployeeId == record.EmployeeId && x.CustomerId == record.CustomerId &&
x.CompositionDate == record.CompositionDate && x.Type == record.Type && x.Items.Count == record.Items.Count &&
x.Items.First().FlowerId == record.Items.First().FlowerId &&
x.Items.First().BouquetId == record.Items.First().BouquetId &&
x.Items.First().Quantity == record.Items.First().Quantity;
});
//Act
_saleBusinessLogicContract.InsertBouquet(record);
//Assert
_saleStorageContract.Verify(x => x.AddElement(It.IsAny<BouquetDataModel>()), Times.Once);
Assert.That(flag);
}
[Test]
public void InsertBouquet_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_saleStorageContract.Setup(x => x.AddElement(It.IsAny<BouquetDataModel>())).Throws(new ElementExistsException("Data", "Data"));
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.InsertBouquet(new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(),
Guid.NewGuid().ToString(), "name1", DateTime.UtcNow, BouquetType.Wedding, [new BouquetItemDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<ElementExistsException>());
_saleStorageContract.Verify(x => x.AddElement(It.IsAny<BouquetDataModel>()), Times.Once);
}
[Test]
public void InsertBouquet_NullRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.InsertBouquet(null), Throws.TypeOf<ArgumentNullException>());
_saleStorageContract.Verify(x => x.AddElement(It.IsAny<BouquetDataModel>()), Times.Never);
}
[Test]
public void InsertBouquet_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.InsertBouquet(new BouquetDataModel("id", Guid.NewGuid().ToString(),
Guid.NewGuid().ToString(), "name1", DateTime.UtcNow, BouquetType.Wedding, [])), Throws.TypeOf<ValidationException>());
_saleStorageContract.Verify(x => x.AddElement(It.IsAny<BouquetDataModel>()), Times.Never);
}
[Test]
public void InsertBouquet_StorageThrowError_ThrowException_Test()
{
//Arrange
_saleStorageContract.Setup(x => x.AddElement(It.IsAny<BouquetDataModel>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.InsertBouquet(new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(),
Guid.NewGuid().ToString(), "name1", DateTime.UtcNow, BouquetType.Wedding, [new BouquetItemDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<StorageException>());
_saleStorageContract.Verify(x => x.AddElement(It.IsAny<BouquetDataModel>()), 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.CancelBouquet(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.CancelBouquet(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.CancelBouquet(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _saleBusinessLogicContract.CancelBouquet(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.CancelBouquet("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.CancelBouquet(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_saleStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
}
}

View File

@@ -0,0 +1,350 @@
using DaisiesBusinessLogic.Implementations;
using DaisiesContracts.DataModels;
using DaisiesContracts.Exceptions;
using DaisiesContracts.StoragesContracts;
using Microsoft.Extensions.Logging;
using Moq;
namespace DaisiesTests.BusinessLogicsContractsTests;
[TestFixture]
internal class CustomerBusinessLogicContractTests
{
private CustomerBusinessLogicContract _buyerBusinessLogicContract;
private Mock<ICustomerStorageContract> _buyerStorageContract;
[OneTimeSetUp]
public void OneTimeSetUp()
{
_buyerStorageContract = new Mock<ICustomerStorageContract>();
_buyerBusinessLogicContract = new CustomerBusinessLogicContract(_buyerStorageContract.Object, new Mock<ILogger>().Object);
}
[SetUp]
public void SetUp()
{
_buyerStorageContract.Reset();
}
[Test]
public void GetAllBuyers_ReturnListOfRecords_Test()
{
//Arrange
var listOriginal = new List<CustomerDataModel>()
{
new(Guid.NewGuid().ToString(), "fio 1", "+7-111-111-11-11", DateTime.UtcNow),
new(Guid.NewGuid().ToString(), "fio 2", "+7-555-444-33-23", DateTime.UtcNow),
new(Guid.NewGuid().ToString(), "fio 3", "+7-777-777-7777", DateTime.UtcNow),
};
_buyerStorageContract.Setup(x => x.GetList()).Returns(listOriginal);
//Act
var list = _buyerBusinessLogicContract.GetAllCustomers();
//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.GetAllCustomers();
//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.GetAllCustomers(), 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.GetAllCustomers(), 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 CustomerDataModel(id, "fio", "+7-111-111-11-11", DateTime.UtcNow);
_buyerStorageContract.Setup(x => x.GetElementById(id)).Returns(record);
//Act
var element = _buyerBusinessLogicContract.GetCustomerByData(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 CustomerDataModel(Guid.NewGuid().ToString(), fio, "+7-111-111-11-11", DateTime.UtcNow);
_buyerStorageContract.Setup(x => x.GetElementByFullName(fio)).Returns(record);
//Act
var element = _buyerBusinessLogicContract.GetCustomerByData(fio);
//Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.FullName, Is.EqualTo(fio));
_buyerStorageContract.Verify(x => x.GetElementByFullName(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetBuyerByData_GetByPhoneNumber_ReturnRecord_Test()
{
//Arrange
var phoneNumber = "+7-111-111-11-11";
var record = new CustomerDataModel(Guid.NewGuid().ToString(), "fio", phoneNumber, DateTime.UtcNow);
_buyerStorageContract.Setup(x => x.GetElementByPhoneNumber(phoneNumber)).Returns(record);
//Act
var element = _buyerBusinessLogicContract.GetCustomerByData(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.GetCustomerByData(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _buyerBusinessLogicContract.GetCustomerByData(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.GetElementByFullName(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetBuyerByData_GetById_NotFoundRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _buyerBusinessLogicContract.GetCustomerByData(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.GetElementByFullName(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetBuyerByData_GetByFio_NotFoundRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _buyerBusinessLogicContract.GetCustomerByData("fio"), Throws.TypeOf<ElementNotFoundException>());
_buyerStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Never);
_buyerStorageContract.Verify(x => x.GetElementByFullName(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.GetCustomerByData("+7-111-111-11-12"), Throws.TypeOf<ElementNotFoundException>());
_buyerStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Never);
_buyerStorageContract.Verify(x => x.GetElementByFullName(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.GetElementByFullName(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.GetCustomerByData(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
Assert.That(() => _buyerBusinessLogicContract.GetCustomerByData("fio"), Throws.TypeOf<StorageException>());
Assert.That(() => _buyerBusinessLogicContract.GetCustomerByData("+7-111-111-11-12"), Throws.TypeOf<StorageException>());
_buyerStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
_buyerStorageContract.Verify(x => x.GetElementByFullName(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 CustomerDataModel(Guid.NewGuid().ToString(), "fio", "+7-111-111-11-11", DateTime.UtcNow);
_buyerStorageContract.Setup(x => x.AddElement(It.IsAny<CustomerDataModel>()))
.Callback((CustomerDataModel x) =>
{
flag = x.Id == record.Id && x.FullName == record.FullName &&
x.PhoneNumber == record.PhoneNumber && x.RegistrationDate == record.RegistrationDate;
});
//Act
_buyerBusinessLogicContract.InsertCustomer(record);
//Assert
_buyerStorageContract.Verify(x => x.AddElement(It.IsAny<CustomerDataModel>()), Times.Once);
Assert.That(flag);
}
[Test]
public void InsertBuyer_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_buyerStorageContract.Setup(x => x.AddElement(It.IsAny<CustomerDataModel>())).Throws(new ElementExistsException("Data", "Data"));
//Act&Assert
Assert.That(() => _buyerBusinessLogicContract.InsertCustomer(new(Guid.NewGuid().ToString(), "fio", "+7-111-111-11-11", DateTime.UtcNow)), Throws.TypeOf<ElementExistsException>());
_buyerStorageContract.Verify(x => x.AddElement(It.IsAny<CustomerDataModel>()), Times.Once);
}
[Test]
public void InsertBuyer_NullRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _buyerBusinessLogicContract.InsertCustomer(null), Throws.TypeOf<ArgumentNullException>());
_buyerStorageContract.Verify(x => x.AddElement(It.IsAny<CustomerDataModel>()), Times.Never);
}
[Test]
public void InsertBuyer_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _buyerBusinessLogicContract.InsertCustomer(new CustomerDataModel("id", "fio", "+7-111-111-11-11", DateTime.UtcNow)), Throws.TypeOf<ValidationException>());
_buyerStorageContract.Verify(x => x.AddElement(It.IsAny<CustomerDataModel>()), Times.Never);
}
[Test]
public void InsertBuyer_StorageThrowError_ThrowException_Test()
{
//Arrange
_buyerStorageContract.Setup(x => x.AddElement(It.IsAny<CustomerDataModel>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _buyerBusinessLogicContract.InsertCustomer(new(Guid.NewGuid().ToString(), "fio", "+7-111-111-11-11", DateTime.UtcNow)), Throws.TypeOf<StorageException>());
_buyerStorageContract.Verify(x => x.AddElement(It.IsAny<CustomerDataModel>()), Times.Once);
}
[Test]
public void UpdateBuyer_CorrectRecord_Test()
{
//Arrange
var flag = false;
var record = new CustomerDataModel(Guid.NewGuid().ToString(), "fio", "+7-111-111-11-11", DateTime.UtcNow);
_buyerStorageContract.Setup(x => x.UpdElement(It.IsAny<CustomerDataModel>()))
.Callback((CustomerDataModel x) =>
{
flag = x.Id == record.Id && x.FullName == record.FullName &&
x.PhoneNumber == record.PhoneNumber && x.RegistrationDate == record.RegistrationDate;
});
//Act
_buyerBusinessLogicContract.UpdateCustomer(record);
//Assert
_buyerStorageContract.Verify(x => x.UpdElement(It.IsAny<CustomerDataModel>()), Times.Once);
Assert.That(flag);
}
[Test]
public void UpdateBuyer_RecordWithIncorrectData_ThrowException_Test()
{
//Arrange
_buyerStorageContract.Setup(x => x.UpdElement(It.IsAny<CustomerDataModel>())).Throws(new ElementNotFoundException(""));
//Act&Assert
Assert.That(() => _buyerBusinessLogicContract.UpdateCustomer(new(Guid.NewGuid().ToString(), "fio", "+7-111-111-11-11", DateTime.UtcNow)), Throws.TypeOf<ElementNotFoundException>());
_buyerStorageContract.Verify(x => x.UpdElement(It.IsAny<CustomerDataModel>()), Times.Once);
}
[Test]
public void UpdateBuyer_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_buyerStorageContract.Setup(x => x.UpdElement(It.IsAny<CustomerDataModel>())).Throws(new ElementExistsException("Data", "Data"));
//Act&Assert
Assert.That(() => _buyerBusinessLogicContract.UpdateCustomer(new(Guid.NewGuid().ToString(), "fio", "+7-111-111-11-11", DateTime.UtcNow)), Throws.TypeOf<ElementExistsException>());
_buyerStorageContract.Verify(x => x.UpdElement(It.IsAny<CustomerDataModel>()), Times.Once);
}
[Test]
public void UpdateBuyer_NullRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _buyerBusinessLogicContract.UpdateCustomer(null), Throws.TypeOf<ArgumentNullException>());
_buyerStorageContract.Verify(x => x.UpdElement(It.IsAny<CustomerDataModel>()), Times.Never);
}
[Test]
public void UpdateBuyer_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _buyerBusinessLogicContract.UpdateCustomer(new CustomerDataModel("id", "fio", "+7-111-111-11-11", DateTime.UtcNow)), Throws.TypeOf<ValidationException>());
_buyerStorageContract.Verify(x => x.UpdElement(It.IsAny<CustomerDataModel>()), Times.Never);
}
[Test]
public void UpdateBuyer_StorageThrowError_ThrowException_Test()
{
//Arrange
_buyerStorageContract.Setup(x => x.UpdElement(It.IsAny<CustomerDataModel>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _buyerBusinessLogicContract.UpdateCustomer(new(Guid.NewGuid().ToString(), "fio", "+7-111-111-11-11", DateTime.UtcNow)), Throws.TypeOf<StorageException>());
_buyerStorageContract.Verify(x => x.UpdElement(It.IsAny<CustomerDataModel>()), 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.DeleteCustomer(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.DeleteCustomer(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.DeleteCustomer(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _buyerBusinessLogicContract.DeleteCustomer(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.DeleteCustomer("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.DeleteCustomer(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_buyerStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
}
}

View File

@@ -0,0 +1,303 @@
using DaisiesBusinessLogic.Implementations;
using DaisiesContracts.DataModels;
using DaisiesContracts.Enums;
using DaisiesContracts.Exceptions;
using DaisiesContracts.StoragesContracts;
using Microsoft.Extensions.Logging;
using Moq;
namespace DaisiesTests.BusinessLogicsContractsTests;
[TestFixture]
internal class CustomerDiscountBusinessLogicContractTests
{
private CustomerDiscountBusinessLogicContract _salaryBusinessLogicContract;
private Mock<ICustomerDiscountStorageContract> _salaryStorageContract;
private Mock<IBouquetStorageContract> _saleStorageContract;
private Mock<ICustomerStorageContract> _workerStorageContract;
[OneTimeSetUp]
public void OneTimeSetUp()
{
_salaryStorageContract = new Mock<ICustomerDiscountStorageContract>();
_saleStorageContract = new Mock<IBouquetStorageContract>();
_workerStorageContract = new Mock<ICustomerStorageContract>();
_salaryBusinessLogicContract = new CustomerDiscountBusinessLogicContract(_salaryStorageContract.Object,
_saleStorageContract.Object, _workerStorageContract.Object, new Mock<ILogger>().Object);
}
[SetUp]
public void SetUp()
{
_salaryStorageContract.Reset();
_saleStorageContract.Reset();
_workerStorageContract.Reset();
}
[Test]
public void GetAllSalaries_ReturnListOfRecords_Test()
{
//Arrange
var startDate = DateTime.UtcNow;
var endDate = DateTime.UtcNow.AddDays(1);
var listOriginal = new List<CustomerDiscountDataModel>()
{
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.GetAllDiscountsByPeriod(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.GetAllDiscountsByPeriod(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.GetAllDiscountsByPeriod(dateTime, dateTime), Throws.TypeOf<IncorrectDatesException>());
Assert.That(() => _salaryBusinessLogicContract.GetAllDiscountsByPeriod(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.GetAllDiscountsByPeriod(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.GetAllDiscountsByPeriod(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<CustomerDiscountDataModel>()
{
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.GetAllDiscountsByPeriodByCustomer(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.GetAllDiscountsByPeriodByCustomer(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.GetAllDiscountsByPeriodByCustomer(dateTime, dateTime, Guid.NewGuid().ToString()), Throws.TypeOf<IncorrectDatesException>());
Assert.That(() => _salaryBusinessLogicContract.GetAllDiscountsByPeriodByCustomer(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.GetAllDiscountsByPeriodByCustomer(DateTime.UtcNow, DateTime.UtcNow.AddDays(1), null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _salaryBusinessLogicContract.GetAllDiscountsByPeriodByCustomer(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.GetAllDiscountsByPeriodByCustomer(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.GetAllDiscountsByPeriodByCustomer(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.GetAllDiscountsByPeriodByCustomer(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 = 0.0;
var postSalary = 0.0;
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns([new BouquetDataModel(Guid.NewGuid().ToString(), workerId, workerId, "Name", DateTime.UtcNow, BouquetType.Standard, [])]);
_workerStorageContract.Setup(x => x.GetList())
.Returns([new CustomerDataModel(workerId, "Full Name", "+79999999999", DateTime.UtcNow)]);
var sum = 0.0;
var expectedSum = postSalary + saleSum * 0.1;
_salaryStorageContract.Setup(x => x.AddElement(It.IsAny<CustomerDiscountDataModel>()))
.Callback((CustomerDiscountDataModel x) =>
{
sum = (double)x.Discount;
});
//Act
_salaryBusinessLogicContract.CalculateDiscountByMounth(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<CustomerDataModel>() {
new(worker1Id, "Full Name", "+79999999999", DateTime.UtcNow),
new(worker2Id, "Full Name", "+79999999999", DateTime.UtcNow),
new(worker3Id, "Full Name", "+79999999999", DateTime.UtcNow)
};
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns([
new BouquetDataModel(Guid.NewGuid().ToString(), worker1Id, worker1Id, "Name", DateTime.UtcNow, BouquetType.Standard, []),
new BouquetDataModel(Guid.NewGuid().ToString(), worker2Id, worker2Id, "Name", DateTime.UtcNow, BouquetType.Standard, []),
new BouquetDataModel(Guid.NewGuid().ToString(), worker2Id, worker2Id, "Name", DateTime.UtcNow, BouquetType.Standard, []),
new BouquetDataModel(Guid.NewGuid().ToString(), worker3Id, worker3Id, "Name", DateTime.UtcNow, BouquetType.Standard, []),
new BouquetDataModel(Guid.NewGuid().ToString(), worker3Id, worker3Id, "Name", DateTime.UtcNow, BouquetType.Standard, [])
]);
_workerStorageContract.Setup(x => x.GetList())
.Returns(list);
//Act
_salaryBusinessLogicContract.CalculateDiscountByMounth(DateTime.UtcNow);
//Assert
_salaryStorageContract.Verify(x => x.AddElement(It.IsAny<CustomerDiscountDataModel>()), Times.Exactly(list.Count));
}
[Test]
public void CalculateSalaryByMounth_WithoitSalesByWorker_Test()
{
//Arrange
var postSalary = 0.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([]);
_workerStorageContract.Setup(x => x.GetList())
.Returns([new CustomerDataModel(workerId, "Full Name", "+79999999999", DateTime.UtcNow)]);
var sum = 0.0;
var expectedSum = postSalary;
_salaryStorageContract.Setup(x => x.AddElement(It.IsAny<CustomerDiscountDataModel>()))
.Callback((CustomerDiscountDataModel x) =>
{
sum = (double)x.Discount;
});
//Act
_salaryBusinessLogicContract.CalculateDiscountByMounth(DateTime.UtcNow);
//Assert
Assert.That(sum, Is.EqualTo(expectedSum));
}
[Test]
public void CalculateSalaryByMounth_SaleStorageReturnNull_ThrowException_Test()
{
//Arrange
var workerId = Guid.NewGuid().ToString();
_workerStorageContract.Setup(x => x.GetList())
.Returns([new CustomerDataModel(workerId, "Full Name", "+79999999999", DateTime.UtcNow)]);
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.CalculateDiscountByMounth(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 BouquetDataModel(Guid.NewGuid().ToString(), workerId, workerId, "Name", DateTime.UtcNow, BouquetType.Standard, [])]);
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.CalculateDiscountByMounth(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()));
_workerStorageContract.Setup(x => x.GetList())
.Returns([new CustomerDataModel(workerId, "Full Name", "+79999999999", DateTime.UtcNow)]);
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.CalculateDiscountByMounth(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 BouquetDataModel(Guid.NewGuid().ToString(), workerId, workerId, "Name", DateTime.UtcNow, BouquetType.Standard, [])]);
_workerStorageContract.Setup(x => x.GetList())
.Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.CalculateDiscountByMounth(DateTime.UtcNow), Throws.TypeOf<StorageException>());
}
}

View File

@@ -0,0 +1,401 @@
using DaisiesBusinessLogic.Implementations;
using DaisiesContracts.DataModels;
using DaisiesContracts.Enums;
using DaisiesContracts.Exceptions;
using DaisiesContracts.StoragesContracts;
using Microsoft.Extensions.Logging;
using Moq;
namespace DaisiesTests.BusinessLogicsContractsTests;
[TestFixture]
internal class EmployeeBusinessLogicContractTests
{
private EmployeeBusinessLogicContract _workerBusinessLogicContract;
private Mock<IEmployeeStorageContract> _workerStorageContract;
[OneTimeSetUp]
public void OneTimeSetUp()
{
_workerStorageContract = new Mock<IEmployeeStorageContract>();
_workerBusinessLogicContract = new EmployeeBusinessLogicContract(_workerStorageContract.Object, new Mock<ILogger>().Object);
}
[SetUp]
public void SetUp()
{
_workerStorageContract.Reset();
}
[Test]
public void GetAllEmployeers_ReturnListOfRecords_Test()
{
//Arrange
var listOriginal = new List<EmployeeDataModel>()
{
new(Guid.NewGuid().ToString(), "fio 1", EmployeeRole.Helper, DateTime.Now, false),
new(Guid.NewGuid().ToString(), "fio 2", EmployeeRole.Helper, DateTime.Now, true),
new(Guid.NewGuid().ToString(), "fio 3", EmployeeRole.Helper, DateTime.Now, false),
};
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Returns(listOriginal);
//Act
var listOnlyActive = _workerBusinessLogicContract.GetAllEmployeers(true);
var list = _workerBusinessLogicContract.GetAllEmployeers(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), Times.Once);
_workerStorageContract.Verify(x => x.GetList(false, null, null), Times.Once);
}
[Test]
public void GetAllEmployeers_ReturnEmptyList_Test()
{
//Arrange
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Returns([]);
//Act
var listOnlyActive = _workerBusinessLogicContract.GetAllEmployeers(true);
var list = _workerBusinessLogicContract.GetAllEmployeers(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), Times.Exactly(2));
}
[Test]
public void GetAllEmployeers_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.GetAllEmployeers(It.IsAny<bool>()), Throws.TypeOf<NullListException>());
_workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Once);
}
[Test]
public void GetAllEmployeers_StorageThrowError_ThrowException_Test()
{
//Arrange
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.GetAllEmployeers(It.IsAny<bool>()), Throws.TypeOf<StorageException>());
_workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), null, null), Times.Once);
}
[Test]
public void GetAllEmployeersByEmploymentDate_ReturnListOfRecords_Test()
{
//Arrange
var date = DateTime.UtcNow;
var listOriginal = new List<EmployeeDataModel>()
{
new(Guid.NewGuid().ToString(), "fio 1", EmployeeRole.Helper, DateTime.Now, false),
new(Guid.NewGuid().ToString(), "fio 2", EmployeeRole.Helper, DateTime.Now, true),
new(Guid.NewGuid().ToString(), "fio 3", EmployeeRole.Helper, DateTime.Now, false),
};
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Returns(listOriginal);
//Act
var listOnlyActive = _workerBusinessLogicContract.GetAllEmployeersByEmploymentDate(date, date.AddDays(1), true);
var list = _workerBusinessLogicContract.GetAllEmployeersByEmploymentDate(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, date, date.AddDays(1)), Times.Once);
_workerStorageContract.Verify(x => x.GetList(false, date, date.AddDays(1)), Times.Once);
}
[Test]
public void GetAllEmployeersByEmploymentDate_ReturnEmptyList_Test()
{
//Arrange
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Returns([]);
//Act
var listOnlyActive = _workerBusinessLogicContract.GetAllEmployeersByEmploymentDate(DateTime.UtcNow, DateTime.UtcNow.AddDays(1), true);
var list = _workerBusinessLogicContract.GetAllEmployeersByEmploymentDate(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, It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Once);
_workerStorageContract.Verify(x => x.GetList(false, It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Once);
}
[Test]
public void GetAllEmployeersByEmploymentDate_IncorrectDates_ThrowException_Test()
{
//Arrange
var date = DateTime.UtcNow;
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.GetAllEmployeersByEmploymentDate(date, date, It.IsAny<bool>()), Throws.TypeOf<IncorrectDatesException>());
Assert.That(() => _workerBusinessLogicContract.GetAllEmployeersByEmploymentDate(date, date.AddSeconds(-1), It.IsAny<bool>()), Throws.TypeOf<IncorrectDatesException>());
_workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Never);
}
[Test]
public void GetAllEmployeersByEmploymentDate_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.GetAllEmployeersByEmploymentDate(DateTime.UtcNow, DateTime.UtcNow.AddDays(1), It.IsAny<bool>()), Throws.TypeOf<NullListException>());
_workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Once);
}
[Test]
public void GetAllEmployeersByEmploymentDate_StorageThrowError_ThrowException_Test()
{
//Arrange
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.GetAllEmployeersByEmploymentDate(DateTime.UtcNow, DateTime.UtcNow.AddDays(1), It.IsAny<bool>()), Throws.TypeOf<StorageException>());
_workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Once);
}
[Test]
public void GetWorkerByData_GetById_ReturnRecord_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
var record = new EmployeeDataModel(id, "fio", EmployeeRole.Administrator, DateTime.Now, false);
_workerStorageContract.Setup(x => x.GetElementById(id)).Returns(record);
//Act
var element = _workerBusinessLogicContract.GetEmployeerByData(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 EmployeeDataModel(Guid.NewGuid().ToString(), fio, EmployeeRole.Administrator, DateTime.Now, false);
_workerStorageContract.Setup(x => x.GetElementByFullName(fio)).Returns(record);
//Act
var element = _workerBusinessLogicContract.GetEmployeerByData(fio);
//Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.FullName, Is.EqualTo(fio));
_workerStorageContract.Verify(x => x.GetElementByFullName(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetWorkerByData_EmptyData_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.GetEmployeerByData(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _workerBusinessLogicContract.GetEmployeerByData(string.Empty), Throws.TypeOf<ArgumentNullException>());
_workerStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Never);
_workerStorageContract.Verify(x => x.GetElementByFullName(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetWorkerByData_GetById_NotFoundRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.GetEmployeerByData(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_workerStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
_workerStorageContract.Verify(x => x.GetElementByFullName(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetWorkerByData_GetByFio_NotFoundRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.GetEmployeerByData("fio"), Throws.TypeOf<ElementNotFoundException>());
_workerStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Never);
_workerStorageContract.Verify(x => x.GetElementByFullName(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.GetElementByFullName(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.GetEmployeerByData(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
Assert.That(() => _workerBusinessLogicContract.GetEmployeerByData("fio"), Throws.TypeOf<StorageException>());
_workerStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
_workerStorageContract.Verify(x => x.GetElementByFullName(It.IsAny<string>()), Times.Once);
}
[Test]
public void InsertWorker_CorrectRecord_Test()
{
//Arrange
var flag = false;
var record = new EmployeeDataModel(Guid.NewGuid().ToString(), "Full Name", EmployeeRole.Administrator, DateTime.Now, false);
_workerStorageContract.Setup(x => x.AddElement(It.IsAny<EmployeeDataModel>()))
.Callback((EmployeeDataModel x) =>
{
flag = x.Id == record.Id && x.FullName == record.FullName && x.Role == record.Role &&
x.EmploymentDate == record.EmploymentDate && x.IsActive == record.IsActive;
});
//Act
_workerBusinessLogicContract.InsertEmployeer(record);
//Assert
_workerStorageContract.Verify(x => x.AddElement(It.IsAny<EmployeeDataModel>()), Times.Once);
Assert.That(flag);
}
[Test]
public void InsertWorker_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_workerStorageContract.Setup(x => x.AddElement(It.IsAny<EmployeeDataModel>())).Throws(new ElementExistsException("Data", "Data"));
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.InsertEmployeer(new(Guid.NewGuid().ToString(), "Full Name", EmployeeRole.Administrator, DateTime.Now, false)), Throws.TypeOf<ElementExistsException>());
_workerStorageContract.Verify(x => x.AddElement(It.IsAny<EmployeeDataModel>()), Times.Once);
}
[Test]
public void InsertWorker_NullRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.InsertEmployeer(null), Throws.TypeOf<ArgumentNullException>());
_workerStorageContract.Verify(x => x.AddElement(It.IsAny<EmployeeDataModel>()), Times.Never);
}
[Test]
public void InsertWorker_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.InsertEmployeer(new EmployeeDataModel("id", "fio", EmployeeRole.Administrator, DateTime.Now, false)), Throws.TypeOf<ValidationException>());
_workerStorageContract.Verify(x => x.AddElement(It.IsAny<EmployeeDataModel>()), Times.Never);
}
[Test]
public void InsertWorker_StorageThrowError_ThrowException_Test()
{
//Arrange
_workerStorageContract.Setup(x => x.AddElement(It.IsAny<EmployeeDataModel>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.InsertEmployeer(new(Guid.NewGuid().ToString(), "Full Name", EmployeeRole.Administrator, DateTime.Now, false)), Throws.TypeOf<StorageException>());
_workerStorageContract.Verify(x => x.AddElement(It.IsAny<EmployeeDataModel>()), Times.Once);
}
[Test]
public void UpdateWorker_CorrectRecord_Test()
{
//Arrange
var flag = false;
var record = new EmployeeDataModel(Guid.NewGuid().ToString(), "Full Name", EmployeeRole.Administrator, DateTime.Now, false);
_workerStorageContract.Setup(x => x.UpdElement(It.IsAny<EmployeeDataModel>()))
.Callback((EmployeeDataModel x) =>
{
flag = x.Id == record.Id && x.FullName == record.FullName && x.Role == record.Role &&
x.EmploymentDate == record.EmploymentDate && x.IsActive == record.IsActive;
});
//Act
_workerBusinessLogicContract.UpdateEmployeer(record);
//Assert
_workerStorageContract.Verify(x => x.UpdElement(It.IsAny<EmployeeDataModel>()), Times.Once);
Assert.That(flag);
}
[Test]
public void UpdateWorker_RecordWithIncorrectData_ThrowException_Test()
{
//Arrange
_workerStorageContract.Setup(x => x.UpdElement(It.IsAny<EmployeeDataModel>())).Throws(new ElementNotFoundException(""));
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.UpdateEmployeer(new(Guid.NewGuid().ToString(), "Full Name", EmployeeRole.Administrator, DateTime.Now, false)), Throws.TypeOf<ElementNotFoundException>());
_workerStorageContract.Verify(x => x.UpdElement(It.IsAny<EmployeeDataModel>()), Times.Once);
}
[Test]
public void UpdateWorker_NullRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.UpdateEmployeer(null), Throws.TypeOf<ArgumentNullException>());
_workerStorageContract.Verify(x => x.UpdElement(It.IsAny<EmployeeDataModel>()), Times.Never);
}
[Test]
public void UpdateWorker_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.UpdateEmployeer(new EmployeeDataModel("id", "fio", EmployeeRole.Administrator, DateTime.Now, false)), Throws.TypeOf<ValidationException>());
_workerStorageContract.Verify(x => x.UpdElement(It.IsAny<EmployeeDataModel>()), Times.Never);
}
[Test]
public void UpdateWorker_StorageThrowError_ThrowException_Test()
{
//Arrange
_workerStorageContract.Setup(x => x.UpdElement(It.IsAny<EmployeeDataModel>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.UpdateEmployeer(new(Guid.NewGuid().ToString(), "Full Name", EmployeeRole.Administrator, DateTime.Now, false)), Throws.TypeOf<StorageException>());
_workerStorageContract.Verify(x => x.UpdElement(It.IsAny<EmployeeDataModel>()), 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.DeleteEmployeer(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.DeleteEmployeer(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.DeleteEmployeer(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _workerBusinessLogicContract.DeleteEmployeer(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.DeleteEmployeer("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.DeleteEmployeer(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_workerStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
}
}

View File

@@ -0,0 +1,332 @@
using DaisiesBusinessLogic.Implementations;
using DaisiesContracts.DataModels;
using DaisiesContracts.Exceptions;
using DaisiesContracts.StoragesContracts;
using Microsoft.Extensions.Logging;
using Moq;
using static NUnit.Framework.Internal.OSPlatform;
namespace DaisiesTests.BusinessLogicsContractsTests;
[TestFixture]
internal class FlowerBusinessLogicContractTests
{
private FlowerBusinessLogicContract _productBusinessLogicContract;
private Mock<IFlowerStorageContract> _productStorageContract;
[OneTimeSetUp]
public void OneTimeSetUp()
{
_productStorageContract = new Mock<IFlowerStorageContract>();
_productBusinessLogicContract = new FlowerBusinessLogicContract(_productStorageContract.Object, new Mock<ILogger>().Object);
}
[SetUp]
public void SetUp()
{
_productStorageContract.Reset();
}
[Test]
public void GetAllFlowers_ReturnListOfRecords_Test()
{
//Arrange
var listOriginal = new List<FlowerDataModel>()
{
new(Guid.NewGuid().ToString(), "name 1", 10),
new(Guid.NewGuid().ToString(), "name 2", 10),
new(Guid.NewGuid().ToString(), "name 3", 10),
};
_productStorageContract.Setup(x => x.GetList()).Returns(listOriginal);
//Act
var listOnlyActive = _productBusinessLogicContract.GetAllFlowers(true);
var list = _productBusinessLogicContract.GetAllFlowers(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(), Times.Exactly(2));
}
[Test]
public void GetAllFlowers_ReturnEmptyList_Test()
{
//Arrange
_productStorageContract.Setup(x => x.GetList()).Returns([]);
//Act
var listOnlyActive = _productBusinessLogicContract.GetAllFlowers(true);
var list = _productBusinessLogicContract.GetAllFlowers(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(), Times.Exactly(2));
}
[Test]
public void GetAllFlowers_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _productBusinessLogicContract.GetAllFlowers(It.IsAny<bool>()), Throws.TypeOf<NullListException>());
_productStorageContract.Verify(x => x.GetList(), Times.Once);
}
[Test]
public void GetAllFlowers_StorageThrowError_ThrowException_Test()
{
//Arrange
_productStorageContract.Setup(x => x.GetList()).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _productBusinessLogicContract.GetAllFlowers(It.IsAny<bool>()), Throws.TypeOf<StorageException>());
_productStorageContract.Verify(x => x.GetList(), Times.Once);
}
[Test]
public void GetProductByData_GetById_ReturnRecord_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
var record = new FlowerDataModel(id, "name", 10);
_productStorageContract.Setup(x => x.GetElementById(id)).Returns(record);
//Act
var element = _productBusinessLogicContract.GetFlowerByData(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 FlowerDataModel(Guid.NewGuid().ToString(), name, 10);
_productStorageContract.Setup(x => x.GetElementByName(name)).Returns(record);
//Act
var element = _productBusinessLogicContract.GetFlowerByData(name);
//Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.Name, 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.GetFlowerByData(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _productBusinessLogicContract.GetFlowerByData(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.GetFlowerByData(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.GetFlowerByData("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.GetFlowerByData(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
Assert.That(() => _productBusinessLogicContract.GetFlowerByData("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 FlowerDataModel(Guid.NewGuid().ToString(), "name", 10);
_productStorageContract.Setup(x => x.AddElement(It.IsAny<FlowerDataModel>()))
.Callback((FlowerDataModel x) =>
{
flag = x.Id == record.Id && x.Name == record.Name &&
x.Price == record.Price;
});
//Act
_productBusinessLogicContract.InsertFlower(record);
//Assert
_productStorageContract.Verify(x => x.AddElement(It.IsAny<FlowerDataModel>()), Times.Once);
Assert.That(flag);
}
[Test]
public void InsertProduct_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_productStorageContract.Setup(x => x.AddElement(It.IsAny<FlowerDataModel>())).Throws(new ElementExistsException("Data", "Data"));
//Act&Assert
Assert.That(() => _productBusinessLogicContract.InsertFlower(new(Guid.NewGuid().ToString(), "name", 10)), Throws.TypeOf<ElementExistsException>());
_productStorageContract.Verify(x => x.AddElement(It.IsAny<FlowerDataModel>()), Times.Once);
}
[Test]
public void InsertProduct_NullRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _productBusinessLogicContract.InsertFlower(null), Throws.TypeOf<ArgumentNullException>());
_productStorageContract.Verify(x => x.AddElement(It.IsAny<FlowerDataModel>()), Times.Never);
}
[Test]
public void InsertProduct_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _productBusinessLogicContract.InsertFlower(new FlowerDataModel("id", "name", 10)), Throws.TypeOf<ValidationException>());
_productStorageContract.Verify(x => x.AddElement(It.IsAny<FlowerDataModel>()), Times.Never);
}
[Test]
public void InsertProduct_StorageThrowError_ThrowException_Test()
{
//Arrange
_productStorageContract.Setup(x => x.AddElement(It.IsAny<FlowerDataModel>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _productBusinessLogicContract.InsertFlower(new(Guid.NewGuid().ToString(), "name", 10)), Throws.TypeOf<StorageException>());
_productStorageContract.Verify(x => x.AddElement(It.IsAny<FlowerDataModel>()), Times.Once);
}
[Test]
public void UpdateProduct_CorrectRecord_Test()
{
//Arrange
var flag = false;
var record = new FlowerDataModel(Guid.NewGuid().ToString(), "name", 10);
_productStorageContract.Setup(x => x.UpdElement(It.IsAny<FlowerDataModel>()))
.Callback((FlowerDataModel x) =>
{
flag = x.Id == record.Id && x.Name == record.Name &&
x.Price == record.Price;
});
//Act
_productBusinessLogicContract.UpdateFlower(record);
//Assert
_productStorageContract.Verify(x => x.UpdElement(It.IsAny<FlowerDataModel>()), Times.Once);
Assert.That(flag);
}
[Test]
public void UpdateProduct_RecordWithIncorrectData_ThrowException_Test()
{
//Arrange
_productStorageContract.Setup(x => x.UpdElement(It.IsAny<FlowerDataModel>())).Throws(new ElementNotFoundException(""));
//Act&Assert
Assert.That(() => _productBusinessLogicContract.UpdateFlower(new(Guid.NewGuid().ToString(), "name", 10)), Throws.TypeOf<ElementNotFoundException>());
_productStorageContract.Verify(x => x.UpdElement(It.IsAny<FlowerDataModel>()), Times.Once);
}
[Test]
public void UpdateProduct_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_productStorageContract.Setup(x => x.UpdElement(It.IsAny<FlowerDataModel>())).Throws(new ElementExistsException("Data", "Data"));
//Act&Assert
Assert.That(() => _productBusinessLogicContract.UpdateFlower(new(Guid.NewGuid().ToString(), "anme", 10)), Throws.TypeOf<ElementExistsException>());
_productStorageContract.Verify(x => x.UpdElement(It.IsAny<FlowerDataModel>()), Times.Once);
}
[Test]
public void UpdateProduct_NullRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _productBusinessLogicContract.UpdateFlower(null), Throws.TypeOf<ArgumentNullException>());
_productStorageContract.Verify(x => x.UpdElement(It.IsAny<FlowerDataModel>()), Times.Never);
}
[Test]
public void UpdateProduct_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _productBusinessLogicContract.UpdateFlower(new FlowerDataModel("id", "name", 10)), Throws.TypeOf<ValidationException>());
_productStorageContract.Verify(x => x.UpdElement(It.IsAny<FlowerDataModel>()), Times.Never);
}
[Test]
public void UpdateProduct_StorageThrowError_ThrowException_Test()
{
//Arrange
_productStorageContract.Setup(x => x.UpdElement(It.IsAny<FlowerDataModel>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _productBusinessLogicContract.UpdateFlower(new(Guid.NewGuid().ToString(), "name", 10)), Throws.TypeOf<StorageException>());
_productStorageContract.Verify(x => x.UpdElement(It.IsAny<FlowerDataModel>()), 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.DeleteFlower(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.DeleteFlower(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.DeleteFlower(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _productBusinessLogicContract.DeleteFlower(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.DeleteFlower("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.DeleteFlower(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_productStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
}
}

View File

@@ -10,7 +10,9 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging" Version="9.0.3" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.6.0" />
<PackageReference Include="Moq" Version="4.20.72" />
<PackageReference Include="NUnit" Version="3.13.3" />
<PackageReference Include="NUnit3TestAdapter" Version="4.2.1" />
<PackageReference Include="NUnit.Analyzers" Version="3.6.1" />
@@ -18,7 +20,9 @@
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\DaisiesBusinessLogic\DaisiesBusinessLogic.csproj" />
<ProjectReference Include="..\DaisiesContracts\DaisiesContracts.csproj" />
<ProjectReference Include="..\DaisiesDatabase\DaisiesDatabase.csproj" />
</ItemGroup>
</Project>

View File

@@ -102,5 +102,5 @@ public class BouquetDataModelTests
new BouquetDataModel(id, employeeId, customerId, name, compositionDate, type, items);
private static List<BouquetItemDataModel> CreateItems() =>
new List<BouquetItemDataModel> { new BouquetItemDataModel(Guid.NewGuid().ToString(), 1) };
new List<BouquetItemDataModel> { new BouquetItemDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 1) };
}

View File

@@ -6,14 +6,34 @@ namespace DaisiesTests.DataModelTests;
[TestFixture]
public class BouquetItemDataModelTests
{
[Test]
public void Validate_ThrowsException_WhenBouquetIdIsNullOrEmpty()
{
Assert.Multiple(() =>
{
Assert.That(() => CreateDataModel(null, Guid.NewGuid().ToString(), 1).Validate(),
Throws.TypeOf<ValidationException>());
Assert.That(() => CreateDataModel(string.Empty, Guid.NewGuid().ToString(), 1).Validate(),
Throws.TypeOf<ValidationException>());
});
}
[Test]
public void Validate_ThrowsException_WhenBouquetIdIsNotGuid()
{
Assert.That(() => CreateDataModel("invalid-guid", Guid.NewGuid().ToString(), 1).Validate(),
Throws.TypeOf<ValidationException>());
}
[Test]
public void Validate_ThrowsException_WhenFlowerIdIsNullOrEmpty()
{
Assert.Multiple(() =>
{
Assert.That(() => CreateDataModel(null, 1).Validate(),
Assert.That(() => CreateDataModel(Guid.NewGuid().ToString(), null, 1).Validate(),
Throws.TypeOf<ValidationException>());
Assert.That(() => CreateDataModel(string.Empty, 1).Validate(),
Assert.That(() => CreateDataModel(Guid.NewGuid().ToString(), string.Empty, 1).Validate(),
Throws.TypeOf<ValidationException>());
});
}
@@ -21,14 +41,15 @@ public class BouquetItemDataModelTests
[Test]
public void Validate_ThrowsException_WhenFlowerIdIsNotGuid()
{
Assert.That(() => CreateDataModel("invalid-guid", 1).Validate(),
Assert.That(() => CreateDataModel(Guid.NewGuid().ToString(), "invalid-guid", 1).Validate(),
Throws.TypeOf<ValidationException>());
}
[Test]
public void Validate_ThrowsException_WhenQuantityIsNotPositive()
{
Assert.That(() => CreateDataModel(Guid.NewGuid().ToString(), 0).Validate(),
Assert.That(() => CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 0).Validate(),
Throws.TypeOf<ValidationException>());
}
@@ -36,18 +57,20 @@ public class BouquetItemDataModelTests
public void AllFieldsAreCorrectTest()
{
var flowerId = Guid.NewGuid().ToString();
var bouquetId = Guid.NewGuid().ToString();
var quantity = 1;
var item = CreateDataModel(flowerId, quantity);
var item = CreateDataModel(bouquetId, flowerId, quantity);
Assert.That(() => item.Validate(), Throws.Nothing);
Assert.Multiple(() =>
{
Assert.That(item.BouquetId, Is.EqualTo(bouquetId));
Assert.That(item.FlowerId, Is.EqualTo(flowerId));
Assert.That(item.Quantity, Is.EqualTo(quantity));
});
}
private static BouquetItemDataModel CreateDataModel(string flowerId, int quantity) =>
new BouquetItemDataModel(flowerId, quantity);
private static BouquetItemDataModel CreateDataModel(string bouquetId, string flowerId, int quantity) =>
new BouquetItemDataModel(bouquetId, flowerId, quantity);
}

View File

@@ -79,5 +79,5 @@ public class CustomerDataModelTests
}
private static CustomerDataModel CreateDataModel(string id, string fullName, string phoneNumber, decimal discount, DateTime registrationDate) =>
new CustomerDataModel(id, fullName, phoneNumber, discount, registrationDate);
new CustomerDataModel(id, fullName, phoneNumber, registrationDate);
}

View File

@@ -0,0 +1,57 @@
using DaisiesContracts.DataModels;
using DaisiesContracts.Exceptions;
namespace DaisiesTests.DataModelTests;
[TestFixture]
public class CustomerDiscountDataModelTests
{
[Test]
public void Validate_ThrowsException_WhenCustomerIdIsNullOrEmpty()
{
Assert.Multiple(() =>
{
Assert.That(() => CreateDataModel(null, DateTime.UtcNow, 20m).Validate(),
Throws.TypeOf<ValidationException>());
Assert.That(() => CreateDataModel(string.Empty, DateTime.UtcNow, 20m).Validate(),
Throws.TypeOf<ValidationException>());
});
}
[Test]
public void Validate_ThrowsException_WhenCustomerIdIsNotGuid()
{
Assert.That(() => CreateDataModel("invalid-guid", DateTime.UtcNow, 20m).Validate(),
Throws.TypeOf<ValidationException>());
}
[Test]
public void Validate_ThrowsException_WhenDiscountIsOutOfRange()
{
Assert.That(() => CreateDataModel(Guid.NewGuid().ToString(), DateTime.UtcNow, -1m).Validate(),
Throws.TypeOf<ValidationException>());
Assert.That(() => CreateDataModel(Guid.NewGuid().ToString(), DateTime.UtcNow, 101m).Validate(),
Throws.TypeOf<ValidationException>());
}
[Test]
public void AllFieldsAreCorrectTest()
{
var discountDateTime = DateTime.UtcNow;
var customerId = Guid.NewGuid().ToString();
var discount = 20m;
var customerDiscount = CreateDataModel(customerId, discountDateTime, discount);
Assert.That(() => customerDiscount.Validate(), Throws.Nothing);
Assert.Multiple(() =>
{
Assert.That(customerDiscount.DiscountDateTime, Is.EqualTo(discountDateTime));
Assert.That(customerDiscount.CustomerId, Is.EqualTo(customerId));
Assert.That(customerDiscount.Discount, Is.EqualTo(discount));
});
}
private static CustomerDiscountDataModel CreateDataModel(string customerId, DateTime dateTime, decimal discount) =>
new CustomerDiscountDataModel(customerId, dateTime, discount);
}

View File

@@ -0,0 +1,8 @@
using DaisiesContracts.Infrastrcuture;
namespace DaisiesTests.Infrastructure;
internal class ConfigurationDatabaseTest : IConfigurationDatabase
{
public string ConnectionString => "Host=localhost;Port=5432;Database=ee;Username=postgres;Password=123456789;";
}

View File

@@ -0,0 +1,24 @@
using DaisiesDatabase;
using DaisiesTests.Infrastructure;
namespace DaisiesTests.StorageContractsTests;
internal class BaseStorageContractTests
{
protected DaisiesDbContext DaisiesDbContext { get; private set; }
[OneTimeSetUp]
public void OneTimeSetUp()
{
DaisiesDbContext = new DaisiesDbContext(new ConfigurationDatabaseTest());
DaisiesDbContext.Database.EnsureDeleted();
DaisiesDbContext.Database.EnsureCreated();
}
[OneTimeTearDown]
public void OneTimeTearDown()
{
DaisiesDbContext.Database.EnsureDeleted();
DaisiesDbContext.Dispose();
}
}

View File

@@ -0,0 +1,291 @@
using DaisiesContracts.DataModels;
using DaisiesContracts.Exceptions;
using DaisiesDatabase.Implementations;
using DaisiesDatabase.Models;
using DaisiesTests.StorageContractsTests;
using Microsoft.EntityFrameworkCore;
namespace DaisiesTests.StoragesContractsTests;
internal class BouquetStorageContractTests : BaseStorageContractTests
{
private BouquetStorageContract _orderStorageContract;
private Customer _customer;
private Employee _worker;
private Flower _product;
[SetUp]
public void SetUp()
{
_orderStorageContract = new BouquetStorageContract(DaisiesDbContext);
_worker = InsertWorkerToDatabaseAndReturn();
_product = InsertProductToDatabaseAndReturn();
_customer = InsertBuyerToDatabaseAndReturn();
}
[TearDown]
public void TearDown()
{
DaisiesDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Bouquets\" CASCADE; ");
DaisiesDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Employeers\" CASCADE; ");
DaisiesDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Flowers\" CASCADE; ");
DaisiesDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Customers\" CASCADE; ");
}
[Test]
public void Try_GetList_WhenHaveRecords_Test()
{
var Order = InsertOrderToDatabaseAndReturn(_worker.Id, _customer.Id, products: [(_product.Id, 1)]);
InsertOrderToDatabaseAndReturn(_worker.Id, _customer.Id, products: [(_product.Id, 5)]);
var list = _orderStorageContract.GetList();
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(2));
AssertElement(list.First(x => x.Id == Order.Id), Order);
}
[Test]
public void Try_GetList_WhenNoRecords_Test()
{
var list = _orderStorageContract.GetList();
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.Empty);
}
[Test]
public void Try_GetList_ByPeriod_Test()
{
InsertOrderToDatabaseAndReturn(_worker.Id, _customer.Id, OrderDate: DateTime.UtcNow.AddDays(-1).AddMinutes(-3), products: [(_product.Id, 1)]);
InsertOrderToDatabaseAndReturn(_worker.Id, _customer.Id, OrderDate: DateTime.UtcNow.AddDays(-1).AddMinutes(3), products: [(_product.Id, 1)]);
var list = _orderStorageContract.GetList(startDate: DateTime.UtcNow.AddDays(-1), endDate: DateTime.UtcNow.AddDays(1));
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(1));
}
[Test]
public void Try_GetList_ByWorkerId_Test()
{
var worker = InsertWorkerToDatabaseAndReturn("Other worker", "test4@gmail.com");
InsertOrderToDatabaseAndReturn(_worker.Id, _customer.Id, products: [(_product.Id, 1)]);
InsertOrderToDatabaseAndReturn(_worker.Id, _customer.Id, products: [(_product.Id, 1)]);
var list = _orderStorageContract.GetList(employeeId: _worker.Id);
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(2));
Assert.That(list.All(x => x.EmployeeId == _worker.Id));
}
[Test]
public void Try_GetList_ByProductId_Test()
{
var product = InsertProductToDatabaseAndReturn("Other name");
InsertOrderToDatabaseAndReturn(_worker.Id, _customer.Id, products: [(_product.Id, 5)]);
InsertOrderToDatabaseAndReturn(_worker.Id, _customer.Id, products: [(_product.Id, 1), (product.Id, 4)]);
var list = _orderStorageContract.GetList(flowerId: _product.Id);
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(2));
Assert.That(list.All(x => x.Items!.Any(y => y.FlowerId ==
_product.Id)));
}
[Test]
public void Try_GetList_ByAllParameters_Test()
{
var worker = InsertWorkerToDatabaseAndReturn("Other worker", "test2@gmail.com");
var buyer = InsertBuyerToDatabaseAndReturn("Other name1", "location");
var product = InsertProductToDatabaseAndReturn("Other name2");
InsertOrderToDatabaseAndReturn(_worker.Id, _customer.Id, OrderDate:
DateTime.UtcNow.AddDays(-1).AddMinutes(-3), products: [(_product.Id, 1)]);
InsertOrderToDatabaseAndReturn(worker.Id, _customer.Id, OrderDate:
DateTime.UtcNow.AddDays(-1).AddMinutes(3), products: [(_product.Id, 1)]);
InsertOrderToDatabaseAndReturn(worker.Id, _customer.Id, OrderDate:
DateTime.UtcNow.AddDays(-1).AddMinutes(3), products: [(product.Id, 1)]);
InsertOrderToDatabaseAndReturn(_worker.Id, buyer.Id, OrderDate:
DateTime.UtcNow.AddDays(1).AddMinutes(-3), products: [(_product.Id, 1)]);
InsertOrderToDatabaseAndReturn(_worker.Id, _customer.Id, OrderDate:
DateTime.UtcNow.AddDays(1).AddMinutes(-3), products: [(product.Id, 1)]);
var list = _orderStorageContract.GetList(startDate:
DateTime.UtcNow.AddDays(-1), endDate: DateTime.UtcNow.AddDays(1), employeeId: _worker.Id, flowerId: product.Id);
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(1));
}
[Test]
public void Try_GetElementById_WhenHaveRecord_Test()
{
var Order = InsertOrderToDatabaseAndReturn(_worker.Id, _customer.Id,
products: [(_product.Id, 1)]);
AssertElement(_orderStorageContract.GetElementById(Order.Id), Order);
}
[Test]
public void Try_GetElementById_WhenNoRecord_Test()
{
InsertOrderToDatabaseAndReturn(_worker.Id, _customer.Id, products: [(_product.Id, 1)]);
Assert.That(() =>
_orderStorageContract.GetElementById(Guid.NewGuid().ToString()), Is.Null);
}
[Test]
public void Try_GetElementById_WhenRecordHasCanceled_Test()
{
var Order = InsertOrderToDatabaseAndReturn(_worker.Id, _customer.Id, products: [(_product.Id, 1)], name: "fio fio");
AssertElement(_orderStorageContract.GetElementById(Order.Id), Order);
}
[Test]
public void Try_AddElement_Test()
{
var order = CreateModel(Guid.NewGuid().ToString(), _worker.Id, _customer.Id, "fio fio", [_product.Id]);
_orderStorageContract.AddElement(order);
AssertElement(GetOrderFromDatabaseById(order.Id), order);
}
[Test]
public void Try_AddElement_WhenIsDeletedIsTrue_Test()
{
var Order = CreateModel(Guid.NewGuid().ToString(), _worker.Id, _customer.Id, "fio fio", [_product.Id]);
Assert.That(() => _orderStorageContract.AddElement(Order), Throws.Nothing);
AssertElement(GetOrderFromDatabaseById(Order.Id), CreateModel(Order.Id, _worker.Id, _customer.Id, "fio fio", [_product.Id]));
}
[Test]
public void Try_DelElement_Test()
{
var Order = InsertOrderToDatabaseAndReturn(_worker.Id, _customer.Id,
products: [(_product.Id, 1)], name: "name fio");
_orderStorageContract.DelElement(Order.Id);
var element = GetOrderFromDatabaseById(Order.Id);
Assert.That(element, Is.Null);
}
[Test]
public void Try_DelElement_WhenNoRecordWithThisId_Test()
{
Assert.That(() => _orderStorageContract.DelElement(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
}
private Customer InsertBuyerToDatabaseAndReturn(string name = "test", string phone = "+79876664455")
{
var customers = new Customer()
{
Id = Guid.NewGuid().ToString(),
FullName = name,
PhoneNumber = phone
};
DaisiesDbContext.Customers.Add(customers);
DaisiesDbContext.SaveChanges();
return customers;
}
private Employee InsertWorkerToDatabaseAndReturn(string fio = "test", string email = "test@gmail.com")
{
var worker = new Employee()
{
Id = Guid.NewGuid().ToString(),
FullName = fio,
Role = DaisiesContracts.Enums.EmployeeRole.Florist
};
DaisiesDbContext.Employeers.Add(worker);
DaisiesDbContext.SaveChanges();
return worker;
}
private Flower InsertProductToDatabaseAndReturn(string productName = "test", decimal price = 1)
{
var product = new Flower()
{
Id = Guid.NewGuid().ToString(),
Name = productName,
Price = price,
};
DaisiesDbContext.Flowers.Add(product);
DaisiesDbContext.SaveChanges();
return product;
}
private Bouquet InsertOrderToDatabaseAndReturn(string workerId, string customerId,
DateTime? OrderDate = null, string name = "fio",
List<(string, int)>? products = null)
{
var bouquet = new Bouquet()
{
EmployeeId = workerId,
CustomerId = customerId,
CompositionDate = OrderDate ?? DateTime.UtcNow,
Id = Guid.NewGuid().ToString(),
Name = name,
Items = []
};
if (products is not null)
{
foreach (var elem in products)
{
bouquet.Items.Add(new BouquetItem
{
Id = Guid.NewGuid().ToString(),
FlowerId = elem.Item1,
BouquetId = bouquet.Id,
Quantity = elem.Item2,
});
}
}
DaisiesDbContext.Bouquets.Add(bouquet);
DaisiesDbContext.SaveChanges();
return bouquet;
}
private static void AssertElement(BouquetDataModel? actual, Bouquet expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.Id, Is.EqualTo(expected.Id));
Assert.That(actual.EmployeeId, Is.EqualTo(expected.EmployeeId));
Assert.That(actual.CustomerId, Is.EqualTo(expected.CustomerId));
Assert.That(actual.Name, Is.EqualTo(expected.Name));
});
if (expected.Items is not null)
{
Assert.That(actual.Items, Is.Not.Null); Assert.That(actual.Items,
Has.Count.EqualTo(expected.Items.Count));
for (int i = 0; i < actual.Items.Count; ++i)
{
Assert.Multiple(() =>
{
Assert.That(actual.Items[i].FlowerId,
Is.EqualTo(expected.Items[i].FlowerId));
Assert.That(actual.Items[i].Quantity,
Is.EqualTo(expected.Items[i].Quantity));
});
}
}
else
{
Assert.That(actual.Items, Is.Null);
}
}
private static BouquetDataModel CreateModel(string id, string workerId, string? customerId, string name, List<string> productIds)
{
var products = productIds.Select(x => new BouquetItemDataModel(id, x, 1)).ToList();
return new(id, workerId, customerId, name, DateTime.UtcNow, DaisiesContracts.Enums.BouquetType.Standard, products);
}
private Bouquet? GetOrderFromDatabaseById(string id) => DaisiesDbContext.Bouquets.Include(x => x.Items).FirstOrDefault(x => x.Id == id);
private static void AssertElement(Bouquet? actual, BouquetDataModel expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.Id, Is.EqualTo(expected.Id));
Assert.That(actual.EmployeeId, Is.EqualTo(expected.EmployeeId));
Assert.That(actual.CustomerId, Is.EqualTo(expected.CustomerId));
Assert.That(actual.Name, Is.EqualTo(expected.Name));
});
if (expected.Items is not null)
{
Assert.That(actual.Items, Is.Not.Null);
Assert.That(actual.Items, Has.Count.EqualTo(expected.Items.Count));
for (int i = 0; i < actual.Items.Count; ++i)
{
Assert.Multiple(() =>
{
Assert.That(actual.Items[i].FlowerId,
Is.EqualTo(expected.Items[i].FlowerId));
Assert.That(actual.Items[i].Quantity,
Is.EqualTo(expected.Items[i].Quantity));
});
}
}
else
{
Assert.That(actual.Items, Is.Null);
}
}
}

View File

@@ -0,0 +1,153 @@
using DaisiesContracts.DataModels;
using DaisiesDatabase.Implementations;
using DaisiesDatabase.Models;
using DaisiesTests.StorageContractsTests;
using Microsoft.EntityFrameworkCore;
using CustomerDiscount = DaisiesDatabase.Models.CustomerDiscount;
namespace DaisiesTests.StoragesContractsTests;
internal class CustomerDiscountStorageContractTests : BaseStorageContractTests
{
private CustomerDiscountStorageContract _salaryStorageContract;
private Customer _worker;
[SetUp]
public void SetUp()
{
_salaryStorageContract = new CustomerDiscountStorageContract(DaisiesDbContext);
_worker = InsertWorkerToDatabaseAndReturn();
}
[TearDown]
public void TearDown()
{
DaisiesDbContext.Database.ExecuteSqlRaw("TRUNCATE \"CustomerDiscounts\" CASCADE; ");
DaisiesDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Customers\" CASCADE; ");
}
[Test]
public void Try_GetList_WhenHaveRecords_Test()
{
var salary = InsertSalaryToDatabaseAndReturn(Guid.NewGuid().ToString(), _worker.Id, workerSalary: 100);
InsertSalaryToDatabaseAndReturn(Guid.NewGuid().ToString(), _worker.Id);
InsertSalaryToDatabaseAndReturn(Guid.NewGuid().ToString(), _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(Guid.NewGuid().ToString(), _worker.Id, salaryDate: DateTime.UtcNow.AddDays(-2));
InsertSalaryToDatabaseAndReturn(Guid.NewGuid().ToString(), _worker.Id, salaryDate: DateTime.UtcNow.AddDays(-1).AddMinutes(-5));
InsertSalaryToDatabaseAndReturn(Guid.NewGuid().ToString(), _worker.Id, salaryDate: DateTime.UtcNow.AddDays(-1).AddMinutes(5));
InsertSalaryToDatabaseAndReturn(Guid.NewGuid().ToString(), _worker.Id, salaryDate: DateTime.UtcNow.AddDays(1).AddMinutes(-5));
InsertSalaryToDatabaseAndReturn(Guid.NewGuid().ToString(), _worker.Id, salaryDate: DateTime.UtcNow.AddDays(1).AddMinutes(5));
InsertSalaryToDatabaseAndReturn(Guid.NewGuid().ToString(), _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", "79996547878");
InsertSalaryToDatabaseAndReturn(Guid.NewGuid().ToString(), _worker.Id);
InsertSalaryToDatabaseAndReturn(Guid.NewGuid().ToString(), _worker.Id);
InsertSalaryToDatabaseAndReturn(Guid.NewGuid().ToString(), 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.CustomerId == _worker.Id));
});
}
[Test]
public void Try_GetList_ByWorkerOnlyInDatePeriod_Test()
{
var worker = InsertWorkerToDatabaseAndReturn("name 2", "79996547878");
InsertSalaryToDatabaseAndReturn(Guid.NewGuid().ToString(), _worker.Id, salaryDate: DateTime.UtcNow.AddDays(-2));
InsertSalaryToDatabaseAndReturn(Guid.NewGuid().ToString(), _worker.Id, salaryDate: DateTime.UtcNow.AddDays(-1).AddMinutes(5));
InsertSalaryToDatabaseAndReturn(Guid.NewGuid().ToString(), worker.Id, salaryDate: DateTime.UtcNow.AddDays(-1).AddMinutes(5));
InsertSalaryToDatabaseAndReturn(Guid.NewGuid().ToString(), _worker.Id, salaryDate: DateTime.UtcNow.AddDays(1).AddMinutes(-5));
InsertSalaryToDatabaseAndReturn(Guid.NewGuid().ToString(), worker.Id, salaryDate: DateTime.UtcNow.AddDays(1).AddMinutes(-5));
InsertSalaryToDatabaseAndReturn(Guid.NewGuid().ToString(), _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.CustomerId == _worker.Id));
});
}
[Test]
public void Try_AddElement_Test()
{
var salary = CreateModel(_worker.Id);
_salaryStorageContract.AddElement(salary);
AssertElement(GetSalaryFromDatabaseByCustomerId(_worker.Id), salary);
}
private Customer InsertWorkerToDatabaseAndReturn(string workerFIO = "fio", string phoneNumber = "+76549999999")
{
var worker = new Customer()
{
Id = Guid.NewGuid().ToString(),
PhoneNumber = phoneNumber,
FullName = workerFIO,
};
DaisiesDbContext.Customers.Add(worker);
DaisiesDbContext.SaveChanges();
return worker;
}
private CustomerDiscount InsertSalaryToDatabaseAndReturn(string id, string workerId, decimal workerSalary = 1, DateTime? salaryDate = null)
{
var salary = new CustomerDiscount()
{
Id = id,
CustomerId = workerId,
Discount = workerSalary,
DiscountDateTime = salaryDate ?? DateTime.UtcNow
};
DaisiesDbContext.CustomerDiscounts.Add(salary);
DaisiesDbContext.SaveChanges();
return salary;
}
private static void AssertElement(CustomerDiscountDataModel? actual, CustomerDiscount expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.CustomerId, Is.EqualTo(expected.CustomerId));
Assert.That(actual.Discount, Is.EqualTo(expected.Discount));
});
}
private static CustomerDiscountDataModel CreateModel(string customerId, decimal discountSize = 1, DateTime? salaryDate = null) => new(customerId, salaryDate ?? DateTime.UtcNow, discountSize);
private CustomerDiscount? GetSalaryFromDatabaseByCustomerId(string id) => DaisiesDbContext.CustomerDiscounts.FirstOrDefault(x => x.CustomerId == id);
private static void AssertElement(CustomerDiscount? actual, CustomerDiscountDataModel expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.CustomerId, Is.EqualTo(expected.CustomerId));
Assert.That(actual.Discount, Is.EqualTo(expected.Discount));
});
}
}

View File

@@ -0,0 +1,224 @@
using DaisiesContracts.DataModels;
using DaisiesContracts.Exceptions;
using DaisiesDatabase;
using DaisiesDatabase.Implementations;
using DaisiesDatabase.Models;
using DaisiesTests.StorageContractsTests;
using Microsoft.EntityFrameworkCore;
using System;
namespace DaisiesTests.StoragesContractsTests;
internal class CustomerStorageContractTests : BaseStorageContractTests
{
private CustomerStorageContract _buyerStorageContract;
[SetUp]
public void SetUp()
{
_buyerStorageContract = new CustomerStorageContract(DaisiesDbContext);
}
[TearDown]
public void TearDown()
{
DaisiesDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Customers\" CASCADE; ");
}
[Test]
public void Try_GetList_WhenHaveRecords_Test()
{
var buyer = InsertBuyerToDatabaseAndReturn(Guid.NewGuid().ToString(), phoneNumber: "+5-555-555-55-45");
InsertBuyerToDatabaseAndReturn(Guid.NewGuid().ToString(), phoneNumber: "+6-666-666-66-46");
InsertBuyerToDatabaseAndReturn(Guid.NewGuid().ToString(), phoneNumber: "+7-777-777-77-47");
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(), "New Fio", "+5-666-555-88-99");
AssertElement(_buyerStorageContract.GetElementById(buyer.Id), buyer);
}
[Test]
public void Try_GetElementById_WhenNoRecord_Test()
{
InsertBuyerToDatabaseAndReturn(Guid.NewGuid().ToString(), "New Fio", "+5-666-645-55-56");
Assert.That(() => _buyerStorageContract.GetElementById(Guid.NewGuid().ToString()), Is.Null);
}
[Test]
public void Try_GetElementByFIO_WhenHaveRecord_Test()
{
var buyer = InsertBuyerToDatabaseAndReturn(Guid.NewGuid().ToString(), "New Fio4444", "+5-987-555-55-56");
AssertElement(_buyerStorageContract.GetElementByFullName(buyer.FullName), buyer);
}
[Test]
public void Try_GetElementByFIO_WhenNoRecord_Test()
{
InsertBuyerToDatabaseAndReturn(Guid.NewGuid().ToString(), "New Fio32132", "+5-635-555-55-56");
Assert.That(() => _buyerStorageContract.GetElementByFullName("New Fio222222222222"), Is.Null);
}
[Test]
public void Try_GetElementByPhoneNumber_WhenHaveRecord_Test()
{
var buyer =
InsertBuyerToDatabaseAndReturn(Guid.NewGuid().ToString(), "New Fio", "+5-126-555-55-56");
AssertElement(_buyerStorageContract.GetElementByPhoneNumber(buyer.PhoneNumber), buyer);
}
[Test]
public void Try_GetElementByPhoneNumber_WhenNoRecord_Test()
{
InsertBuyerToDatabaseAndReturn(Guid.NewGuid().ToString(), "New Fio", "+5-664-555-55-56");
Assert.That(() => _buyerStorageContract.GetElementByPhoneNumber("+8- 888 - 888 - 78 - 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-56");
InsertBuyerToDatabaseAndReturn(buyer.Id, "New Fio", "+5-666-555-55-56");
Assert.That(() => _buyerStorageContract.AddElement(buyer),
Throws.TypeOf<ElementExistsException>());
}
[Test]
public void Try_AddElement_WhenHaveRecordWithSamePhoneNumber_Test()
{
var buyer = CreateModel(Guid.NewGuid().ToString(), "New Fio", "+5-321-555-55-58");
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");
InsertBuyerToDatabaseAndReturn(buyer.Id, "New Fio", phoneNumber: "+7-147-777-77-77");
_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-321-555-55-55");
InsertBuyerToDatabaseAndReturn(buyer.Id, phoneNumber: "+7-111-777-77-77");
InsertBuyerToDatabaseAndReturn(Guid.NewGuid().ToString(), phoneNumber: buyer.PhoneNumber);
Assert.That(() => _buyerStorageContract.UpdElement(buyer), Throws.TypeOf<StorageException>());
}
[Test]
public void Try_DelElement_Test()
{
var buyer =
InsertBuyerToDatabaseAndReturn(Guid.NewGuid().ToString(), phoneNumber: "+7-777-332-77-77");
_buyerStorageContract.DelElement(buyer.Id);
var element = GetBuyerFromDatabase(buyer.Id);
Assert.That(element, Is.Null);
}
[Test]
public void Try_DelElement_WhenHaveOrdersByThisBuyer_Test()
{
var buyer = InsertBuyerToDatabaseAndReturn(Guid.NewGuid().ToString(), phoneNumber: "+7-777-777-01-77");
var workerId = Guid.NewGuid().ToString();
DaisiesDbContext.Employeers.Add(new Employee()
{
Id = workerId,
FullName = "test",
Role = DaisiesContracts.Enums.EmployeeRole.Administrator,
IsActive = true,
EmploymentDate = DateTime.UtcNow.AddDays(-1)
});
DaisiesDbContext.Bouquets.Add(new Bouquet()
{
Id = Guid.NewGuid().ToString(),
EmployeeId = workerId,
CustomerId = buyer.Id,
Name = "name"
});
DaisiesDbContext.Bouquets.Add(new Bouquet()
{
Id = Guid.NewGuid().ToString(),
EmployeeId = workerId,
CustomerId = buyer.Id,
Name = "name"
});
DaisiesDbContext.SaveChanges();
var OrdersBeforeDelete = DaisiesDbContext.Bouquets.Where(x => x.CustomerId == buyer.Id).ToArray();
_buyerStorageContract.DelElement(buyer.Id);
var element = GetBuyerFromDatabase(buyer.Id);
var OrdersAfterDelete = DaisiesDbContext.Bouquets.Where(x => x.CustomerId == buyer.Id).ToArray();
Assert.Multiple(() =>
{
Assert.That(element, Is.Null);
Assert.That(OrdersBeforeDelete, Has.Length.EqualTo(2));
Assert.That(OrdersAfterDelete, Is.Empty);
Assert.That(DaisiesDbContext.Bouquets.Count(), Is.EqualTo(0));
});
}
[Test]
public void Try_DelElement_WhenNoRecordWithThisId_Test()
{
Assert.That(() => _buyerStorageContract.DelElement(Guid.NewGuid().ToString()),
Throws.TypeOf<ElementNotFoundException>());
}
private Customer InsertBuyerToDatabaseAndReturn(string id, string fio = "test", string phoneNumber = "+7-777-777-77-77")
{
var buyer = new Customer()
{
Id = id,
FullName = fio,
PhoneNumber = phoneNumber,
RegistrationDate = DateTime.UtcNow,
};
DaisiesDbContext.Customers.Add(buyer);
DaisiesDbContext.SaveChanges();
return buyer;
}
private static void AssertElement(CustomerDataModel? actual, Customer expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.Id, Is.EqualTo(expected.Id));
Assert.That(actual.FullName, Is.EqualTo(expected.FullName));
Assert.That(actual.PhoneNumber, Is.EqualTo(expected.PhoneNumber));
});
}
private static CustomerDataModel CreateModel(string id, string fio = "test", string phoneNumber = "+7-777-777-77-77") => new(id, fio, phoneNumber, DateTime.UtcNow);
private Customer? GetBuyerFromDatabase(string id) => DaisiesDbContext.Customers.FirstOrDefault(x => x.Id == id);
private static void AssertElement(Customer? actual, CustomerDataModel expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.Id, Is.EqualTo(expected.Id));
Assert.That(actual.FullName, Is.EqualTo(expected.FullName));
Assert.That(actual.PhoneNumber, Is.EqualTo(expected.PhoneNumber));
});
}
}

View File

@@ -0,0 +1,169 @@
using Microsoft.EntityFrameworkCore;
using DaisiesContracts.DataModels;
using DaisiesContracts.Exceptions;
using DaisiesDatabase.Implementations;
using DaisiesDatabase.Models;
using DaisiesTests.StorageContractsTests;
using DaisiesContracts.Enums;
namespace DaisiesTests.StoragesContractsTests;
[TestFixture]
internal class EmployeeStorageContractTests : BaseStorageContractTests
{
private EmployeeStorageContract _workerStorageContract;
[SetUp]
public void SetUp()
{
_workerStorageContract = new EmployeeStorageContract(DaisiesDbContext);
}
[TearDown]
public void TearDown()
{
DaisiesDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Employeers\" 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_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_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_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, isActive: false);
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.IsActive);
}
[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, isActive: false);
Assert.That(() => _workerStorageContract.DelElement(worker.Id), Throws.TypeOf<ElementNotFoundException>());
}
private Employee InsertWorkerToDatabaseAndReturn(string id, string fio = "test", EmployeeRole role = EmployeeRole.Helper,
DateTime? employmentDate = null, bool isActive = true)
{
var worker = new Employee()
{
Id = id,
FullName = fio,
Role = role,
EmploymentDate = employmentDate ?? DateTime.UtcNow,
IsActive = isActive
};
DaisiesDbContext.Employeers.Add(worker);
DaisiesDbContext.SaveChanges();
return worker;
}
private static void AssertElement(EmployeeDataModel? actual, Employee expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.Id, Is.EqualTo(expected.Id));
Assert.That(actual.FullName, Is.EqualTo(expected.FullName));
Assert.That(actual.Role, Is.EqualTo(expected.Role));
Assert.That(actual.EmploymentDate, Is.EqualTo(expected.EmploymentDate));
Assert.That(actual.IsActive, Is.EqualTo(expected.IsActive));
});
}
private static EmployeeDataModel CreateModel(string id, string fio = "fio", EmployeeRole role = EmployeeRole.Helper,
DateTime? employmentDate = null, bool isActive = true) =>
new(id, fio, role, employmentDate ?? DateTime.UtcNow, isActive);
private Employee? GetWorkerFromDatabase(string id) => DaisiesDbContext.Employeers.FirstOrDefault(x => x.Id == id);
private static void AssertElement(Employee? actual, EmployeeDataModel expected)
{
Assert.That(actual, Is.Not.Null); Assert.Multiple(() =>
{
Assert.That(actual.Id, Is.EqualTo(expected.Id));
Assert.That(actual.FullName, Is.EqualTo(expected.FullName));
Assert.That(actual.Role, Is.EqualTo(expected.Role));
Assert.That(actual.EmploymentDate, Is.EqualTo(expected.EmploymentDate));
Assert.That(actual.IsActive, Is.EqualTo(expected.IsActive));
});
}
}

View File

@@ -0,0 +1,169 @@
using DaisiesContracts.DataModels;
using DaisiesContracts.Exceptions;
using DaisiesDatabase.Implementations;
using DaisiesDatabase.Models;
using DaisiesTests.StorageContractsTests;
using Microsoft.EntityFrameworkCore;
namespace DaisiesTests.StoragesContractsTests;
[TestFixture]
internal class FlowerStorageContractTests : BaseStorageContractTests
{
private FlowerStorageContract _productStorageContract;
[SetUp]
public void SetUp()
{
_productStorageContract = new FlowerStorageContract(DaisiesDbContext);
}
[TearDown]
public void TearDown()
{
DaisiesDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Flowers\" CASCADE; ");
}
[Test]
public void Try_GetList_WhenHaveRecords_Test()
{
var product =
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 1");
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 2");
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), "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_GetElementById_WhenHaveRecord_Test()
{
var product = InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString());
AssertElement(_productStorageContract.GetElementById(product.Id), product);
}
[Test]
public void Try_GetElementById_WhenNoRecord_Test()
{
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString());
Assert.That(() => _productStorageContract.GetElementById(Guid.NewGuid().ToString()), Is.Null);
}
[Test]
public void Try_GetElementByName_WhenHaveRecord_Test()
{
var product =
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString());
AssertElement(_productStorageContract.GetElementByName(product.Name), product);
}
[Test]
public void Try_GetElementByName_WhenNoRecord_Test()
{
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString());
Assert.That(() => _productStorageContract.GetElementByName("name"), Is.Null);
}
[Test]
public void Try_AddElement_Test()
{
var product = CreateModel(Guid.NewGuid().ToString());
_productStorageContract.AddElement(product);
AssertElement(GetProductFromDatabaseById(product.Id), product);
}
[Test]
public void Try_AddElement_WhenHaveRecordWithSameId_Test()
{
var product = CreateModel(Guid.NewGuid().ToString());
InsertProductToDatabaseAndReturn(product.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(), "name unique");
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), productName: product.Name);
Assert.That(() => _productStorageContract.AddElement(product), Throws.TypeOf<ElementExistsException>());
}
[Test]
public void Try_UpdElement_Test()
{
var product = CreateModel(Guid.NewGuid().ToString());
InsertProductToDatabaseAndReturn(product.Id);
_productStorageContract.UpdElement(product);
AssertElement(GetProductFromDatabaseById(product.Id), product);
}
[Test]
public void Try_UpdElement_WhenNoRecordWithThisId_Test()
{
Assert.That(() => _productStorageContract.UpdElement(CreateModel(Guid.NewGuid().ToString())), Throws.TypeOf<ElementNotFoundException>());
}
[Test]
public void Try_UpdElement_WhenHaveRecordWithSameName_Test()
{
var product = CreateModel(Guid.NewGuid().ToString(), "name unique");
InsertProductToDatabaseAndReturn(product.Id, productName: "name");
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), productName: product.Name);
Assert.That(() => _productStorageContract.UpdElement(product),
Throws.TypeOf<ElementExistsException>());
}
[Test]
public void Try_DelElement_Test()
{
var product = InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString());
_productStorageContract.DelElement(product.Id);
var element = GetProductFromDatabaseById(product.Id);
Assert.That(element, Is.Null);
}
[Test]
public void Try_DelElement_WhenNoRecordWithThisId_Test()
{
Assert.That(() => _productStorageContract.DelElement(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
}
private Flower InsertProductToDatabaseAndReturn(string id, string productName = "test", decimal price = 1)
{
var product = new Flower()
{
Id = id,
Name = productName,
Price = price,
};
DaisiesDbContext.Flowers.Add(product);
DaisiesDbContext.SaveChanges();
return product;
}
private static void AssertElement(FlowerDataModel? actual, Flower expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.Id, Is.EqualTo(expected.Id));
Assert.That(actual.Name, Is.EqualTo(expected.Name));
Assert.That(actual.Price, Is.EqualTo(expected.Price));
});
}
private static FlowerDataModel CreateModel(string id, string productName = "test", decimal price = 1)
=> new(id, productName, price);
private Flower? GetProductFromDatabaseById(string id) => DaisiesDbContext.Flowers.FirstOrDefault(x => x.Id == id);
private static void AssertElement(Flower? actual, FlowerDataModel expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.Id, Is.EqualTo(expected.Id));
Assert.That(actual.Name, Is.EqualTo(expected.Name));
Assert.That(actual.Price, Is.EqualTo(expected.Price));
});
}
}