lab3-ready

This commit is contained in:
2025-04-15 02:40:51 +04:00
parent d51c616862
commit 86881f7317
47 changed files with 3323 additions and 373 deletions

View File

@@ -56,6 +56,7 @@ internal class ProductBusinessLogicContract(IProductStorageContract productStora
_logger.LogInformation("New data: {json}", JsonSerializer.Serialize(productDataModel));
ArgumentNullException.ThrowIfNull(productDataModel);
productDataModel.Validate();
_productStorageContract.AddElement(productDataModel);
}
public void UpdateProduct(ProductDataModel productDataModel)
@@ -63,6 +64,7 @@ internal class ProductBusinessLogicContract(IProductStorageContract productStora
_logger.LogInformation("Update data: {json}", JsonSerializer.Serialize(productDataModel));
ArgumentNullException.ThrowIfNull(productDataModel);
productDataModel.Validate();
_productStorageContract.UpdElement(productDataModel);
}
public void DeleteProduct(string id)

View File

@@ -13,11 +13,11 @@ using System.Threading.Tasks;
namespace CandyHouseBusinessLogic.Implementations;
internal class SaleBusinessLogicContract(ISaleStorageContract saleStorageContract, ILogger logger)
: ISaleBusinessLogicContract
internal class SaleBusinessLogicContract(ISaleStorageContract saleStorageContract, IStorageStorageContract storageStorageContract, ILogger logger) : ISaleBusinessLogicContract
{
private readonly ILogger _logger = logger;
private readonly ISaleStorageContract _saleStorageContract = saleStorageContract;
private readonly IStorageStorageContract _storageStorageContract = storageStorageContract;
public List<SaleDataModel> GetAllSalesByPeriod(DateTime fromDate, DateTime toDate)
{
@@ -26,7 +26,6 @@ internal class SaleBusinessLogicContract(ISaleStorageContract saleStorageContrac
{
throw new IncorrectDatesException(fromDate, toDate);
}
return _saleStorageContract.GetList(fromDate, toDate) ?? throw new NullListException();
}
@@ -37,17 +36,14 @@ internal class SaleBusinessLogicContract(ISaleStorageContract saleStorageContrac
{
throw new IncorrectDatesException(fromDate, toDate);
}
if (employeeId.IsEmpty())
{
throw new ArgumentNullException(nameof(employeeId));
}
if (!employeeId.IsGuid())
{
throw new ValidationException("The value in the field employeeId is not a unique identifier.");
}
return _saleStorageContract.GetList(fromDate, toDate, employeeId: employeeId) ?? throw new NullListException();
}
@@ -58,17 +54,14 @@ internal class SaleBusinessLogicContract(ISaleStorageContract saleStorageContrac
{
throw new IncorrectDatesException(fromDate, toDate);
}
if (clientId.IsEmpty())
{
throw new ArgumentNullException(nameof(clientId));
}
if (!clientId.IsGuid())
{
throw new ValidationException("The value in the field clientId is not a unique identifier.");
}
return _saleStorageContract.GetList(fromDate, toDate, clientId: clientId) ?? throw new NullListException();
}
@@ -79,17 +72,14 @@ internal class SaleBusinessLogicContract(ISaleStorageContract saleStorageContrac
{
throw new IncorrectDatesException(fromDate, toDate);
}
if (productId.IsEmpty())
{
throw new ArgumentNullException(nameof(productId));
}
if (!productId.IsGuid())
{
throw new ValidationException("The value in the field productId is not a unique identifier.");
}
return _saleStorageContract.GetList(fromDate, toDate, productId: productId) ?? throw new NullListException();
}
@@ -100,12 +90,10 @@ internal class SaleBusinessLogicContract(ISaleStorageContract saleStorageContrac
{
throw new ArgumentNullException(nameof(data));
}
if (!data.IsGuid())
{
throw new ValidationException("Id is not a unique identifier");
}
return _saleStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data);
}
@@ -114,6 +102,10 @@ internal class SaleBusinessLogicContract(ISaleStorageContract saleStorageContrac
_logger.LogInformation("New data: {json}", JsonSerializer.Serialize(saleDataModel));
ArgumentNullException.ThrowIfNull(saleDataModel);
saleDataModel.Validate();
if (!_storageStorageContract.CheckComponents(saleDataModel))
{
throw new InsufficientException("Dont have product in storage");
}
_saleStorageContract.AddElement(saleDataModel);
}
@@ -124,12 +116,10 @@ internal class SaleBusinessLogicContract(ISaleStorageContract saleStorageContrac
{
throw new ArgumentNullException(nameof(id));
}
if (!id.IsGuid())
{
throw new ValidationException("Id is not a unique identifier");
}
_saleStorageContract.DelElement(id);
}
}
}

View File

@@ -14,14 +14,14 @@ using System.Threading.Tasks;
namespace CandyHouseBusinessLogic.Implementations;
public class StorageBusinessLogicContract(IStorageStorageContract agencyStorageContract, ILogger logger) : IStorageBusinessLogicContract
public class StorageBusinessLogicContract(IStorageStorageContract storageStorageContract, ILogger logger) : IStorageBusinessLogicContract
{
private readonly IStorageStorageContract _agencyStorageContract = agencyStorageContract;
private readonly IStorageStorageContract _storageStorageContract = storageStorageContract;
private readonly ILogger _logger = logger;
public List<StorageDataModel> GetAllComponents()
{
_logger.LogInformation("GetAllComponents");
return _agencyStorageContract.GetList() ?? throw new NullListException();
return _storageStorageContract.GetList() ?? throw new NullListException();
return [];
}
@@ -37,7 +37,9 @@ public class StorageBusinessLogicContract(IStorageStorageContract agencyStorageC
{
throw new ElementNotFoundException(data);
}
return _agencyStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data);
return _storageStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data);
return new("", ProductType.None, 0, []);
}
public void InsertComponent(StorageDataModel storageDataModel)
@@ -45,7 +47,7 @@ public class StorageBusinessLogicContract(IStorageStorageContract agencyStorageC
_logger.LogInformation("New data: {json}", JsonSerializer.Serialize(storageDataModel));
ArgumentNullException.ThrowIfNull(storageDataModel);
storageDataModel.Validate();
_agencyStorageContract.AddElement(storageDataModel);
_storageStorageContract.AddElement(storageDataModel);
}
public void UpdateComponent(StorageDataModel storageDataModel)
@@ -53,7 +55,7 @@ public class StorageBusinessLogicContract(IStorageStorageContract agencyStorageC
_logger.LogInformation("Update data: {json}", JsonSerializer.Serialize(storageDataModel));
ArgumentNullException.ThrowIfNull(storageDataModel);
storageDataModel.Validate();
_agencyStorageContract.UpdElement(storageDataModel);
_storageStorageContract.UpdElement(storageDataModel);
}
public void DeleteComponent(string id)
@@ -67,6 +69,6 @@ public class StorageBusinessLogicContract(IStorageStorageContract agencyStorageC
{
throw new ValidationException("Id is not a unique identifier");
}
_agencyStorageContract.DelElement(id);
_storageStorageContract.DelElement(id);
}
}

View File

@@ -12,16 +12,13 @@ using System.Xml.Linq;
namespace CandyHouseContracts.DataModels;
public class ProductDataModel(string id, string productName, string productDescription, double price, ProductType productType,
List<ProductSuppliesDataModel> supplies, List<ProductStorageDataModel> agency) : IValidation
public class ProductDataModel(string id, string productName, string productDescription, double price, ProductType productType) : IValidation
{
public string Id { get; private set; } = id;
public string ProductName { get; private set; } = productName;
public string ProductDescription { get; private set; } = productDescription;
public double Price { get; private set; } = price;
public ProductType Type { get; private set; } = productType;
public List<ProductSuppliesDataModel> Supplies { get; private set; } = supplies;
public List<ProductStorageDataModel> Storage { get; private set; } = agency;
public ProductType ProductType { get; private set; } = productType;
public void Validate()
{
@@ -35,11 +32,7 @@ public class ProductDataModel(string id, string productName, string productDescr
throw new ValidationException("Field ProductDescription is empty");
if (Price <= 0)
throw new ValidationException("Field Price is less than or equal to 0");
if (Type == ProductType.None)
if (ProductType == ProductType.None)
throw new ValidationException("Field Type is empty");
if ((Supplies?.Count ?? 0) == 0)
throw new ValidationException("The product must include supplies");
if ((Storage?.Count ?? 0) == 0)
throw new ValidationException("The product must include agency");
}
}

View File

@@ -10,9 +10,9 @@ using System.Threading.Tasks;
namespace CandyHouseContracts.DataModels;
public class ProductStorageDataModel(string agencyId, string productId, int count) : IValidation
public class ProductStorageDataModel(string storageId, string productId, int count) : IValidation
{
public string StorageId { get; private set; } = agencyId;
public string StorageId { get; private set; } = storageId;
public string ProductId { get; private set; } = productId;
public int Count { get; private set; } = count;

View File

@@ -11,7 +11,7 @@ using System.Threading.Tasks;
namespace CandyHouseContracts.DataModels;
public class SaleDataModel(string id, string employeeId, string? clientId, double sum, DiscountType discountType,
double discount, bool isCancel, List<SaleProductDataModel> products) : IValidation
double discount, bool isCancel, List<SaleProductDataModel> saleProducts) : IValidation
{
public string Id { get; private set; } = id;
@@ -28,7 +28,7 @@ public class SaleDataModel(string id, string employeeId, string? clientId, doubl
public bool IsCancel { get; private set; } = isCancel;
public List<SaleProductDataModel> Products { get; private set; } = products;
public List<SaleProductDataModel> Products { get; private set; } = saleProducts;
public void Validate()
{

View File

@@ -9,11 +9,11 @@ using System.Threading.Tasks;
namespace CandyHouseContracts.DataModels;
public class SaleProductDataModel(string saleId, string cocktailId, int count) : IValidation
public class SaleProductDataModel(string saleId, string productId, int count) : IValidation
{
public string SaleId { get; private set; } = saleId;
public string ProductId { get; private set; } = cocktailId;
public string ProductId { get; private set; } = productId;
public int Count { get; private set; } = count;

View File

@@ -6,10 +6,11 @@ using System.Threading.Tasks;
namespace CandyHouseContracts.Enums;
public enum PostType
{
None = 0,
Manager = 1,
SuperManager = 2,
Baker = 3,
}
}

View File

@@ -0,0 +1,12 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseContracts.Exceptions;
public class ElementDeletedException : Exception
{
public ElementDeletedException(string id) : base($"Cannot modify a deleted item (id: {id})") { }
}

View File

@@ -0,0 +1,12 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseContracts.Infrastructure;
public interface IConfigurationDatabase
{
string ConnectionString { get; }
}

View File

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

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,169 @@
using AutoMapper;
using CandyHouseContracts.DataModels;
using CandyHouseContracts.Exceptions;
using CandyHouseContracts.StoragesContracts;
using CandyHouseDatabase.Models;
using Microsoft.EntityFrameworkCore;
using Npgsql;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseDatabase.Implementations;
internal class ProductStorageContract : IProductStorageContract
{
private readonly CandyHouseDbContext _dbContext;
private readonly Mapper _mapper;
public ProductStorageContract(CandyHouseDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Product, ProductDataModel>();
cfg.CreateMap<ProductDataModel, Product>();
cfg.CreateMap<ProductHistory, ProductHistoryDataModel>(); ;
});
_mapper = new Mapper(config);
}
public List<ProductDataModel> GetList()
{
try
{
return [.. _dbContext.Products.Select(x => _mapper.Map<ProductDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public List<ProductHistoryDataModel> GetHistoryByProductId(string productId)
{
try
{
return [.. _dbContext.ProductHistories.Where(x => x.ProductId == productId).OrderByDescending(x => x.ChangeDate).Select(x => _mapper.Map<ProductHistoryDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public ProductDataModel? GetElementById(string id)
{
try
{
return _mapper.Map<ProductDataModel>(GetProductById(id));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public ProductDataModel? GetElementByName(string name)
{
try
{
return _mapper.Map<ProductDataModel>(_dbContext.Products.FirstOrDefault(x => x.ProductName == name));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void AddElement(ProductDataModel productDataModel)
{
try
{
_dbContext.Products.Add(_mapper.Map<Product>(productDataModel));
_dbContext.SaveChanges();
}
catch (InvalidOperationException ex) when (ex.TargetSite?.Name == "ThrowIdentityConflict")
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("Id", productDataModel.Id);
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Products_ProductName" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("ProductName", productDataModel.ProductName);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void UpdElement(ProductDataModel productDataModel)
{
try
{
var element = GetProductById(productDataModel.Id) ?? throw new ElementNotFoundException(productDataModel.Id);
_dbContext.Products.Update(_mapper.Map(productDataModel, element));
_dbContext.SaveChanges();
}
catch (ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Products_ProductName" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("ProductName", productDataModel.ProductName);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void DelElement(string id)
{
try
{
var element = GetProductById(id) ?? throw new ElementNotFoundException(id);
_dbContext.Products.Remove(element);
_dbContext.SaveChanges();
}
catch (ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void ResElement(string id)
{
try
{
var element = GetProductById(id) ?? throw new ElementNotFoundException(id);
_dbContext.SaveChanges();
}
catch
{
_dbContext.ChangeTracker.Clear();
throw;
}
}
private Product? GetProductById(string id) => _dbContext.Products.FirstOrDefault(x => x.Id == id);
}

View File

@@ -0,0 +1,62 @@
using AutoMapper;
using CandyHouseContracts.DataModels;
using CandyHouseContracts.Exceptions;
using CandyHouseContracts.StoragesContracts;
using CandyHouseDatabase.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseDatabase.Implementations;
internal class SalaryStorageContract : ISalaryStorageContract
{
private readonly CandyHouseDbContext _dbContext;
private readonly Mapper _mapper;
public SalaryStorageContract(CandyHouseDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Salary, SalaryDataModel>();
cfg.CreateMap<SalaryDataModel, Salary>()
.ForMember(dest => dest.EmployeeSalary, opt => opt.MapFrom(src => src.Salary));
});
_mapper = new Mapper(config);
}
public List<SalaryDataModel> GetList(DateTime startDate, DateTime endDate, string? employeeId = null)
{
try
{
var query = _dbContext.Salaries.Where(x => x.SalaryDate >= startDate && x.SalaryDate <= endDate);
if (employeeId is not null)
{
query = query.Where(x => x.EmployeeId == employeeId);
}
return [.. query.Select(x => _mapper.Map<SalaryDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void AddElement(SalaryDataModel salaryDataModel)
{
try
{
_dbContext.Salaries.Add(_mapper.Map<Salary>(salaryDataModel));
_dbContext.SaveChanges();
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
}

View File

@@ -0,0 +1,117 @@
using AutoMapper;
using CandyHouseContracts.DataModels;
using CandyHouseContracts.Exceptions;
using CandyHouseContracts.StoragesContracts;
using CandyHouseDatabase.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseDatabase.Implementations;
internal class SaleStorageContract : ISaleStorageContract
{
private readonly CandyHouseDbContext _dbContext;
private readonly Mapper _mapper;
public SaleStorageContract(CandyHouseDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<SaleProduct, SaleProductDataModel>();
cfg.CreateMap<SaleProductDataModel, SaleProduct>();
cfg.CreateMap<Sale, SaleDataModel>();
cfg.CreateMap<SaleDataModel, Sale>()
.ForMember(x => x.IsCancel, x => x.MapFrom(src => false))
.ForMember(x => x.SaleProducts, x => x.MapFrom(src => src.Products));
});
_mapper = new Mapper(config);
}
public List<SaleDataModel> GetList(DateTime? startDate = null, DateTime? endDate = null, string? employeeId = null, string? clientId = null, string? productId = null)
{
try
{
var query = _dbContext.Sales.Include(x => x.SaleProducts).AsQueryable();
if (startDate is not null && endDate is not null)
{
query = query.Where(x => x.SaleDate >= startDate && x.SaleDate < endDate);
}
if (employeeId is not null)
{
query = query.Where(x => x.EmployeeId == employeeId);
}
if (clientId is not null)
{
query = query.Where(x => x.ClientId == clientId);
}
if (productId is not null)
{
query = query.Where(x => x.SaleProducts!.Any(y => y.ProductId == productId));
}
return [.. query.Select(x => _mapper.Map<SaleDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public SaleDataModel? GetElementById(string id)
{
try
{
return _mapper.Map<SaleDataModel>(GetSaleById(id));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void AddElement(SaleDataModel saleDataModel)
{
try
{
_dbContext.Sales.Add(_mapper.Map<Sale>(saleDataModel));
_dbContext.SaveChanges();
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void DelElement(string id)
{
try
{
var element = GetSaleById(id) ?? throw new ElementNotFoundException(id);
if (element.IsCancel)
{
throw new ElementDeletedException(id);
}
element.IsCancel = true;
_dbContext.SaveChanges();
}
catch (Exception ex) when (ex is ElementDeletedException || ex is ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
private Sale? GetSaleById(string id) => _dbContext.Sales.FirstOrDefault(x => x.Id == id);
}

View File

@@ -0,0 +1,148 @@
using AutoMapper;
using CandyHouseContracts.DataModels;
using CandyHouseContracts.Exceptions;
using CandyHouseContracts.StoragesContracts;
using CandyHouseDatabase.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseDatabase.Implementations;
public class StorageStorageContract : IStorageStorageContract
{
private readonly CandyHouseDbContext _dbContext;
private readonly Mapper _mapper;
public StorageStorageContract(CandyHouseDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Storage, StorageDataModel>()
.ConstructUsing(src => new StorageDataModel(
src.Id,
src.Type,
src.Count,
_mapper.Map<List<ProductStorageDataModel>>(src.Products)
));
cfg.CreateMap<StorageDataModel, Storage>();
cfg.CreateMap<ProductStorageDataModel, ProductStorage>().ReverseMap();
});
_mapper = new Mapper(config);
}
public List<StorageDataModel> GetList()
{
try
{
return [.. _dbContext.Agencies.Select(x => _mapper.Map<StorageDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public StorageDataModel GetElementById(string id)
{
try
{
return _mapper.Map<StorageDataModel>(GetStorageById(id));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void AddElement(StorageDataModel storageDataModel)
{
try
{
_dbContext.Agencies.Add(_mapper.Map<Storage>(storageDataModel));
_dbContext.SaveChanges();
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void UpdElement(StorageDataModel storageDataModel)
{
try
{
var element = GetStorageById(storageDataModel.Id) ?? throw new ElementNotFoundException(storageDataModel.Id);
_dbContext.Agencies.Update(_mapper.Map(storageDataModel, element));
_dbContext.SaveChanges();
}
catch (ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void DelElement(string id)
{
try
{
var element = GetStorageById(id) ?? throw new ElementNotFoundException(id);
_dbContext.Agencies.Remove(element);
_dbContext.SaveChanges();
}
catch (ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public bool CheckComponents(SaleDataModel saleDataModel)
{
using (var transaction = _dbContext.Database.BeginTransaction())
{
foreach (SaleProductDataModel sale_product in saleDataModel.Products)
{
var product = _dbContext.Products.FirstOrDefault(x => x.Id == sale_product.ProductId);
var storage = _dbContext.Agencies.FirstOrDefault(x => x.Type == product.ProductType && x.Count >= sale_product.Count);
if (storage == null)
{
transaction.Rollback();
return false;
}
if (storage.Count - sale_product.Count == 0)
{
DelElement(storage.Id);
}
else
{
storage.Count -= sale_product.Count;
}
}
transaction.Commit();
_dbContext.SaveChanges();
return true;
}
}
private Storage? GetStorageById(string id) => _dbContext.Agencies.FirstOrDefault(x => x.Id == id);
}

View File

@@ -0,0 +1,100 @@
using AutoMapper;
using CandyHouseContracts.DataModels;
using CandyHouseContracts.Exceptions;
using CandyHouseContracts.StoragesContracts;
using CandyHouseDatabase.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseDatabase.Implementations;
public class SuppliesStorageContract : ISuppliesStorageContract
{
private readonly CandyHouseDbContext _dbContext;
private readonly Mapper _mapper;
public SuppliesStorageContract(CandyHouseDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Supplies, SuppliesDataModel>()
.ConstructUsing(src => new SuppliesDataModel(
src.Id,
src.Type,
src.OrderDate,
src.Count,
_mapper.Map<List<ProductSuppliesDataModel>>(src.Products)
));
cfg.CreateMap<SuppliesDataModel, Supplies>();
cfg.CreateMap<ProductSuppliesDataModel, ProductSupplies>().ReverseMap();
});
_mapper = new Mapper(config);
}
public List<SuppliesDataModel> GetList(DateTime? startDate = null)
{
try
{
return [.. _dbContext.Supplieses.Select(x => _mapper.Map<SuppliesDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public SuppliesDataModel GetElementById(string id)
{
try
{
return _mapper.Map<SuppliesDataModel>(GetSuppliesById(id));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void AddElement(SuppliesDataModel suppliesDataModel)
{
try
{
_dbContext.Supplieses.Add(_mapper.Map<Supplies>(suppliesDataModel));
_dbContext.SaveChanges();
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void UpdElement(SuppliesDataModel suppliesDataModel)
{
try
{
var element = GetSuppliesById(suppliesDataModel.Id) ?? throw new ElementNotFoundException(suppliesDataModel.Id);
_dbContext.Supplieses.Update(_mapper.Map(suppliesDataModel, element));
_dbContext.SaveChanges();
}
catch (ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
private Supplies? GetSuppliesById(string id) => _dbContext.Supplieses.FirstOrDefault(x => x.Id == id);
}

View File

@@ -0,0 +1,66 @@
using CandyHouseContracts.Infrastructure;
using CandyHouseDatabase.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseDatabase;
public class CandyHouseDbContext(IConfigurationDatabase configurationDatabase) : DbContext
{
private readonly IConfigurationDatabase? _configurationDatabase = configurationDatabase;
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseNpgsql(_configurationDatabase?.ConnectionString, o => o.SetPostgresVersion(12, 2));
base.OnConfiguring(optionsBuilder);
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Client>().HasIndex(x => x.PhoneNumber).IsUnique();
modelBuilder.Entity<Product>().HasIndex(x => x.ProductName).IsUnique();
modelBuilder.Entity<Post>()
.HasIndex(e => new { e.PostName, e.IsActual })
.IsUnique()
.HasFilter($"\"{nameof(Post.IsActual)}\" = TRUE");
modelBuilder.Entity<Post>()
.HasIndex(e => new { e.PostId, e.IsActual })
.IsUnique()
.HasFilter($"\"{nameof(Post.IsActual)}\" = TRUE");
modelBuilder.Entity<SaleProduct>().HasKey(x => new { x.SaleId, x.ProductId });
modelBuilder.Entity<ProductSupplies>().HasKey(x => new { x.SuppliesId, x.ProductId });
modelBuilder.Entity<ProductStorage>().HasKey(x => new { x.StorageId, x.ProductId });
}
public DbSet<Client> Clients { get; set; }
public DbSet<Post> Posts { get; set; }
public DbSet<Product> Products { get; set; }
public DbSet<ProductHistory> ProductHistories { get; set; }
public DbSet<Salary> Salaries { get; set; }
public DbSet<Sale> Sales { get; set; }
public DbSet<SaleProduct> SaleProducts { get; set; }
public DbSet<Employee> Employees { get; set; }
public DbSet<Supplies> Supplieses { get; set; }
public DbSet<Storage> Agencies { get; set; }
public DbSet<ProductSupplies> ProductSupplieses { get; set; }
public DbSet<ProductStorage> ProductAgensies { get; set; }
}

View File

@@ -0,0 +1,24 @@
using AutoMapper;
using CandyHouseContracts.DataModels;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseDatabase.Models;
[AutoMap(typeof(ClientDataModel), ReverseMap = true)]
public class Client
{
public required string Id { get; set; }
public required string FIO { get; set; }
public required string PhoneNumber { get; set; }
public double DiscountSize { get; set; }
[ForeignKey("ClientId")]
public List<Sale>? Sales { get; set; }
}

View File

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

View File

@@ -0,0 +1,20 @@
using CandyHouseContracts.Enums;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseDatabase.Models;
public class Post
{
public required string Id { get; set; } = Guid.NewGuid().ToString();
public required string PostId { get; set; }
public required string PostName { get; set; }
public PostType PostType { get; set; }
public double Salary { get; set; }
public bool IsActual { get; set; }
public DateTime ChangeDate { get; set; }
}

View File

@@ -0,0 +1,30 @@
using AutoMapper;
using CandyHouseContracts.DataModels;
using CandyHouseContracts.Enums;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseDatabase.Models;
[AutoMap(typeof(ProductDataModel), ReverseMap = true)]
public class Product
{
public required string Id { get; set; }
public required string ProductName { get; set; }
public string? ProductDescription { get; set; }
public double Price { get; set; }
public required ProductType ProductType { get; set; }
[ForeignKey("ProductId")]
public List<SaleProduct>? SaleProducts { get; set; }
[ForeignKey("ProductId")]
public List<ProductHistory>? ProductHistories { get; set; }
[ForeignKey("SuppliesesId")]
public List<ProductSupplies>? ProductSupplies { get; set; }
[ForeignKey("AgenciesId")]
public List<ProductStorage>? ProductStorage { get; set; }
}

View File

@@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseDatabase.Models;
public class ProductHistory
{
public string Id { get; set; } = Guid.NewGuid().ToString();
public required string ProductId { get; set; }
public double OldPrice { get; set; }
public DateTime ChangeDate { get; set; }
public Product? Product { get; set; }
}

View File

@@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseDatabase.Models;
public class ProductStorage
{
public required string StorageId { get; set; }
public required string ProductId { get; set; }
public int Count { get; set; }
public Storage? Agencies { get; set; }
public Product? Products { get; set; }
}

View File

@@ -0,0 +1,19 @@
using AutoMapper;
using CandyHouseContracts.DataModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseDatabase.Models;
[AutoMap(typeof(ProductSuppliesDataModel), ReverseMap = true)]
public class ProductSupplies
{
public required string SuppliesId { get; set; }
public required string ProductId { get; set; }
public int Count { get; set; }
public Supplies? Supplies { get; set; }
public Product? Products { get; set; }
}

View File

@@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseDatabase.Models;
public class Salary
{
public string Id { get; set; } = Guid.NewGuid().ToString();
public required string EmployeeId { get; set; }
public DateTime SalaryDate { get; set; }
public double EmployeeSalary { get; set; }
public Employee? Employee { get; set; }
}

View File

@@ -0,0 +1,32 @@
using CandyHouseContracts.DataModels;
using CandyHouseContracts.Enums;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseDatabase.Models;
public class Sale
{
public string Id { get; set; } = Guid.NewGuid().ToString();
public required string EmployeeId { get; set; }
public string? ClientId { get; set; }
public DateTime SaleDate { get; set; }
public double Sum { get; set; }
public DiscountType DiscountType { get; set; }
public double Discount { get; set; }
public bool IsCancel { get; set; }
public Employee? Employee { get; set; }
public Client? Client { get; set; }
[ForeignKey("SaleId")]
public List<SaleProduct>? SaleProducts { get; set; }
}

View File

@@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseDatabase.Models;
public class SaleProduct
{
public required string SaleId { get; set; }
public required string ProductId { get; set; }
public int Count { get; set; }
}

View File

@@ -0,0 +1,21 @@
using AutoMapper;
using CandyHouseContracts.DataModels;
using CandyHouseContracts.Enums;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseDatabase.Models;
public class Storage
{
public required string Id { get; set; }
public required ProductType Type { get; set; }
public required int Count { get; set; }
[ForeignKey("StorageId")]
public List<ProductStorage>? Products { get; set; }
}

View File

@@ -0,0 +1,22 @@
using AutoMapper;
using CandyHouseContracts.DataModels;
using CandyHouseContracts.Enums;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseDatabase.Models;
public class Supplies
{
public required string Id { get; set; }
public required ProductType Type { get; set; }
public DateTime OrderDate { get; set; }
public required int Count { get; set; }
[ForeignKey("SuppliesId")]
public List<ProductSupplies>? Products { get; set; }
}

View File

@@ -6,6 +6,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CandyHouseTests", "CandyHou
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CandyHouseBusinessLogic", "CandyHouseBusinessLogic\CandyHouseBusinessLogic.csproj", "{9D56286D-B8FE-4A50-96B1-CE51EEBE95A2}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CandyHouseDatabase", "CandyHouseDatabase\CandyHouseDatabase.csproj", "{928DD22D-F304-4767-B950-990BEE31CFF5}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@@ -24,5 +26,9 @@ Global
{9D56286D-B8FE-4A50-96B1-CE51EEBE95A2}.Debug|Any CPU.Build.0 = Debug|Any CPU
{9D56286D-B8FE-4A50-96B1-CE51EEBE95A2}.Release|Any CPU.ActiveCfg = Release|Any CPU
{9D56286D-B8FE-4A50-96B1-CE51EEBE95A2}.Release|Any CPU.Build.0 = Release|Any CPU
{928DD22D-F304-4767-B950-990BEE31CFF5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{928DD22D-F304-4767-B950-990BEE31CFF5}.Debug|Any CPU.Build.0 = Debug|Any CPU
{928DD22D-F304-4767-B950-990BEE31CFF5}.Release|Any CPU.ActiveCfg = Release|Any CPU
{928DD22D-F304-4767-B950-990BEE31CFF5}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
EndGlobal

View File

@@ -24,8 +24,7 @@ internal class ProductBusinessLogicContractTests
public void OneTimeSetUp()
{
_productStorageContract = new Mock<IProductStorageContract>();
_productBusinessLogicContract =
new ProductBusinessLogicContract(_productStorageContract.Object, new Mock<ILogger>().Object);
_productBusinessLogicContract = new ProductBusinessLogicContract(_productStorageContract.Object, new Mock<ILogger>().Object);
}
[SetUp]
@@ -40,9 +39,9 @@ internal class ProductBusinessLogicContractTests
//Arrange
var listOriginal = new List<ProductDataModel>()
{
new(Guid.NewGuid().ToString(), "name 1", "country1", 15.5, ProductType.Chocolate, [], []),
new(Guid.NewGuid().ToString(), "name 2", "country2", 10.1, ProductType.Candy, [], []),
new(Guid.NewGuid().ToString(), "name 3", "country3", 13.9, ProductType.Cake, [], []),
new(Guid.NewGuid().ToString(), "name 1", "description1", 15.5, ProductType.Chocolate),
new(Guid.NewGuid().ToString(), "name 2", "description2", 10.1, ProductType.Candy),
new(Guid.NewGuid().ToString(), "name 3", "description3", 13.9, ProductType.Cake),
};
_productStorageContract.Setup(x => x.GetList()).Returns(listOriginal);
//Act
@@ -120,10 +119,8 @@ internal class ProductBusinessLogicContractTests
public void GetProductHistoryByProduct_ProductIdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _productBusinessLogicContract.GetProductHistoryByProduct(null),
Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _productBusinessLogicContract.GetProductHistoryByProduct(string.Empty),
Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _productBusinessLogicContract.GetProductHistoryByProduct(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _productBusinessLogicContract.GetProductHistoryByProduct(string.Empty), Throws.TypeOf<ArgumentNullException>());
_productStorageContract.Verify(x => x.GetHistoryByProductId(It.IsAny<string>()), Times.Never);
}
@@ -131,8 +128,7 @@ internal class ProductBusinessLogicContractTests
public void GetProductHistoryByProduct_ProductIdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _productBusinessLogicContract.GetProductHistoryByProduct("productId"),
Throws.TypeOf<ValidationException>());
Assert.That(() => _productBusinessLogicContract.GetProductHistoryByProduct("productId"), Throws.TypeOf<ValidationException>());
_productStorageContract.Verify(x => x.GetHistoryByProductId(It.IsAny<string>()), Times.Never);
}
@@ -140,8 +136,7 @@ internal class ProductBusinessLogicContractTests
public void GetProductHistoryByProduct_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _productBusinessLogicContract.GetProductHistoryByProduct(Guid.NewGuid().ToString()),
Throws.TypeOf<NullListException>());
Assert.That(() => _productBusinessLogicContract.GetProductHistoryByProduct(Guid.NewGuid().ToString()), Throws.TypeOf<NullListException>());
_productStorageContract.Verify(x => x.GetHistoryByProductId(It.IsAny<string>()), Times.Once);
}
@@ -149,11 +144,9 @@ internal class ProductBusinessLogicContractTests
public void GetProductHistoryByProduct_StorageThrowError_ThrowException_Test()
{
//Arrange
_productStorageContract.Setup(x => x.GetHistoryByProductId(It.IsAny<string>()))
.Throws(new StorageException(new InvalidOperationException()));
_productStorageContract.Setup(x => x.GetHistoryByProductId(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _productBusinessLogicContract.GetProductHistoryByProduct(Guid.NewGuid().ToString()),
Throws.TypeOf<StorageException>());
Assert.That(() => _productBusinessLogicContract.GetProductHistoryByProduct(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_productStorageContract.Verify(x => x.GetHistoryByProductId(It.IsAny<string>()), Times.Once);
}
@@ -162,7 +155,7 @@ internal class ProductBusinessLogicContractTests
{
//Arrange
var id = Guid.NewGuid().ToString();
var record = new ProductDataModel(id, "name", "country", 10, ProductType.Chocolate, [], []);
var record = new ProductDataModel(id, "name", "description", 10, ProductType.Chocolate);
_productStorageContract.Setup(x => x.GetElementById(id)).Returns(record);
//Act
var element = _productBusinessLogicContract.GetProductByData(id);
@@ -177,7 +170,7 @@ internal class ProductBusinessLogicContractTests
{
//Arrange
var name = "name";
var record = new ProductDataModel(Guid.NewGuid().ToString(), name, "country", 10, ProductType.Chocolate, [], []);
var record = new ProductDataModel(Guid.NewGuid().ToString(), name, "description", 10, ProductType.Chocolate);
_productStorageContract.Setup(x => x.GetElementByName(name)).Returns(record);
//Act
var element = _productBusinessLogicContract.GetProductByData(name);
@@ -186,19 +179,18 @@ internal class ProductBusinessLogicContractTests
Assert.That(element.ProductName, Is.EqualTo(name));
_productStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetProductByData_GetByDescription_ReturnRecord_Test()
{
//Arrange
var country = "country";
var record = new ProductDataModel(Guid.NewGuid().ToString(), "name", country, 10, ProductType.Chocolate, [], []);
_productStorageContract.Setup(x => x.GetElementByName(country)).Returns(record);
var description = "description";
var record = new ProductDataModel(Guid.NewGuid().ToString(), "name", description, 10, ProductType.Chocolate);
_productStorageContract.Setup(x => x.GetElementByName(description)).Returns(record);
//Act
var element = _productBusinessLogicContract.GetProductByData(country);
var element = _productBusinessLogicContract.GetProductByData(description);
//Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.ProductDescription, Is.EqualTo(country));
Assert.That(element.ProductDescription, Is.EqualTo(description));
_productStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Once);
}
@@ -207,8 +199,7 @@ internal class ProductBusinessLogicContractTests
{
//Act&Assert
Assert.That(() => _productBusinessLogicContract.GetProductByData(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _productBusinessLogicContract.GetProductByData(string.Empty),
Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _productBusinessLogicContract.GetProductByData(string.Empty), Throws.TypeOf<ArgumentNullException>());
_productStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Never);
_productStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Never);
}
@@ -217,8 +208,7 @@ internal class ProductBusinessLogicContractTests
public void GetProductByData_GetById_NotFoundRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _productBusinessLogicContract.GetProductByData(Guid.NewGuid().ToString()),
Throws.TypeOf<ElementNotFoundException>());
Assert.That(() => _productBusinessLogicContract.GetProductByData(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_productStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
}
@@ -226,17 +216,14 @@ internal class ProductBusinessLogicContractTests
public void GetProductByData_GetByName_NotFoundRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _productBusinessLogicContract.GetProductByData("name"),
Throws.TypeOf<ElementNotFoundException>());
Assert.That(() => _productBusinessLogicContract.GetProductByData("name"), Throws.TypeOf<ElementNotFoundException>());
_productStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetProductByData_GetByDescription_NotFoundRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _productBusinessLogicContract.GetProductByData("country"),
Throws.TypeOf<ElementNotFoundException>());
Assert.That(() => _productBusinessLogicContract.GetProductByData("description"), Throws.TypeOf<ElementNotFoundException>());
_productStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Once);
}
@@ -244,18 +231,43 @@ internal class ProductBusinessLogicContractTests
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()));
_productStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
_productStorageContract.Setup(x => x.GetElementByName(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _productBusinessLogicContract.GetProductByData(Guid.NewGuid().ToString()),
Throws.TypeOf<StorageException>());
Assert.That(() => _productBusinessLogicContract.GetProductByData(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
Assert.That(() => _productBusinessLogicContract.GetProductByData("name"), Throws.TypeOf<StorageException>());
_productStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
_productStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Once);
}
[Test]
public void InsertProduct_CorrectRecord_Test()
{
//Arrange
var flag = false;
var record = new ProductDataModel(Guid.NewGuid().ToString(), "name","description",10, ProductType.Chocolate);
_productStorageContract.Setup(x => x.AddElement(It.IsAny<ProductDataModel>()))
.Callback((ProductDataModel x) =>
{
flag = x.Id == record.Id && x.ProductName == record.ProductName && x.ProductDescription == record.ProductDescription
&& x.Price == record.Price && x.ProductType == record.ProductType;
});
//Act
_productBusinessLogicContract.InsertProduct(record);
//Assert
_productStorageContract.Verify(x => x.AddElement(It.IsAny<ProductDataModel>()), Times.Once);
Assert.That(flag);
}
[Test]
public void InsertProduct_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_productStorageContract.Setup(x => x.AddElement(It.IsAny<ProductDataModel>())).Throws(new ElementExistsException("Data", "Data"));
//Act&Assert
Assert.That(() => _productBusinessLogicContract.InsertProduct(new(Guid.NewGuid().ToString(), "name","description",10, ProductType.Chocolate)), Throws.TypeOf<ElementExistsException>());
_productStorageContract.Verify(x => x.AddElement(It.IsAny<ProductDataModel>()), Times.Once);
}
[Test]
public void InsertProduct_NullRecord_ThrowException_Test()
@@ -269,12 +281,48 @@ internal class ProductBusinessLogicContractTests
public void InsertProduct_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(
() => _productBusinessLogicContract.InsertProduct(new ProductDataModel("id", "name", "country", 10,
ProductType.Chocolate, [], [])), Throws.TypeOf<ValidationException>());
Assert.That(() => _productBusinessLogicContract.InsertProduct(new ProductDataModel("id", "name", "description", 10, ProductType.Chocolate)), Throws.TypeOf<ValidationException>());
_productStorageContract.Verify(x => x.AddElement(It.IsAny<ProductDataModel>()), Times.Never);
}
[Test]
public void UpdateProduct_CorrectRecord_Test()
{
//Arrange
var flag = false;
var record = new ProductDataModel(Guid.NewGuid().ToString(), "name", "description", 10, ProductType.Chocolate);
_productStorageContract.Setup(x => x.UpdElement(It.IsAny<ProductDataModel>()))
.Callback((ProductDataModel x) =>
{
flag = x.Id == record.Id && x.ProductName == record.ProductName && x.ProductDescription == record.ProductDescription
&& x.Price == record.Price && x.ProductType == record.ProductType;
});
//Act
_productBusinessLogicContract.UpdateProduct(record);
//Assert
_productStorageContract.Verify(x => x.UpdElement(It.IsAny<ProductDataModel>()), Times.Once);
Assert.That(flag);
}
[Test]
public void UpdateProduct_RecordWithIncorrectData_ThrowException_Test()
{
//Arrange
_productStorageContract.Setup(x => x.UpdElement(It.IsAny<ProductDataModel>())).Throws(new ElementNotFoundException(""));
//Act&Assert
Assert.That(() => _productBusinessLogicContract.UpdateProduct(new(Guid.NewGuid().ToString(), "name", "description", 10, ProductType.Chocolate)), Throws.TypeOf<ElementNotFoundException>());
_productStorageContract.Verify(x => x.UpdElement(It.IsAny<ProductDataModel>()), Times.Once);
}
[Test]
public void UpdateProduct_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_productStorageContract.Setup(x => x.UpdElement(It.IsAny<ProductDataModel>())).Throws(new ElementExistsException("Data", "Data"));
//Act&Assert
Assert.That(() => _productBusinessLogicContract.UpdateProduct(new(Guid.NewGuid().ToString(), "name", "description", 10, ProductType.Chocolate)), Throws.TypeOf <ElementExistsException>());
_productStorageContract.Verify(x => x.UpdElement(It.IsAny<ProductDataModel>()), Times.Once);
}
[Test]
public void UpdateProduct_NullRecord_ThrowException_Test()
@@ -288,14 +336,19 @@ internal class ProductBusinessLogicContractTests
public void UpdateProduct_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _productBusinessLogicContract.UpdateProduct(new ProductDataModel("id", "name", "country", 10,
ProductType.Chocolate,
[new ProductSuppliesDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)],
[new ProductStorageDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])),
Throws.TypeOf<ValidationException>());
Assert.That(() => _productBusinessLogicContract.UpdateProduct(new ProductDataModel("id", "name", "description", 10, ProductType.Chocolate)), Throws.TypeOf<ValidationException>());
_productStorageContract.Verify(x => x.UpdElement(It.IsAny<ProductDataModel>()), Times.Never);
}
[Test]
public void UpdateProduct_StorageThrowError_ThrowException_Test()
{
//Arrange
_productStorageContract.Setup(x => x.UpdElement(It.IsAny<ProductDataModel>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _productBusinessLogicContract.UpdateProduct(new(Guid.NewGuid().ToString(), "name", "description", 10, ProductType.Chocolate)), Throws.TypeOf<StorageException>());
_productStorageContract.Verify(x => x.UpdElement(It.IsAny<ProductDataModel>()), Times.Once);
}
[Test]
public void DeleteProduct_CorrectRecord_Test()
@@ -318,8 +371,7 @@ internal class ProductBusinessLogicContractTests
var id = Guid.NewGuid().ToString();
_productStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new ElementNotFoundException(id));
//Act&Assert
Assert.That(() => _productBusinessLogicContract.DeleteProduct(Guid.NewGuid().ToString()),
Throws.TypeOf<ElementNotFoundException>());
Assert.That(() => _productBusinessLogicContract.DeleteProduct(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_productStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
}
@@ -328,8 +380,7 @@ internal class ProductBusinessLogicContractTests
{
//Act&Assert
Assert.That(() => _productBusinessLogicContract.DeleteProduct(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _productBusinessLogicContract.DeleteProduct(string.Empty),
Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _productBusinessLogicContract.DeleteProduct(string.Empty), Throws.TypeOf<ArgumentNullException>());
_productStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Never);
}
@@ -345,11 +396,9 @@ internal class ProductBusinessLogicContractTests
public void DeleteProduct_StorageThrowError_ThrowException_Test()
{
//Arrange
_productStorageContract.Setup(x => x.DelElement(It.IsAny<string>()))
.Throws(new StorageException(new InvalidOperationException()));
_productStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _productBusinessLogicContract.DeleteProduct(Guid.NewGuid().ToString()),
Throws.TypeOf<StorageException>());
Assert.That(() => _productBusinessLogicContract.DeleteProduct(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_productStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
}
}

View File

@@ -18,19 +18,22 @@ internal class SaleBusinessLogicContractTests
{
private SaleBusinessLogicContract _saleBusinessLogicContract;
private Mock<ISaleStorageContract> _saleStorageContract;
private Mock<IStorageStorageContract> _storageStorageContract;
[OneTimeSetUp]
public void OneTimeSetUp()
{
_saleStorageContract = new Mock<ISaleStorageContract>();
_saleBusinessLogicContract =
new SaleBusinessLogicContract(_saleStorageContract.Object, new Mock<ILogger>().Object);
_storageStorageContract = new Mock<IStorageStorageContract>();
_saleBusinessLogicContract = new SaleBusinessLogicContract(_saleStorageContract.Object,
_storageStorageContract.Object, new Mock<ILogger>().Object);
}
[TearDown]
public void TearDown()
{
_saleStorageContract.Reset();
_storageStorageContract.Reset();
}
[Test]
@@ -45,8 +48,7 @@ internal class SaleBusinessLogicContractTests
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, DiscountType.None, 0, false, []),
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, DiscountType.None, 0, false, []),
};
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(),
It.IsAny<string>(), It.IsAny<string>())).Returns(listOriginal);
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Returns(listOriginal);
//Act
var list = _saleBusinessLogicContract.GetAllSalesByPeriod(date, date.AddDays(1));
//Assert
@@ -59,16 +61,13 @@ internal class SaleBusinessLogicContractTests
public void GetAllSalesByPeriod_ReturnEmptyList_Test()
{
//Arrange
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(),
It.IsAny<string>(), It.IsAny<string>())).Returns([]);
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Returns([]);
//Act
var list = _saleBusinessLogicContract.GetAllSalesByPeriod(DateTime.UtcNow, DateTime.UtcNow.AddDays(1));
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
_saleStorageContract.Verify(
x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(),
It.IsAny<string>()), Times.Once);
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test]
@@ -77,39 +76,27 @@ internal class SaleBusinessLogicContractTests
//Arrange
var date = DateTime.UtcNow;
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByPeriod(date, date),
Throws.TypeOf<IncorrectDatesException>());
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByPeriod(date, date.AddSeconds(-1)),
Throws.TypeOf<IncorrectDatesException>());
_saleStorageContract.Verify(
x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(),
It.IsAny<string>()), Times.Never);
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByPeriod(date, date), Throws.TypeOf<IncorrectDatesException>());
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByPeriod(date, date.AddSeconds(-1)), Throws.TypeOf<IncorrectDatesException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSalesByPeriod_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByPeriod(DateTime.UtcNow, DateTime.UtcNow.AddDays(1)),
Throws.TypeOf<NullListException>());
_saleStorageContract.Verify(
x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(),
It.IsAny<string>()), Times.Once);
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByPeriod(DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<NullListException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSalesByPeriod_StorageThrowError_ThrowException_Test()
{
//Arrange
_saleStorageContract
.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(),
It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByPeriod(DateTime.UtcNow, DateTime.UtcNow.AddDays(1)),
Throws.TypeOf<StorageException>());
_saleStorageContract.Verify(
x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(),
It.IsAny<string>()), Times.Once);
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByPeriod(DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<StorageException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test]
@@ -125,8 +112,7 @@ internal class SaleBusinessLogicContractTests
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, DiscountType.None, 0, false, []),
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, DiscountType.None, 0, false, []),
};
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(),
It.IsAny<string>(), It.IsAny<string>())).Returns(listOriginal);
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Returns(listOriginal);
//Act
var list = _saleBusinessLogicContract.GetAllSalesByEmployeeByPeriod(employeeId, date, date.AddDays(1));
//Assert
@@ -139,17 +125,13 @@ internal class SaleBusinessLogicContractTests
public void GetAllSalesByEmployeeByPeriod_ReturnEmptyList_Test()
{
//Arrange
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(),
It.IsAny<string>(), It.IsAny<string>())).Returns([]);
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Returns([]);
//Act
var list = _saleBusinessLogicContract.GetAllSalesByEmployeeByPeriod(Guid.NewGuid().ToString(), DateTime.UtcNow,
DateTime.UtcNow.AddDays(1));
var list = _saleBusinessLogicContract.GetAllSalesByEmployeeByPeriod(Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow.AddDays(1));
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
_saleStorageContract.Verify(
x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(),
It.IsAny<string>()), Times.Once);
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test]
@@ -158,70 +140,44 @@ internal class SaleBusinessLogicContractTests
//Arrange
var date = DateTime.UtcNow;
//Act&Assert
Assert.That(
() => _saleBusinessLogicContract.GetAllSalesByEmployeeByPeriod(Guid.NewGuid().ToString(), date, date),
Throws.TypeOf<IncorrectDatesException>());
Assert.That(
() => _saleBusinessLogicContract.GetAllSalesByEmployeeByPeriod(Guid.NewGuid().ToString(), date,
date.AddSeconds(-1)), Throws.TypeOf<IncorrectDatesException>());
_saleStorageContract.Verify(
x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(),
It.IsAny<string>()), Times.Never);
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByEmployeeByPeriod(Guid.NewGuid().ToString(), date, date), Throws.TypeOf<IncorrectDatesException>());
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByEmployeeByPeriod(Guid.NewGuid().ToString(), date, date.AddSeconds(-1)), Throws.TypeOf<IncorrectDatesException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSalesByEmployeeByPeriod_EmployeeIdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(
() => _saleBusinessLogicContract.GetAllSalesByEmployeeByPeriod(null, DateTime.UtcNow,
DateTime.UtcNow.AddDays(1)), Throws.TypeOf<ArgumentNullException>());
Assert.That(
() => _saleBusinessLogicContract.GetAllSalesByEmployeeByPeriod(string.Empty, DateTime.UtcNow,
DateTime.UtcNow.AddDays(1)), Throws.TypeOf<ArgumentNullException>());
_saleStorageContract.Verify(
x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(),
It.IsAny<string>()), Times.Never);
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByEmployeeByPeriod(null, DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByEmployeeByPeriod(string.Empty, DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<ArgumentNullException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSalesByEmployeeByPeriod_EmployeeIdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(
() => _saleBusinessLogicContract.GetAllSalesByEmployeeByPeriod("employeeId", DateTime.UtcNow,
DateTime.UtcNow.AddDays(1)), Throws.TypeOf<ValidationException>());
_saleStorageContract.Verify(
x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(),
It.IsAny<string>()), Times.Never);
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByEmployeeByPeriod("employeeId", DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<ValidationException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSalesByEmployeeByPeriod_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(
() => _saleBusinessLogicContract.GetAllSalesByEmployeeByPeriod(Guid.NewGuid().ToString(), DateTime.UtcNow,
DateTime.UtcNow.AddDays(1)), Throws.TypeOf<NullListException>());
_saleStorageContract.Verify(
x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(),
It.IsAny<string>()), Times.Once);
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByEmployeeByPeriod(Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<NullListException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSalesByEmployeeByPeriod_StorageThrowError_ThrowException_Test()
{
//Arrange
_saleStorageContract
.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(),
It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(
() => _saleBusinessLogicContract.GetAllSalesByEmployeeByPeriod(Guid.NewGuid().ToString(), DateTime.UtcNow,
DateTime.UtcNow.AddDays(1)), Throws.TypeOf<StorageException>());
_saleStorageContract.Verify(
x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(),
It.IsAny<string>()), Times.Once);
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByEmployeeByPeriod(Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<StorageException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test]
@@ -237,8 +193,7 @@ internal class SaleBusinessLogicContractTests
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, DiscountType.None, 0, false, []),
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, DiscountType.None, 0, false, []),
};
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(),
It.IsAny<string>(), It.IsAny<string>())).Returns(listOriginal);
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Returns(listOriginal);
//Act
var list = _saleBusinessLogicContract.GetAllSalesByClientByPeriod(clientId, date, date.AddDays(1));
//Assert
@@ -251,17 +206,13 @@ internal class SaleBusinessLogicContractTests
public void GetAllSalesByClientByPeriod_ReturnEmptyList_Test()
{
//Arrange
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(),
It.IsAny<string>(), It.IsAny<string>())).Returns([]);
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Returns([]);
//Act
var list = _saleBusinessLogicContract.GetAllSalesByClientByPeriod(Guid.NewGuid().ToString(), DateTime.UtcNow,
DateTime.UtcNow.AddDays(1));
var list = _saleBusinessLogicContract.GetAllSalesByClientByPeriod(Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow.AddDays(1));
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
_saleStorageContract.Verify(
x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(),
It.IsAny<string>()), Times.Once);
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test]
@@ -270,69 +221,44 @@ internal class SaleBusinessLogicContractTests
//Arrange
var date = DateTime.UtcNow;
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByClientByPeriod(Guid.NewGuid().ToString(), date, date),
Throws.TypeOf<IncorrectDatesException>());
Assert.That(
() => _saleBusinessLogicContract.GetAllSalesByClientByPeriod(Guid.NewGuid().ToString(), date,
date.AddSeconds(-1)), Throws.TypeOf<IncorrectDatesException>());
_saleStorageContract.Verify(
x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(),
It.IsAny<string>()), Times.Never);
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByClientByPeriod(Guid.NewGuid().ToString(), date, date), Throws.TypeOf<IncorrectDatesException>());
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByClientByPeriod(Guid.NewGuid().ToString(), date, date.AddSeconds(-1)), Throws.TypeOf<IncorrectDatesException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSalesByClientByPeriod_ClientIdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(
() => _saleBusinessLogicContract.GetAllSalesByClientByPeriod(null, DateTime.UtcNow,
DateTime.UtcNow.AddDays(1)), Throws.TypeOf<ArgumentNullException>());
Assert.That(
() => _saleBusinessLogicContract.GetAllSalesByClientByPeriod(string.Empty, DateTime.UtcNow,
DateTime.UtcNow.AddDays(1)), Throws.TypeOf<ArgumentNullException>());
_saleStorageContract.Verify(
x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(),
It.IsAny<string>()), Times.Never);
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByClientByPeriod(null, DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByClientByPeriod(string.Empty, DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<ArgumentNullException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSalesByClientByPeriod_ClientIdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(
() => _saleBusinessLogicContract.GetAllSalesByClientByPeriod("clientId", DateTime.UtcNow,
DateTime.UtcNow.AddDays(1)), Throws.TypeOf<ValidationException>());
_saleStorageContract.Verify(
x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(),
It.IsAny<string>()), Times.Never);
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByClientByPeriod("clientId", DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<ValidationException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSalesByClientByPeriod_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(
() => _saleBusinessLogicContract.GetAllSalesByClientByPeriod(Guid.NewGuid().ToString(), DateTime.UtcNow,
DateTime.UtcNow.AddDays(1)), Throws.TypeOf<NullListException>());
_saleStorageContract.Verify(
x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(),
It.IsAny<string>()), Times.Once);
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByClientByPeriod(Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<NullListException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSalesByClientByPeriod_StorageThrowError_ThrowException_Test()
{
//Arrange
_saleStorageContract
.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(),
It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(
() => _saleBusinessLogicContract.GetAllSalesByClientByPeriod(Guid.NewGuid().ToString(), DateTime.UtcNow,
DateTime.UtcNow.AddDays(1)), Throws.TypeOf<StorageException>());
_saleStorageContract.Verify(
x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(),
It.IsAny<string>()), Times.Once);
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByClientByPeriod(Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<StorageException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test]
@@ -348,8 +274,7 @@ internal class SaleBusinessLogicContractTests
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, DiscountType.None, 0, false, []),
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, DiscountType.None, 0, false, []),
};
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(),
It.IsAny<string>(), It.IsAny<string>())).Returns(listOriginal);
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Returns(listOriginal);
//Act
var list = _saleBusinessLogicContract.GetAllSalesByProductByPeriod(cocktailId, date, date.AddDays(1));
//Assert
@@ -362,17 +287,13 @@ internal class SaleBusinessLogicContractTests
public void GetAllSalesByProductByPeriod_ReturnEmptyList_Test()
{
//Arrange
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(),
It.IsAny<string>(), It.IsAny<string>())).Returns([]);
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Returns([]);
//Act
var list = _saleBusinessLogicContract.GetAllSalesByProductByPeriod(Guid.NewGuid().ToString(), DateTime.UtcNow,
DateTime.UtcNow.AddDays(1));
var list = _saleBusinessLogicContract.GetAllSalesByProductByPeriod(Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow.AddDays(1));
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
_saleStorageContract.Verify(
x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(),
It.IsAny<string>()), Times.Once);
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test]
@@ -381,70 +302,44 @@ internal class SaleBusinessLogicContractTests
//Arrange
var date = DateTime.UtcNow;
//Act&Assert
Assert.That(
() => _saleBusinessLogicContract.GetAllSalesByProductByPeriod(Guid.NewGuid().ToString(), date, date),
Throws.TypeOf<IncorrectDatesException>());
Assert.That(
() => _saleBusinessLogicContract.GetAllSalesByProductByPeriod(Guid.NewGuid().ToString(), date,
date.AddSeconds(-1)), Throws.TypeOf<IncorrectDatesException>());
_saleStorageContract.Verify(
x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(),
It.IsAny<string>()), Times.Never);
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByProductByPeriod(Guid.NewGuid().ToString(), date, date), Throws.TypeOf<IncorrectDatesException>());
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByProductByPeriod(Guid.NewGuid().ToString(), date, date.AddSeconds(-1)), Throws.TypeOf<IncorrectDatesException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSalesByProductByPeriod_ProductIdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(
() => _saleBusinessLogicContract.GetAllSalesByProductByPeriod(null, DateTime.UtcNow,
DateTime.UtcNow.AddDays(1)), Throws.TypeOf<ArgumentNullException>());
Assert.That(
() => _saleBusinessLogicContract.GetAllSalesByProductByPeriod(string.Empty, DateTime.UtcNow,
DateTime.UtcNow.AddDays(1)), Throws.TypeOf<ArgumentNullException>());
_saleStorageContract.Verify(
x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(),
It.IsAny<string>()), Times.Never);
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByProductByPeriod(null, DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByProductByPeriod(string.Empty, DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<ArgumentNullException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSalesByProductByPeriod_ProductIdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(
() => _saleBusinessLogicContract.GetAllSalesByProductByPeriod("ProductId", DateTime.UtcNow,
DateTime.UtcNow.AddDays(1)), Throws.TypeOf<ValidationException>());
_saleStorageContract.Verify(
x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(),
It.IsAny<string>()), Times.Never);
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByProductByPeriod("ProductId", DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<ValidationException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSalesByProductByPeriod_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(
() => _saleBusinessLogicContract.GetAllSalesByProductByPeriod(Guid.NewGuid().ToString(), DateTime.UtcNow,
DateTime.UtcNow.AddDays(1)), Throws.TypeOf<NullListException>());
_saleStorageContract.Verify(
x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(),
It.IsAny<string>()), Times.Once);
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByProductByPeriod(Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<NullListException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSalesByProductByPeriod_StorageThrowError_ThrowException_Test()
{
//Arrange
_saleStorageContract
.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(),
It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(
() => _saleBusinessLogicContract.GetAllSalesByProductByPeriod(Guid.NewGuid().ToString(), DateTime.UtcNow,
DateTime.UtcNow.AddDays(1)), Throws.TypeOf<StorageException>());
_saleStorageContract.Verify(
x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(),
It.IsAny<string>()), Times.Once);
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByProductByPeriod(Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<StorageException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test]
@@ -453,7 +348,7 @@ internal class SaleBusinessLogicContractTests
//Arrange
var id = Guid.NewGuid().ToString();
var record = new SaleDataModel(id, Guid.NewGuid().ToString(), null, 10, DiscountType.None, 0, false,
[new SaleProductDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]);
[new SaleProductDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]);
_saleStorageContract.Setup(x => x.GetElementById(id)).Returns(record);
//Act
var element = _saleBusinessLogicContract.GetSaleByData(id);
@@ -468,8 +363,7 @@ internal class SaleBusinessLogicContractTests
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetSaleByData(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _saleBusinessLogicContract.GetSaleByData(string.Empty),
Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _saleBusinessLogicContract.GetSaleByData(string.Empty), Throws.TypeOf<ArgumentNullException>());
_saleStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Never);
}
@@ -485,8 +379,7 @@ internal class SaleBusinessLogicContractTests
public void GetSaleByData_GetById_NotFoundRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetSaleByData(Guid.NewGuid().ToString()),
Throws.TypeOf<ElementNotFoundException>());
Assert.That(() => _saleBusinessLogicContract.GetSaleByData(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_saleStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
}
@@ -494,11 +387,9 @@ internal class SaleBusinessLogicContractTests
public void GetSaleByData_StorageThrowError_ThrowException_Test()
{
//Arrange
_saleStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Throws(new StorageException(new InvalidOperationException()));
_saleStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetSaleByData(Guid.NewGuid().ToString()),
Throws.TypeOf<StorageException>());
Assert.That(() => _saleBusinessLogicContract.GetSaleByData(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_saleStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
}
@@ -507,23 +398,23 @@ internal class SaleBusinessLogicContractTests
{
//Arrange
var flag = false;
var record = new SaleDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(),
10, DiscountType.None, 10,
var record = new SaleDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 10, DiscountType.None, 10,
false, [new SaleProductDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]);
_storageStorageContract.Setup(x => x.CheckComponents(It.IsAny<SaleDataModel>())).Returns(true);
_saleStorageContract.Setup(x => x.AddElement(It.IsAny<SaleDataModel>()))
.Callback((SaleDataModel x) =>
{
flag = x.Id == record.Id && x.EmployeeId == record.EmployeeId && x.ClientId == record.ClientId &&
x.SaleDate == record.SaleDate && x.Sum == record.Sum && x.DiscountType == record.DiscountType &&
x.Discount == record.Discount && x.IsCancel == record.IsCancel &&
x.Products.Count == record.Products.Count &&
x.Products.First().ProductId == record.Products.First().ProductId &&
x.Products.First().SaleId == record.Products.First().SaleId &&
x.Products.First().Count == record.Products.First().Count;
x.SaleDate == record.SaleDate && x.Sum == record.Sum && x.DiscountType == record.DiscountType &&
x.Discount == record.Discount && x.IsCancel == record.IsCancel && x.Products.Count == record.Products.Count &&
x.Products.First().ProductId == record.Products.First().ProductId &&
x.Products.First().SaleId == record.Products.First().SaleId &&
x.Products.First().Count == record.Products.First().Count;
});
//Act
_saleBusinessLogicContract.InsertSale(record);
//Assert
_storageStorageContract.Verify(x => x.CheckComponents(It.IsAny<SaleDataModel>()), Times.Once);
_saleStorageContract.Verify(x => x.AddElement(It.IsAny<SaleDataModel>()), Times.Once);
Assert.That(flag);
}
@@ -532,15 +423,13 @@ internal class SaleBusinessLogicContractTests
public void InsertSale_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_saleStorageContract.Setup(x => x.AddElement(It.IsAny<SaleDataModel>()))
.Throws(new ElementExistsException("Data", "Data"));
_storageStorageContract.Setup(x => x.CheckComponents(It.IsAny<SaleDataModel>())).Returns(true);
_saleStorageContract.Setup(x => x.AddElement(It.IsAny<SaleDataModel>())).Throws(new ElementExistsException("Data", "Data"));
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.InsertSale(new(Guid.NewGuid().ToString(),
Guid.NewGuid().ToString(),
Guid.NewGuid().ToString(), 10, DiscountType.None, 10, false,
[new SaleProductDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])),
Throws.TypeOf<ElementExistsException>());
Assert.That(() => _saleBusinessLogicContract.InsertSale(new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(),
Guid.NewGuid().ToString(), 10, DiscountType.None, 10, false, [new SaleProductDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<ElementExistsException>());
_saleStorageContract.Verify(x => x.AddElement(It.IsAny<SaleDataModel>()), Times.Once);
_storageStorageContract.Verify(x => x.CheckComponents(It.IsAny<SaleDataModel>()), Times.Once);
}
[Test]
@@ -555,10 +444,7 @@ internal class SaleBusinessLogicContractTests
public void InsertSale_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(
() => _saleBusinessLogicContract.InsertSale(new SaleDataModel("id", Guid.NewGuid().ToString(),
Guid.NewGuid().ToString(), 10, DiscountType.None, 10, false, [])),
Throws.TypeOf<ValidationException>());
Assert.That(() => _saleBusinessLogicContract.InsertSale(new SaleDataModel("id", Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 10, DiscountType.None, 10, false, [])), Throws.TypeOf<ValidationException>());
_saleStorageContract.Verify(x => x.AddElement(It.IsAny<SaleDataModel>()), Times.Never);
}
@@ -566,17 +452,27 @@ internal class SaleBusinessLogicContractTests
public void InsertSale_StorageThrowError_ThrowException_Test()
{
//Arrange
_saleStorageContract.Setup(x => x.AddElement(It.IsAny<SaleDataModel>()))
.Throws(new StorageException(new InvalidOperationException()));
_storageStorageContract.Setup(x => x.CheckComponents(It.IsAny<SaleDataModel>())).Returns(true);
_saleStorageContract.Setup(x => x.AddElement(It.IsAny<SaleDataModel>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.InsertSale(new(Guid.NewGuid().ToString(),
Guid.NewGuid().ToString(),
Guid.NewGuid().ToString(), 10, DiscountType.None, 10, false,
[new SaleProductDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])),
Throws.TypeOf<StorageException>());
Assert.That(() => _saleBusinessLogicContract.InsertSale(new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(),
Guid.NewGuid().ToString(), 10, DiscountType.None, 10, false, [new SaleProductDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<StorageException>());
_storageStorageContract.Verify(x => x.CheckComponents(It.IsAny<SaleDataModel>()), Times.Once);
_saleStorageContract.Verify(x => x.AddElement(It.IsAny<SaleDataModel>()), Times.Once);
}
[Test]
public void InsertSale_InsufficientError_ThrowException_Test()
{
//Arrange
_storageStorageContract.Setup(x => x.CheckComponents(It.IsAny<SaleDataModel>())).Returns(false);
Assert.That(() => _saleBusinessLogicContract.InsertSale(new SaleDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(),
Guid.NewGuid().ToString(), 10, DiscountType.None, 10, false,
[new SaleProductDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<InsufficientException>());
//Act&Assert
_storageStorageContract.Verify(x => x.CheckComponents(It.IsAny<SaleDataModel>()), Times.Once);
}
[Test]
public void CancelSale_CorrectRecord_Test()
{
@@ -598,8 +494,7 @@ internal class SaleBusinessLogicContractTests
var id = Guid.NewGuid().ToString();
_saleStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new ElementNotFoundException(id));
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.CancelSale(Guid.NewGuid().ToString()),
Throws.TypeOf<ElementNotFoundException>());
Assert.That(() => _saleBusinessLogicContract.CancelSale(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_saleStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
}
@@ -624,11 +519,9 @@ internal class SaleBusinessLogicContractTests
public void CancelSale_StorageThrowError_ThrowException_Test()
{
//Arrange
_saleStorageContract.Setup(x => x.DelElement(It.IsAny<string>()))
.Throws(new StorageException(new InvalidOperationException()));
_saleStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.CancelSale(Guid.NewGuid().ToString()),
Throws.TypeOf<StorageException>());
Assert.That(() => _saleBusinessLogicContract.CancelSale(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_saleStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
}
}
}

View File

@@ -11,6 +11,7 @@
<ItemGroup>
<PackageReference Include="coverlet.collector" Version="6.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="9.0.2" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.8.0" />
<PackageReference Include="Moq" Version="4.20.72" />
<PackageReference Include="NUnit" Version="3.14.0" />
@@ -21,6 +22,7 @@
<ItemGroup>
<ProjectReference Include="..\CandyHouseBusinessLogic\CandyHouseBusinessLogic.csproj" />
<ProjectReference Include="..\CandyHouseContracts\CandyHouseContracts.csproj" />
<ProjectReference Include="..\CandyHouseDatabase\CandyHouseDatabase.csproj" />
</ItemGroup>
<ItemGroup>

View File

@@ -15,78 +15,49 @@ internal class ProductDataModelTests
[Test]
public void IdIsNullOrEmptyTest()
{
var cocktail = CreateDataModel(null, "name", "country", 10.5, ProductType.Cake,
CreateSuppliesDataModel(), CreateStorageDataModel());
Assert.That(() => cocktail.Validate(), Throws.TypeOf<ValidationException>());
cocktail = CreateDataModel(string.Empty, "name", "country", 10.5, ProductType.Cake,
CreateSuppliesDataModel(), CreateStorageDataModel());
Assert.That(() => cocktail.Validate(), Throws.TypeOf<ValidationException>());
var product = CreateDataModel(null, "name", "description", 10.5, ProductType.Cake);
Assert.That(() => product.Validate(), Throws.TypeOf<ValidationException>());
product = CreateDataModel(string.Empty, "name", "description", 10.5, ProductType.Cake);
Assert.That(() => product.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void IdIsNotGuidTest()
{
var cocktail = CreateDataModel("id", "name", "country", 10.5, ProductType.Cake,
CreateSuppliesDataModel(), CreateStorageDataModel());
Assert.That(() => cocktail.Validate(), Throws.TypeOf<ValidationException>());
var product = CreateDataModel("id", "name", "description", 10.5, ProductType.Cake);
Assert.That(() => product.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void ProductNameIsNullOrEmptyTest()
{
var cocktail = CreateDataModel(Guid.NewGuid().ToString(), null, "country", 10.5, ProductType.Cake,
CreateSuppliesDataModel(), CreateStorageDataModel());
var cocktail = CreateDataModel(Guid.NewGuid().ToString(), null, "description", 10.5, ProductType.Cake);
Assert.That(() => cocktail.Validate(), Throws.TypeOf<ValidationException>());
cocktail = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, "country", 10.5, ProductType.Cake,
CreateSuppliesDataModel(), CreateStorageDataModel());
cocktail = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, "description", 10.5, ProductType.Cake);
Assert.That(() => cocktail.Validate(), Throws.TypeOf<ValidationException>());
}
public void ProductDescriptionIsNullOrEmptyTest()
{
var cocktail = CreateDataModel(Guid.NewGuid().ToString(), "name", null, 10.5, ProductType.Cake,
CreateSuppliesDataModel(), CreateStorageDataModel());
var cocktail = CreateDataModel(Guid.NewGuid().ToString(), "name", null, 10.5, ProductType.Cake);
Assert.That(() => cocktail.Validate(), Throws.TypeOf<ValidationException>());
cocktail = CreateDataModel(Guid.NewGuid().ToString(), "name", string.Empty, 10.5, ProductType.Cake,
CreateSuppliesDataModel(), CreateStorageDataModel());
cocktail = CreateDataModel(Guid.NewGuid().ToString(), "name", string.Empty, 10.5, ProductType.Cake);
Assert.That(() => cocktail.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void PriceIsLessOrZeroTest()
{
var cocktail = CreateDataModel(Guid.NewGuid().ToString(), null, null, 0, ProductType.Cake,
CreateSuppliesDataModel(), CreateStorageDataModel());
Assert.That(() => cocktail.Validate(), Throws.TypeOf<ValidationException>());
cocktail = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, string.Empty, -10.5, ProductType.Cake,
CreateSuppliesDataModel(), CreateStorageDataModel());
Assert.That(() => cocktail.Validate(), Throws.TypeOf<ValidationException>());
var product = CreateDataModel(Guid.NewGuid().ToString(), null, null, 0, ProductType.Cake);
Assert.That(() => product.Validate(), Throws.TypeOf<ValidationException>());
product = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, string.Empty, -10.5, ProductType.Cake);
Assert.That(() => product.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void ProductTypeIsNoneTest()
{
var cocktail = CreateDataModel(Guid.NewGuid().ToString(), null, null, 0, ProductType.Cake,
CreateSuppliesDataModel(), CreateStorageDataModel());
Assert.That(() => cocktail.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void SuppliesIsEmptyOrNullTest()
{
var model = CreateDataModel(Guid.NewGuid().ToString(), "name", "country", 10.5, ProductType.Cake, [], CreateStorageDataModel());
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
model = CreateDataModel(Guid.NewGuid().ToString(), "name", "country", 10.5, ProductType.Cake, null, CreateStorageDataModel());
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void StorageIsEmptyOrNullTest()
{
var model = CreateDataModel(Guid.NewGuid().ToString(), "name", "country", 10.5, ProductType.Cake, CreateSuppliesDataModel(), []);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
model = CreateDataModel(Guid.NewGuid().ToString(), "name", "country", 10.5, ProductType.Cake, CreateSuppliesDataModel(), null);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
var product = CreateDataModel(Guid.NewGuid().ToString(), null, null, 0, ProductType.Cake);
Assert.That(() => product.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
@@ -94,12 +65,12 @@ internal class ProductDataModelTests
{
var productId = Guid.NewGuid().ToString();
var productName = "name";
var productDescription = "country";
var productDescription = "description";
var price = 10.5;
var productType = ProductType.Chocolate;
var supplies = CreateSuppliesDataModel();
var agency = CreateStorageDataModel();
var product = CreateDataModel(productId, productName, productDescription, price, productType, supplies, agency);
var storage = CreateStorageDataModel();
var product = CreateDataModel(productId, productName, productDescription, price, productType);
Assert.That(() => product.Validate(), Throws.Nothing);
Assert.Multiple(() =>
{
@@ -107,15 +78,12 @@ internal class ProductDataModelTests
Assert.That(product.ProductName, Is.EqualTo(productName));
Assert.That(product.ProductDescription, Is.EqualTo(productDescription));
Assert.That(product.Price, Is.EqualTo(price));
Assert.That(product.Type, Is.EqualTo(productType));
Assert.That(product.Supplies, Is.EqualTo(supplies));
Assert.That(product.Storage, Is.EqualTo(agency));
Assert.That(product.ProductType, Is.EqualTo(productType));
});
}
private static ProductDataModel CreateDataModel(string? id, string? productName, string? countryName, double price, ProductType productType,
List<ProductSuppliesDataModel> supplies, List<ProductStorageDataModel> agency) =>
new(id, productName, countryName,price, productType, supplies, agency);
private static ProductDataModel CreateDataModel(string? id, string? productName, string? descriptionName, double price, ProductType productType) =>
new(id, productName, descriptionName,price, productType);
private static List<ProductSuppliesDataModel> CreateSuppliesDataModel()
=> [new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 1)];

View File

@@ -57,19 +57,19 @@ internal class ProductStorageDataModelTests
[Test]
public void AllFieldsIsCorrectTest()
{
var agencyId = Guid.NewGuid().ToString();
var storageId = Guid.NewGuid().ToString();
var productId = Guid.NewGuid().ToString();
var count = 1;
var model = CreateDataModel(agencyId, productId, count);
var model = CreateDataModel(storageId, productId, count);
Assert.That(() => model.Validate(), Throws.Nothing);
Assert.Multiple(() =>
{
Assert.That(model.StorageId, Is.EqualTo(agencyId));
Assert.That(model.StorageId, Is.EqualTo(storageId));
Assert.That(model.ProductId, Is.EqualTo(productId));
Assert.That(model.Count, Is.EqualTo(count));
});
}
private static ProductStorageDataModel CreateDataModel(string? agencyId, string? productId, int count)
=> new(agencyId, productId, count);
private static ProductStorageDataModel CreateDataModel(string? storageId, string? productId, int count)
=> new(storageId, productId, count);
}

View File

@@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CandyHouseContracts.Infrastructure;
namespace CandyHouseTests.Infrastructure;
internal class ConfigurationDatabaseTest : IConfigurationDatabase
{
public string ConnectionString => "Host=127.0.0.1;Port=5432;Database=CandyHouseTest;Username=postgres;Password=postgres;";
}

View File

@@ -0,0 +1,30 @@
using CandyHouseTests.Infrastructure;
using CandyHouseDatabase;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseTests.StoragesContractsTests;
internal abstract class BaseStorageContractTest
{
protected CandyHouseDbContext CandyHouseDbContext { get; private set; }
[OneTimeSetUp]
public void OneTimeSetUp()
{
CandyHouseDbContext = new CandyHouseDbContext(new ConfigurationDatabaseTest());
CandyHouseDbContext.Database.EnsureDeleted();
CandyHouseDbContext.Database.EnsureCreated();
}
[OneTimeTearDown]
public void OneTimeTearDown()
{
CandyHouseDbContext.Database.EnsureDeleted();
CandyHouseDbContext.Dispose();
}
}

View File

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

View File

@@ -0,0 +1,233 @@
using CandyHouseContracts.DataModels;
using CandyHouseContracts.Exceptions;
using CandyHouseDatabase.Implementations;
using CandyHouseDatabase.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseTests.StoragesContractsTests;
[TestFixture]
class EmployeeStorageContractTests : BaseStorageContractTest
{
private EmployeeStorageContract _employeeStorageContract;
[SetUp]
public void SetUp()
{
_employeeStorageContract = new EmployeeStorageContract(CandyHouseDbContext);
}
[TearDown]
public void TearDown()
{
CandyHouseDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Employees\"CASCADE; ");
}
[Test]
public void Try_GetList_WhenHaveRecords_Test()
{
var employee = InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 1", "abc@gmail.com");
InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 2", "abc@gmail.com");
InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 3", "abc@gmail.com");
var list = _employeeStorageContract.GetList();
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(3));
AssertElement(list.First(), employee);
}
[Test]
public void Try_GetList_WhenNoRecords_Test()
{
var list = _employeeStorageContract.GetList();
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.Empty);
}
[Test]
public void Try_GetList_ByPostId_Test()
{
var postId = Guid.NewGuid().ToString();
InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 1", "abc@gmail.com", postId);
InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 2", "abc@gmail.com", postId);
InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 3", "abc@gmail.com");
var list = _employeeStorageContract.GetList(postId: postId);
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(2));
Assert.That(list.All(x => x.PostId == postId));
}
[Test]
public void Try_GetList_ByBirthDate_Test()
{
InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 1", "abc@gmail.com", birthDate: DateTime.UtcNow.AddYears(-25));
InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 2", "abc@gmail.com", birthDate: DateTime.UtcNow.AddYears(-21));
InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 3", "abc@gmail.com", birthDate: DateTime.UtcNow.AddYears(-20));
InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 4", "abc@gmail.com", birthDate: DateTime.UtcNow.AddYears(-19));
var list = _employeeStorageContract.GetList(fromBirthDate: DateTime.UtcNow.AddYears(-21).AddMinutes(-1), toBirthDate: DateTime.UtcNow.AddYears(-20).AddMinutes(1));
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(2));
}
[Test]
public void Try_GetList_ByEmploymentDate_Test()
{
InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 1", "abc@gmail.com", employmentDate: DateTime.UtcNow.AddDays(-2));
InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 2", "abc@gmail.com", employmentDate: DateTime.UtcNow.AddDays(-1));
InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 3", "abc@gmail.com", employmentDate: DateTime.UtcNow.AddDays(1));
InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 4", "abc@gmail.com", employmentDate: DateTime.UtcNow.AddDays(2));
var list = _employeeStorageContract.GetList(fromEmploymentDate: DateTime.UtcNow.AddDays(-1).AddMinutes(-1), toEmploymentDate: DateTime.UtcNow.AddDays(1).AddMinutes(1));
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(2));
}
[Test]
public void Try_GetList_ByAllParameters_Test()
{
var postId = Guid.NewGuid().ToString();
InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 1", "abc@gmail.com", postId, birthDate: DateTime.UtcNow.AddYears(-25), employmentDate: DateTime.UtcNow.AddDays(-2));
InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 2", "abc@gmail.com", postId, birthDate: DateTime.UtcNow.AddYears(-22), employmentDate: DateTime.UtcNow.AddDays(-1));
InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 3", "abc@gmail.com", postId, birthDate: DateTime.UtcNow.AddYears(-21), employmentDate: DateTime.UtcNow.AddDays(-1));
InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 4", "abc@gmail.com", birthDate: DateTime.UtcNow.AddYears(-20), employmentDate: DateTime.UtcNow.AddDays(1));
var list = _employeeStorageContract.GetList(postId: postId, fromBirthDate: DateTime.UtcNow.AddYears(-21).AddMinutes(-1), toBirthDate: DateTime.UtcNow.AddYears(-20).AddMinutes(1),
fromEmploymentDate: DateTime.UtcNow.AddDays(-1).AddMinutes(-1), toEmploymentDate: DateTime.UtcNow.AddDays(1).AddMinutes(1));
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(1));
}
[Test]
public void Try_GetElementById_WhenHaveRecord_Test()
{
var employee = InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString());
AssertElement(_employeeStorageContract.GetElementById(employee.Id), employee);
}
[Test]
public void Try_GetElementById_WhenNoRecord_Test()
{
Assert.That(() => _employeeStorageContract.GetElementById(Guid.NewGuid().ToString()), Is.Null);
}
[Test]
public void Try_GetElementByFIO_WhenHaveRecord_Test()
{
var employee = InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString());
AssertElement(_employeeStorageContract.GetElementByFIO(employee.FIO), employee);
}
[Test]
public void Try_GetElementByFIO_WhenNoRecord_Test()
{
Assert.That(() => _employeeStorageContract.GetElementByFIO("New Fio"), Is.Null);
}
[Test]
public void Try_AddElement_Test()
{
var employee = CreateModel(Guid.NewGuid().ToString());
_employeeStorageContract.AddElement(employee);
AssertElement(GetEmployeeFromDatabase(employee.Id), employee);
}
[Test]
public void Try_AddElement_WhenHaveRecordWithSameId_Test()
{
var employee = CreateModel(Guid.NewGuid().ToString());
InsertEmployeeToDatabaseAndReturn(employee.Id);
Assert.That(() => _employeeStorageContract.AddElement(employee), Throws.TypeOf<ElementExistsException>());
}
[Test]
public void Try_UpdElement_Test()
{
var employee = CreateModel(Guid.NewGuid().ToString(), "New Fio");
InsertEmployeeToDatabaseAndReturn(employee.Id);
_employeeStorageContract.UpdElement(employee);
AssertElement(GetEmployeeFromDatabase(employee.Id), employee);
}
[Test]
public void Try_UpdElement_WhenNoRecordWithThisId_Test()
{
Assert.That(() => _employeeStorageContract.UpdElement(CreateModel(Guid.NewGuid().ToString())), Throws.TypeOf<ElementNotFoundException>());
}
[Test]
public void Try_UpdElement_WhenNoRecordWasDeleted_Test()
{
var employee = CreateModel(Guid.NewGuid().ToString());
InsertEmployeeToDatabaseAndReturn(employee.Id, isDeleted: true);
Assert.That(() => _employeeStorageContract.UpdElement(employee), Throws.TypeOf<ElementNotFoundException>());
}
[Test]
public void Try_DelElement_Test()
{
var employee = InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString());
_employeeStorageContract.DelElement(employee.Id);
var element = GetEmployeeFromDatabase(employee.Id);
Assert.That(element, Is.Not.Null);
Assert.That(element.IsDeleted);
}
[Test]
public void Try_DelElement_WhenNoRecordWithThisId_Test()
{
Assert.That(() => _employeeStorageContract.DelElement(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
}
[Test]
public void Try_DelElement_WhenNoRecordWasDeleted_Test()
{
var employee = CreateModel(Guid.NewGuid().ToString());
InsertEmployeeToDatabaseAndReturn(employee.Id, isDeleted: true);
Assert.That(() => _employeeStorageContract.DelElement(employee.Id), Throws.TypeOf<ElementNotFoundException>());
}
private Employee InsertEmployeeToDatabaseAndReturn(string id, string fio = "test", string email = "abc@mail.ru",string ? postId = null, DateTime? birthDate = null, DateTime? employmentDate = null, bool isDeleted = false)
{
var employee = new Employee() { Id = id, FIO = fio, Email = email, PostId = postId ?? Guid.NewGuid().ToString(), BirthDate = birthDate ?? DateTime.UtcNow.AddYears(-20), EmploymentDate = employmentDate ?? DateTime.UtcNow, IsDeleted = isDeleted };
CandyHouseDbContext.Employees.Add(employee);
CandyHouseDbContext.SaveChanges();
return employee;
}
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.PostId, Is.EqualTo(expected.PostId));
Assert.That(actual.FIO, Is.EqualTo(expected.FIO));
Assert.That(actual.Email, Is.EqualTo(expected.Email));
Assert.That(actual.BirthDate, Is.EqualTo(expected.BirthDate));
Assert.That(actual.EmploymentDate, Is.EqualTo(expected.EmploymentDate));
Assert.That(actual.IsDeleted, Is.EqualTo(expected.IsDeleted));
});
}
private static EmployeeDataModel CreateModel(string id, string fio = "fio", string email = "abc@mail.ru", string? postId = null, DateTime? birthDate = null, DateTime? employmentDate = null, bool isDeleted = false) =>
new(id, fio, email, postId ?? Guid.NewGuid().ToString(), birthDate ?? DateTime.UtcNow.AddYears(-20), employmentDate ?? DateTime.UtcNow, isDeleted);
private Employee? GetEmployeeFromDatabase(string id) => CandyHouseDbContext.Employees.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.PostId, Is.EqualTo(expected.PostId));
Assert.That(actual.FIO, Is.EqualTo(expected.FIO));
Assert.That(actual.Email, Is.EqualTo(expected.Email));
Assert.That(actual.BirthDate, Is.EqualTo(expected.BirthDate));
Assert.That(actual.EmploymentDate, Is.EqualTo(expected.EmploymentDate));
Assert.That(actual.IsDeleted, Is.EqualTo(expected.IsDeleted));
});
}
}

View File

@@ -0,0 +1,216 @@
using CandyHouseContracts.DataModels;
using CandyHouseContracts.Enums;
using CandyHouseContracts.Exceptions;
using CandyHouseDatabase.Implementations;
using CandyHouseDatabase.Models;
using Microsoft.EntityFrameworkCore;
using Moq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static NUnit.Framework.Internal.OSPlatform;
using ProductType = CandyHouseContracts.Enums.ProductType;
namespace CandyHouseTests.StoragesContractsTests;
[TestFixture]
internal class ProductStorageContractTests : BaseStorageContractTest
{
private ProductStorageContract _productStorageContract;
[SetUp]
public void SetUp()
{
_productStorageContract = new ProductStorageContract(CandyHouseDbContext);
}
[TearDown]
public void TearDown()
{
CandyHouseDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Products\" 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_GetHistoryByProductId_WhenHaveRecords_Test()
{
var product = InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 1");
InsertProductHistoryToDatabaseAndReturn(product.Id, 20, DateTime.UtcNow.AddDays(-1));
InsertProductHistoryToDatabaseAndReturn(product.Id, 30, DateTime.UtcNow.AddMinutes(-10));
InsertProductHistoryToDatabaseAndReturn(product.Id, 40, DateTime.UtcNow.AddDays(1));
var list = _productStorageContract.GetHistoryByProductId(product.Id);
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(3));
}
[Test]
public void Try_GetHistoryByProductId_WhenNoRecords_Test()
{
var product = InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 1");
InsertProductHistoryToDatabaseAndReturn(product.Id, 20, DateTime.UtcNow.AddDays(-1));
InsertProductHistoryToDatabaseAndReturn(product.Id, 30, DateTime.UtcNow.AddMinutes(-10));
InsertProductHistoryToDatabaseAndReturn(product.Id, 40, DateTime.UtcNow.AddDays(1));
var list = _productStorageContract.GetHistoryByProductId(Guid.NewGuid().ToString());
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
}
[Test]
public void Try_GetElementById_WhenHaveRecord_Test()
{
var product = InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString());
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.ProductName), 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.ProductName);
Assert.That(() => _productStorageContract.AddElement(product), Throws.TypeOf<ElementExistsException>());
}
[Test]
public void Try_UpdElement_Test()
{
var product = CreateModel(Guid.NewGuid().ToString(), "new name", "description");
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.ProductName);
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 Product InsertProductToDatabaseAndReturn(string id, string productName = "test", string productDescription = "description", ProductType productType = ProductType.Cake, double price = 1)
{
var product = new Product() { Id = id, ProductName = productName, ProductDescription = productDescription, ProductType = productType, Price = price };
CandyHouseDbContext.Products.Add(product);
CandyHouseDbContext.SaveChanges();
return product;
}
private ProductHistory InsertProductHistoryToDatabaseAndReturn(string productId, double price, DateTime changeDate)
{
var productHistory = new ProductHistory() { Id = Guid.NewGuid().ToString(), ProductId = productId, OldPrice = price, ChangeDate = changeDate };
CandyHouseDbContext.ProductHistories.Add(productHistory);
CandyHouseDbContext.SaveChanges();
return productHistory;
}
private static void AssertElement(ProductDataModel? actual, Product expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.Id, Is.EqualTo(expected.Id));
Assert.That(actual.ProductName, Is.EqualTo(expected.ProductName));
Assert.That(actual.ProductDescription, Is.EqualTo(expected.ProductDescription));
Assert.That(actual.ProductType, Is.EqualTo(expected.ProductType));
Assert.That(actual.Price, Is.EqualTo(expected.Price));
});
}
private static ProductDataModel CreateModel(string id, string productName = "test", string productDescription = "description", ProductType type = ProductType.Cake, double price = 1)
=> new(id, productName, productDescription, price, type);
private Product? GetProductFromDatabaseById(string id) => CandyHouseDbContext.Products.FirstOrDefault(x => x.Id == id);
private static void AssertElement(Product? actual, ProductDataModel expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.Id, Is.EqualTo(expected.Id));
Assert.That(actual.ProductName, Is.EqualTo(expected.ProductName));
Assert.That(actual.ProductDescription, Is.EqualTo(expected.ProductDescription));
Assert.That(actual.ProductType, Is.EqualTo(expected.ProductType));
Assert.That(actual.Price, Is.EqualTo(expected.Price));
});
}
}

View File

@@ -0,0 +1,153 @@
using CandyHouseContracts.DataModels;
using CandyHouseDatabase.Implementations;
using CandyHouseDatabase.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseTests.StoragesContractsTests;
[TestFixture]
internal class SalaryStorageContractTests : BaseStorageContractTest
{
private SalaryStorageContract _salaryStorageContract;
private Employee _employee;
[SetUp]
public void SetUp()
{
_salaryStorageContract = new SalaryStorageContract(CandyHouseDbContext);
_employee = InsertEmployeeToDatabaseAndReturn();
}
[TearDown]
public void TearDown()
{
CandyHouseDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Salaries\" CASCADE;");
CandyHouseDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Employees\" CASCADE;");
}
[Test]
public void Try_GetList_WhenHaveRecords_Test()
{
var salary = InsertSalaryToDatabaseAndReturn(_employee.Id, employeeSalary: 100);
InsertSalaryToDatabaseAndReturn(_employee.Id);
InsertSalaryToDatabaseAndReturn(_employee.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(_employee.Id, salaryDate: DateTime.UtcNow.AddDays(-2));
InsertSalaryToDatabaseAndReturn(_employee.Id, salaryDate: DateTime.UtcNow.AddDays(-1).AddMinutes(-5));
InsertSalaryToDatabaseAndReturn(_employee.Id, salaryDate: DateTime.UtcNow.AddDays(-1).AddMinutes(5));
InsertSalaryToDatabaseAndReturn(_employee.Id, salaryDate: DateTime.UtcNow.AddDays(1).AddMinutes(-5));
InsertSalaryToDatabaseAndReturn(_employee.Id, salaryDate: DateTime.UtcNow.AddDays(1).AddMinutes(5));
InsertSalaryToDatabaseAndReturn(_employee.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_ByEmployee_Test()
{
var employee = InsertEmployeeToDatabaseAndReturn("name 2");
InsertSalaryToDatabaseAndReturn(_employee.Id);
InsertSalaryToDatabaseAndReturn(_employee.Id);
InsertSalaryToDatabaseAndReturn(employee.Id);
var list = _salaryStorageContract.GetList(DateTime.UtcNow.AddDays(-1), DateTime.UtcNow.AddDays(1), _employee.Id);
Assert.That(list, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(list, Has.Count.EqualTo(2));
Assert.That(list.All(x => x.EmployeeId == _employee.Id));
});
}
[Test]
public void Try_GetList_ByEmployeeOnlyInDatePeriod_Test()
{
var employee = InsertEmployeeToDatabaseAndReturn("name 2");
InsertSalaryToDatabaseAndReturn(_employee.Id, salaryDate: DateTime.UtcNow.AddDays(-2));
InsertSalaryToDatabaseAndReturn(_employee.Id, salaryDate: DateTime.UtcNow.AddDays(-1).AddMinutes(5));
InsertSalaryToDatabaseAndReturn(employee.Id, salaryDate: DateTime.UtcNow.AddDays(-1).AddMinutes(5));
InsertSalaryToDatabaseAndReturn(_employee.Id, salaryDate: DateTime.UtcNow.AddDays(1).AddMinutes(-5));
InsertSalaryToDatabaseAndReturn(employee.Id, salaryDate: DateTime.UtcNow.AddDays(1).AddMinutes(-5));
InsertSalaryToDatabaseAndReturn(_employee.Id, salaryDate: DateTime.UtcNow.AddDays(-2));
var list = _salaryStorageContract.GetList(DateTime.UtcNow.AddDays(-1), DateTime.UtcNow.AddDays(1), _employee.Id);
Assert.That(list, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(list, Has.Count.EqualTo(2));
Assert.That(list.All(x => x.EmployeeId == _employee.Id));
});
}
[Test]
public void Try_AddElement_Test()
{
var salary = CreateModel(_employee.Id);
_salaryStorageContract.AddElement(salary);
AssertElement(GetSalaryFromDatabaseByEmployeeId(_employee.Id), salary);
}
private Employee InsertEmployeeToDatabaseAndReturn(string employeeFIO = "fio", string employeeEmail = "abc@mail.ru")
{
var employee = new Employee() { Id = Guid.NewGuid().ToString(), PostId = Guid.NewGuid().ToString(), FIO = employeeFIO, Email = employeeEmail, IsDeleted = false };
CandyHouseDbContext.Employees.Add(employee);
CandyHouseDbContext.SaveChanges();
return employee;
}
private Salary InsertSalaryToDatabaseAndReturn(string employeeId, double employeeSalary = 1, DateTime? salaryDate = null)
{
var salary = new Salary() { EmployeeId = employeeId, EmployeeSalary = employeeSalary, SalaryDate = salaryDate ?? DateTime.UtcNow };
CandyHouseDbContext.Salaries.Add(salary);
CandyHouseDbContext.SaveChanges();
return salary;
}
private static void AssertElement(SalaryDataModel? actual, Salary expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.EmployeeId, Is.EqualTo(expected.EmployeeId));
Assert.That(actual.Salary, Is.EqualTo(expected.EmployeeSalary));
});
}
private static SalaryDataModel CreateModel(string employeeId, double employeeSalary = 1, DateTime? salaryDate = null)
=> new(employeeId, salaryDate ?? DateTime.UtcNow, employeeSalary);
private Salary? GetSalaryFromDatabaseByEmployeeId(string id) => CandyHouseDbContext.Salaries.FirstOrDefault(x => x.EmployeeId == id);
private static void AssertElement(Salary? actual, SalaryDataModel expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.EmployeeId, Is.EqualTo(expected.EmployeeId));
Assert.That(actual.EmployeeSalary, Is.EqualTo(expected.Salary));
});
}
}

View File

@@ -0,0 +1,307 @@
using CandyHouseContracts.DataModels;
using CandyHouseContracts.Enums;
using CandyHouseContracts.Exceptions;
using CandyHouseDatabase.Implementations;
using CandyHouseDatabase.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static NUnit.Framework.Internal.OSPlatform;
using ProductType = CandyHouseContracts.Enums.ProductType;
namespace CandyHouseTests.StoragesContractsTests;
[TestFixture]
internal class SaleStorageContractTests : BaseStorageContractTest
{
private SaleStorageContract _saleStorageContract;
private Client _client;
private Employee _employee;
private Product _product;
[SetUp]
public void SetUp()
{
_saleStorageContract = new SaleStorageContract(CandyHouseDbContext);
_client = InsertClientToDatabaseAndReturn();
_employee = InsertEmployeeToDatabaseAndReturn();
_product = InsertProductToDatabaseAndReturn();
}
[TearDown]
public void TearDown()
{
CandyHouseDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Sales\" CASCADE;");
CandyHouseDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Clients\" CASCADE;");
CandyHouseDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Employees\" CASCADE;");
CandyHouseDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Products\" CASCADE;");
}
[Test]
public void Try_GetList_WhenHaveRecords_Test()
{
var sale = InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, products: [(_product.Id, 1)]);
InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, products: [(_product.Id, 5)]);
InsertSaleToDatabaseAndReturn(_employee.Id, null, products: [(_product.Id, 10)]);
var list = _saleStorageContract.GetList();
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(3));
AssertElement(list.First(x => x.Id == sale.Id), sale);
}
[Test]
public void Try_GetList_WhenNoRecords_Test()
{
var list = _saleStorageContract.GetList();
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.Empty);
}
[Test]
public void Try_GetList_ByPeriod_Test()
{
InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(-3), products: [(_product.Id, 1)]);
InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(3), products: [(_product.Id, 1)]);
InsertSaleToDatabaseAndReturn(_employee.Id, null, saleDate: DateTime.UtcNow.AddDays(1).AddMinutes(-3), products: [(_product.Id, 1)]);
InsertSaleToDatabaseAndReturn(_employee.Id, null, saleDate: DateTime.UtcNow.AddDays(1).AddMinutes(3), products: [(_product.Id, 1)]);
var list = _saleStorageContract.GetList(startDate: DateTime.UtcNow.AddDays(-1), endDate: DateTime.UtcNow.AddDays(1));
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(2));
}
[Test]
public void Try_GetList_ByEmployeeId_Test()
{
var employee = InsertEmployeeToDatabaseAndReturn("Other employee");
InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, products: [(_product.Id, 1)]);
InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, products: [(_product.Id, 1)]);
InsertSaleToDatabaseAndReturn(employee.Id, null, products: [(_product.Id, 1)]);
var list = _saleStorageContract.GetList(employeeId: _employee.Id);
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(2));
Assert.That(list.All(x => x.EmployeeId == _employee.Id));
}
[Test]
public void Try_GetList_ByClientId_Test()
{
var client = InsertClientToDatabaseAndReturn("Other fio", "+8-888-888-88-88");
InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, products: [(_product.Id, 1)]);
InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, products: [(_product.Id, 1)]);
InsertSaleToDatabaseAndReturn(_employee.Id, client.Id, products: [(_product.Id, 1)]);
InsertSaleToDatabaseAndReturn(_employee.Id, null, products: [(_product.Id, 1)]);
var list = _saleStorageContract.GetList(clientId: _client.Id);
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(2));
Assert.That(list.All(x => x.ClientId == _client.Id));
}
[Test]
public void Try_GetList_ByProductId_Test()
{
var product = InsertProductToDatabaseAndReturn("Other name");
InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, products: [(_product.Id, 5)]);
InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, products: [(_product.Id, 1), (product.Id, 4)]);
InsertSaleToDatabaseAndReturn(_employee.Id, null, products: [(product.Id, 1)]);
InsertSaleToDatabaseAndReturn(_employee.Id, null, products: [(product.Id, 1), (_product.Id, 1)]);
var list = _saleStorageContract.GetList(productId: _product.Id);
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(3));
Assert.That(list.All(x => x.Products.Any(y => y.ProductId == _product.Id)));
}
[Test]
public void Try_GetList_ByAllParameters_Test()
{
var employee = InsertEmployeeToDatabaseAndReturn("Other employee");
var client = InsertClientToDatabaseAndReturn("Other fio", "+8-888-888-88-88");
var product = InsertProductToDatabaseAndReturn("Other name");
InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(-3), products: [(_product.Id, 1)]);
InsertSaleToDatabaseAndReturn(employee.Id, null, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(3), products: [(_product.Id, 1)]);
InsertSaleToDatabaseAndReturn(employee.Id, _client.Id, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(3), products: [(_product.Id, 1)]);
InsertSaleToDatabaseAndReturn(employee.Id, _client.Id, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(3), products: [(product.Id, 1)]);
InsertSaleToDatabaseAndReturn(_employee.Id, client.Id, saleDate: DateTime.UtcNow.AddDays(1).AddMinutes(-3), products: [(_product.Id, 1)]);
InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, saleDate: DateTime.UtcNow.AddDays(1).AddMinutes(-3), products: [(product.Id, 1)]);
InsertSaleToDatabaseAndReturn(employee.Id, null, saleDate: DateTime.UtcNow.AddDays(1).AddMinutes(-3), products: [(_product.Id, 1)]);
var list = _saleStorageContract.GetList(startDate: DateTime.UtcNow.AddDays(-1), endDate: DateTime.UtcNow.AddDays(1), employeeId: _employee.Id, clientId: _client.Id, productId: product.Id);
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(1));
}
[Test]
public void Try_GetElementById_WhenHaveRecord_Test()
{
var sale = InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, products: [(_product.Id, 1)]);
AssertElement(_saleStorageContract.GetElementById(sale.Id), sale);
}
[Test]
public void Try_GetElementById_WhenNoRecord_Test()
{
InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, products: [(_product.Id, 1)]);
Assert.That(() => _saleStorageContract.GetElementById(Guid.NewGuid().ToString()), Is.Null);
}
[Test]
public void Try_GetElementById_WhenRecordHasCanceled_Test()
{
var sale = InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, products: [(_product.Id, 1)], isCancel: true);
AssertElement(_saleStorageContract.GetElementById(sale.Id), sale);
}
[Test]
public void Try_AddElement_Test()
{
var sale = CreateModel(Guid.NewGuid().ToString(), _employee.Id, _client.Id, 1, DiscountType.RegularCustomer, 1, false, [_product.Id]);
_saleStorageContract.AddElement(sale);
AssertElement(GetSaleFromDatabaseById(sale.Id), sale);
}
[Test]
public void Try_AddElement_WhenIsDeletedIsTrue_Test()
{
var sale = CreateModel(Guid.NewGuid().ToString(), _employee.Id, _client.Id, 1, DiscountType.RegularCustomer, 1, true, [_product.Id]);
Assert.That(() => _saleStorageContract.AddElement(sale), Throws.Nothing);
AssertElement(GetSaleFromDatabaseById(sale.Id), CreateModel(sale.Id, _employee.Id, _client.Id, 1, DiscountType.RegularCustomer, 1, false, [_product.Id]));
}
[Test]
public void Try_DelElement_Test()
{
var sale = InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, products: [(_product.Id, 1)], isCancel: false);
_saleStorageContract.DelElement(sale.Id);
var element = GetSaleFromDatabaseById(sale.Id);
Assert.Multiple(() =>
{
Assert.That(element, Is.Not.Null);
Assert.That(element!.IsCancel);
});
}
[Test]
public void Try_DelElement_WhenNoRecordWithThisId_Test()
{
Assert.That(() => _saleStorageContract.DelElement(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
}
[Test]
public void Try_DelElement_WhenRecordWasCanceled_Test()
{
var sale = InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, products: [(_product.Id, 1)], isCancel: true);
Assert.That(() => _saleStorageContract.DelElement(sale.Id), Throws.TypeOf<ElementDeletedException>());
}
private Client InsertClientToDatabaseAndReturn(string fio = "test", string phoneNumber = "+7-777-777-77-77")
{
var client = new Client() { Id = Guid.NewGuid().ToString(), FIO = fio, PhoneNumber = phoneNumber, DiscountSize = 10 };
CandyHouseDbContext.Clients.Add(client);
CandyHouseDbContext.SaveChanges();
return client;
}
private Employee InsertEmployeeToDatabaseAndReturn(string fio = "test", string employeeEmail = "abc@gmail.com")
{
var employee = new Employee() { Id = Guid.NewGuid().ToString(), FIO = fio, Email = employeeEmail, PostId = Guid.NewGuid().ToString() };
CandyHouseDbContext.Employees.Add(employee);
CandyHouseDbContext.SaveChanges();
return employee;
}
private Product InsertProductToDatabaseAndReturn(string productName = "test", ProductType productType = ProductType.Candy, double price = 1)
{
var product = new Product() { Id = Guid.NewGuid().ToString(), ProductName = productName, ProductType = productType, Price = price };
CandyHouseDbContext.Products.Add(product);
CandyHouseDbContext.SaveChanges();
return product;
}
private Sale InsertSaleToDatabaseAndReturn(string employeeId, string? clientId, DateTime? saleDate = null, double sum = 1, DiscountType discountType = DiscountType.OnSale, double discount = 0, bool isCancel = false, List<(string, int)>? products = null)
{
var sale = new Sale() { EmployeeId = employeeId, ClientId = clientId, SaleDate = saleDate ?? DateTime.UtcNow, Sum = sum, DiscountType = discountType, Discount = discount, IsCancel = isCancel, SaleProducts = [] };
if (products is not null)
{
foreach (var elem in products)
{
sale.SaleProducts.Add(new SaleProduct { ProductId = elem.Item1, SaleId = sale.Id, Count = elem.Item2 });
}
}
CandyHouseDbContext.Sales.Add(sale);
CandyHouseDbContext.SaveChanges();
return sale;
}
private static void AssertElement(SaleDataModel? actual, Sale expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.Id, Is.EqualTo(expected.Id));
Assert.That(actual.EmployeeId, Is.EqualTo(expected.EmployeeId));
Assert.That(actual.ClientId, Is.EqualTo(expected.ClientId));
Assert.That(actual.DiscountType, Is.EqualTo(expected.DiscountType));
Assert.That(actual.Discount, Is.EqualTo(expected.Discount));
Assert.That(actual.IsCancel, Is.EqualTo(expected.IsCancel));
});
if (expected.SaleProducts is not null)
{
Assert.That(actual.Products, Is.Not.Null);
Assert.That(actual.Products, Has.Count.EqualTo(expected.SaleProducts.Count));
for (int i = 0; i < actual.Products.Count; ++i)
{
Assert.Multiple(() =>
{
Assert.That(actual.Products[i].ProductId, Is.EqualTo(expected.SaleProducts[i].ProductId));
Assert.That(actual.Products[i].Count, Is.EqualTo(expected.SaleProducts[i].Count));
});
}
}
else
{
Assert.That(actual.Products, Is.Null);
}
}
private static SaleDataModel CreateModel(string id, string employeeId, string? clientId, double sum, DiscountType discountType, double discount, bool isCancel, List<string> productIds)
{
var products = productIds.Select(x => new SaleProductDataModel(id, x, 1)).ToList();
return new(id, employeeId, clientId, sum, discountType, discount, isCancel, products);
}
private Sale? GetSaleFromDatabaseById(string id) => CandyHouseDbContext.Sales.Include(x => x.SaleProducts).FirstOrDefault(x => x.Id == id);
private static void AssertElement(Sale? actual, SaleDataModel expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.Id, Is.EqualTo(expected.Id));
Assert.That(actual.EmployeeId, Is.EqualTo(expected.EmployeeId));
Assert.That(actual.ClientId, Is.EqualTo(expected.ClientId));
Assert.That(actual.DiscountType, Is.EqualTo(expected.DiscountType));
Assert.That(actual.Discount, Is.EqualTo(expected.Discount));
Assert.That(actual.IsCancel, Is.EqualTo(expected.IsCancel));
});
if (expected.Products is not null)
{
Assert.That(actual.SaleProducts, Is.Not.Null);
Assert.That(actual.SaleProducts, Has.Count.EqualTo(expected.Products.Count));
for (int i = 0; i < actual.SaleProducts.Count; ++i)
{
Assert.Multiple(() =>
{
Assert.That(actual.SaleProducts[i].ProductId, Is.EqualTo(expected.Products[i].ProductId));
Assert.That(actual.SaleProducts[i].Count, Is.EqualTo(expected.Products[i].Count));
});
}
}
else
{
Assert.That(actual.SaleProducts, Is.Null);
}
}
}

View File

@@ -0,0 +1,215 @@
using CandyHouseContracts.Exceptions;
using CandyHouseDatabase.Implementations;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CandyHouseDatabase.Models;
using CandyHouseContracts.Enums;
using Microsoft.EntityFrameworkCore;
using CandyHouseContracts.DataModels;
namespace CandyHouseTests.StoragesContractsTests;
[TestFixture]
internal class StorageStorageContractTests : BaseStorageContractTest
{
private StorageStorageContract _storageStorageContract;
private Product _product;
[SetUp]
public void SetUp()
{
_storageStorageContract = new StorageStorageContract(CandyHouseDbContext);
_product = InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), "name", ProductType.Candy);
}
[TearDown]
public void TearDown()
{
CandyHouseDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Agencies\" CASCADE;");
CandyHouseDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Products\" CASCADE;");
}
[Test]
public void Try_GetList_WhenHaveRecords_Test()
{
var storage = InsertStorageToDatabaseAndReturn(Guid.NewGuid().ToString(), ProductType.Candy, 5);
InsertStorageToDatabaseAndReturn(Guid.NewGuid().ToString(), ProductType.Candy, 5);
InsertStorageToDatabaseAndReturn(Guid.NewGuid().ToString(), ProductType.Candy, 5);
var list = _storageStorageContract.GetList();
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(3));
AssertElement(list.First(), storage);
}
[Test]
public void Try_GetList_WhenNoRecords_Test()
{
var list = _storageStorageContract.GetList();
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.Empty);
}
[Test]
public void Try_GetElementById_WhenHaveRecord_Test()
{
var storage = InsertStorageToDatabaseAndReturn(Guid.NewGuid().ToString(), ProductType.Candy, 5);
var result = _storageStorageContract.GetElementById(storage.Id);
AssertElement(result, storage);
}
[Test]
public void Try_GetElementById_WhenNoRecord_Test()
{
Assert.That(() => _storageStorageContract.GetElementById(Guid.NewGuid().ToString()), Is.Null);
}
[Test]
public void Try_AddElement_WhenValidData_Test()
{
var storage = CreateModel(Guid.NewGuid().ToString(), ProductType.Candy, 5, [_product.Id]);
_storageStorageContract.AddElement(storage);
var result = GetStorageFromDatabaseById(storage.Id);
AssertElement(result, storage);
}
[Test]
public void Try_AddElement_WhenHaveRecordWithSameId_Test()
{
var storage = CreateModel(Guid.NewGuid().ToString(), ProductType.Candy, 5, [_product.Id]);
InsertStorageToDatabaseAndReturn(storage.Id, ProductType.Candy, 5, [(_product.Id, 3)]);
Assert.That(() => _storageStorageContract.AddElement(storage), Throws.TypeOf<StorageException>());
}
[Test]
public void Try_AddElement_WhenNoHaveProduct_Test()
{
var storage = CreateModel(Guid.NewGuid().ToString(), ProductType.Candy, 0, [_product.Id]);
InsertStorageToDatabaseAndReturn(storage.Id, ProductType.Candy, 5, [(_product.Id, 3)]);
Assert.That(() => _storageStorageContract.AddElement(storage), Throws.TypeOf<StorageException>());
}
[Test]
public void Try_UpdElement_WhenValidData_Test()
{
var storage = CreateModel(Guid.NewGuid().ToString(), ProductType.Candy, 5, [_product.Id]);
InsertStorageToDatabaseAndReturn(storage.Id, ProductType.Chocolate, 10, null);
_storageStorageContract.UpdElement(storage);
var result = GetStorageFromDatabaseById(storage.Id);
AssertElement(result, storage);
}
[Test]
public void Try_UpdElement_WhenNoRecordWithThisId_Test()
{
var storage = CreateModel(Guid.NewGuid().ToString(), ProductType.Candy, 5, [_product.Id]);
Assert.That(() => _storageStorageContract.UpdElement(storage), Throws.TypeOf<ElementNotFoundException>());
}
[Test]
public void Try_DelElement_WhenRecordExists_Test()
{
var storage = InsertStorageToDatabaseAndReturn(Guid.NewGuid().ToString(), ProductType.Candy, 5);
_storageStorageContract.DelElement(storage.Id);
var result = GetStorageFromDatabaseById(storage.Id);
Assert.That(result, Is.Null);
}
[Test]
public void Try_DelElement_WhenRecordDoesNotExist_ThrowsElementNotFoundException()
{
Assert.That(() => _storageStorageContract.DelElement(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
}
private Product InsertProductToDatabaseAndReturn(string id, string name, ProductType type)
{
var product = new Product { Id = id, ProductName = name, ProductType = type };
CandyHouseDbContext.Products.Add(product);
CandyHouseDbContext.SaveChanges();
return product;
}
private Storage InsertStorageToDatabaseAndReturn(string id, ProductType type, int count, List<(string, int)>? products = null)
{
var storage = new Storage { Id = id, Type = type, Count = count, Products = [] };
if (products is not null)
{
foreach (var elem in products)
{
storage.Products.Add(new ProductStorage { StorageId = storage.Id, ProductId = elem.Item1, Count = elem.Item2 });
}
}
CandyHouseDbContext.Agencies.Add(storage);
CandyHouseDbContext.SaveChanges();
return storage;
}
private static void AssertElement(StorageDataModel? actual, Storage expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.Id, Is.EqualTo(expected.Id));
Assert.That(actual.Type, Is.EqualTo(expected.Type));
Assert.That(actual.Count, Is.EqualTo(expected.Count));
});
if (expected.Products is not null)
{
Assert.That(actual.Products, Is.Not.Null);
Assert.That(actual.Products, Has.Count.EqualTo(expected.Products.Count));
for (int i = 0; i < actual.Products.Count; ++i)
{
Assert.Multiple(() =>
{
Assert.That(actual.Products[i].ProductId, Is.EqualTo(expected.Products[i].ProductId));
Assert.That(actual.Products[i].Count, Is.EqualTo(expected.Products[i].Count));
});
}
}
else
{
Assert.That(actual.Products, Is.Null);
}
}
private static void AssertElement(Storage? actual, StorageDataModel expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.Id, Is.EqualTo(expected.Id));
Assert.That(actual.Type, Is.EqualTo(expected.Type));
Assert.That(actual.Count, Is.EqualTo(expected.Count));
});
if (expected.Products is not null)
{
Assert.That(actual.Products, Is.Not.Null);
Assert.That(actual.Products, Has.Count.EqualTo(expected.Products.Count));
for (int i = 0; i < actual.Products.Count; ++i)
{
Assert.Multiple(() =>
{
Assert.That(actual.Products[i].ProductId, Is.EqualTo(expected.Products[i].ProductId));
Assert.That(actual.Products[i].Count, Is.EqualTo(expected.Products[i].Count));
});
}
}
else
{
Assert.That(actual.Products, Is.Null);
}
}
private static StorageDataModel CreateModel(string id, ProductType type, int count, List<string> productsIds)
{
var products = productsIds.Select(x => new ProductStorageDataModel(id, x, 1)).ToList();
return new(id, type, count, products);
}
private Storage? GetStorageFromDatabaseById(string id)
{
return CandyHouseDbContext.Agencies.FirstOrDefault(x => x.Id == id);
}
}

View File

@@ -0,0 +1,191 @@
using CandyHouseContracts.DataModels;
using CandyHouseContracts.Enums;
using CandyHouseContracts.Exceptions;
using CandyHouseDatabase.Implementations;
using CandyHouseDatabase.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseTests.StoragesContractsTests;
[TestFixture]
internal class SuppliesStorageContractTests : BaseStorageContractTest
{
private SuppliesStorageContract _suppliesStorageContract;
private Product _product;
[SetUp]
public void SetUp()
{
_suppliesStorageContract = new SuppliesStorageContract(CandyHouseDbContext);
_product = InsertProductToDatabaseAndReturn();
}
[TearDown]
public void TearDown()
{
CandyHouseDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Supplieses\" CASCADE;");
CandyHouseDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Products\" CASCADE;");
}
[Test]
public void Try_GetList_WhenHaveRecords_Test()
{
var supply = InsertSupplyToDatabaseAndReturn(Guid.NewGuid().ToString(), ProductType.Chocolate, 5);
InsertSupplyToDatabaseAndReturn(Guid.NewGuid().ToString(), ProductType.Chocolate, 5);
InsertSupplyToDatabaseAndReturn(Guid.NewGuid().ToString(), ProductType.Chocolate, 5);
var list = _suppliesStorageContract.GetList();
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(3));
AssertElement(list.First(), supply);
}
[Test]
public void Try_GetList_WhenNoRecords_Test()
{
var list = _suppliesStorageContract.GetList();
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.Empty);
}
[Test]
public void Try_GetElementById_WhenHaveRecord_Test()
{
var supply = InsertSupplyToDatabaseAndReturn(Guid.NewGuid().ToString(), ProductType.Chocolate, 5);
AssertElement(_suppliesStorageContract.GetElementById(supply.Id), supply);
}
[Test]
public void Try_GetElementById_WhenNoRecord_Test()
{
Assert.That(() => _suppliesStorageContract.GetElementById(Guid.NewGuid().ToString()), Is.Null);
}
[Test]
public void Try_AddElement_Test()
{
var supply = CreateModel(Guid.NewGuid().ToString(), ProductType.Chocolate, 5, [_product.Id]);
_suppliesStorageContract.AddElement(supply);
AssertElement(GetSupplyFromDatabaseById(supply.Id), supply);
}
[Test]
public void Try_AddElement_WhenHaveRecordWithSameId_Test()
{
var supply = CreateModel(Guid.NewGuid().ToString(), ProductType.Chocolate, 5, [_product.Id]);
InsertSupplyToDatabaseAndReturn(supply.Id, ProductType.Chocolate, 5, [(_product.Id, 3)]);
Assert.That(() => _suppliesStorageContract.AddElement(supply), Throws.TypeOf<StorageException>());
}
[Test]
public void Try_UpdElement_Test()
{
var supply = CreateModel(Guid.NewGuid().ToString(), ProductType.Chocolate, 5, [_product.Id]);
InsertSupplyToDatabaseAndReturn(supply.Id, ProductType.Chocolate, 5, null);
_suppliesStorageContract.UpdElement(supply);
AssertElement(GetSupplyFromDatabaseById(supply.Id), supply);
}
[Test]
public void Try_UpdElement_WhenNoRecordWithThisId_Test()
{
Assert.That(() => _suppliesStorageContract.UpdElement(CreateModel(Guid.NewGuid().ToString(), ProductType.Chocolate, 5, [_product.Id])), Throws.TypeOf<ElementNotFoundException>());
}
private Product InsertProductToDatabaseAndReturn()
{
var product = new Product { Id = Guid.NewGuid().ToString(), ProductName = "Test Product", ProductType = ProductType.Chocolate };
CandyHouseDbContext.Products.Add(product);
CandyHouseDbContext.SaveChanges();
return product;
}
private Supplies InsertSupplyToDatabaseAndReturn(string id, ProductType type, int count, List<(string, int)>? products = null)
{
var supply = new Supplies { Id = id, Type = type, OrderDate = DateTime.UtcNow, Count = count, Products = [] };
if (products is not null)
{
foreach (var elem in products)
{
supply.Products.Add(new ProductSupplies { SuppliesId = supply.Id, ProductId = elem.Item1, Count = elem.Item2 });
}
}
CandyHouseDbContext.Supplieses.Add(supply);
CandyHouseDbContext.SaveChanges();
return supply;
}
private static void AssertElement(SuppliesDataModel? actual, Supplies expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.Id, Is.EqualTo(expected.Id));
Assert.That(actual.Type, Is.EqualTo(expected.Type));
Assert.That(actual.OrderDate, Is.EqualTo(expected.OrderDate));
Assert.That(actual.Count, Is.EqualTo(expected.Count));
});
if (expected.Products is not null)
{
Assert.That(actual.Products, Is.Not.Null);
Assert.That(actual.Products, Has.Count.EqualTo(expected.Products.Count));
for (int i = 0; i < actual.Products.Count; ++i)
{
Assert.Multiple(() =>
{
Assert.That(actual.Products[i].ProductId, Is.EqualTo(expected.Products[i].ProductId));
Assert.That(actual.Products[i].Count, Is.EqualTo(expected.Products[i].Count));
});
}
}
else
{
Assert.That(actual.Products, Is.Null);
}
}
private static void AssertElement(Supplies? actual, SuppliesDataModel expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.Id, Is.EqualTo(expected.Id));
Assert.That(actual.Type, Is.EqualTo(expected.Type));
Assert.That(actual.OrderDate, Is.EqualTo(expected.OrderDate));
Assert.That(actual.Count, Is.EqualTo(expected.Count));
});
if (expected.Products is not null)
{
Assert.That(actual.Products, Is.Not.Null);
Assert.That(actual.Products, Has.Count.EqualTo(expected.Products.Count));
for (int i = 0; i < actual.Products.Count; ++i)
{
Assert.Multiple(() =>
{
Assert.That(actual.Products[i].ProductId, Is.EqualTo(expected.Products[i].ProductId));
Assert.That(actual.Products[i].Count, Is.EqualTo(expected.Products[i].Count));
});
}
}
else
{
Assert.That(actual.Products, Is.Null);
}
}
private static SuppliesDataModel CreateModel(string id, ProductType type, int count, List<string> productsIds)
{
var products = productsIds.Select(x => new ProductSuppliesDataModel(id, x, 1)).ToList();
return new(id, type, DateTime.UtcNow, count, products);
}
private Supplies? GetSupplyFromDatabaseById(string id)
{
return CandyHouseDbContext.Supplieses.FirstOrDefault(x => x.Id == id);
}
}