5 Commits

Author SHA1 Message Date
d2b57d3c85 Добавил настройки маппинга через атрибуты 2025-03-17 17:09:53 +04:00
448501ef70 Тесты 2025-03-13 14:22:15 +04:00
885d0f773f Контракты 2025-03-12 21:36:54 +04:00
d7edc8bd2b DbContext 2025-03-12 19:27:42 +04:00
c65c66fa6a Проект и модели 2025-03-12 14:21:46 +04:00
30 changed files with 2629 additions and 5 deletions

View File

@@ -5,9 +5,9 @@ using SPiluSZharuContracts.Infrastructure;
namespace SPiluSZharuContracts.DataModels;
public class PostDataModel(string id, string postName, PostType postType, double salary, bool isActual, DateTime changeDate) : IValidation
public class PostDataModel(string postId, string postName, PostType postType, double salary, bool isActual, DateTime changeDate) : IValidation
{
public string Id { get; private set; } = id;
public string Id { get; private set; } = postId;
public string PostName { get; private set; } = postName;

View File

@@ -4,7 +4,7 @@ using SPiluSZharuContracts.Infrastructure;
namespace SPiluSZharuContracts.DataModels;
public class SaleDataModel(string id, string workerId, string? restaurantId, double sum, bool isCancel, List<SaleProductDataModel> products) : IValidation
public class SaleDataModel(string id, string workerId, string? restaurantId, double sum, bool isCancel, List<SaleProductDataModel> saleProducts) : IValidation
{
public string Id { get; private set; } = id;
@@ -18,7 +18,7 @@ public class SaleDataModel(string id, string workerId, string? restaurantId, dou
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

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

View File

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

View File

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

View File

@@ -0,0 +1,155 @@
using AutoMapper;
using Microsoft.EntityFrameworkCore;
using Npgsql;
using SPiluSZharuContracts.DataModels;
using SPiluSZharuContracts.Exceptions;
using SPiluSZharuContracts.StorageContracts;
using SPiluSZharuDatabase.Models;
namespace SPiluSZharuDatabase.Implementations;
internal class RestaurantStorageContract : IRestaurantStorageContract
{
private readonly SPiluSZharuDbContext _dbContext;
private readonly Mapper _mapper;
public RestaurantStorageContract(SPiluSZharuDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.AddMaps(typeof(SPiluSZharuDbContext).Assembly);
});
_mapper = new Mapper(config);
}
public List<RestaurantDataModel> GetList()
{
try
{
return [.. _dbContext.Restaurants.Select(x => _mapper.Map<RestaurantDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public RestaurantDataModel? GetElementById(string id)
{
try
{
return _mapper.Map<RestaurantDataModel>(GetRestaurantById(id));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public RestaurantDataModel? GetElementByName(string name)
{
try
{
return _mapper.Map<RestaurantDataModel>(_dbContext.Restaurants.FirstOrDefault(x => x.RestaurantName == name));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public RestaurantDataModel? GetElementByOldName(string name)
{
try
{
return _mapper.Map<RestaurantDataModel>(_dbContext.Restaurants.FirstOrDefault(x => x.PrevRestaurantName == name ||
x.PrevPrevRestaurantName == name));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void AddElement(RestaurantDataModel RestaurantDataModel)
{
try
{
_dbContext.Restaurants.Add(_mapper.Map<Restaurant>(RestaurantDataModel));
_dbContext.SaveChanges();
}
catch (InvalidOperationException ex) when (ex.TargetSite?.Name == "ThrowIdentityConflict")
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("Id", RestaurantDataModel.Id);
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Restaurants_RestaurantName" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("RestaurantName", RestaurantDataModel.RestaurantName);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void UpdElement(RestaurantDataModel RestaurantDataModel)
{
try
{
var element = GetRestaurantById(RestaurantDataModel.Id) ?? throw new ElementNotFoundException(RestaurantDataModel.Id);
if (element.RestaurantName != RestaurantDataModel.RestaurantName)
{
element.PrevPrevRestaurantName = element.PrevRestaurantName;
element.PrevRestaurantName = element.RestaurantName;
element.RestaurantName = RestaurantDataModel.RestaurantName;
}
_dbContext.Restaurants.Update(element);
_dbContext.SaveChanges();
}
catch (ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Restaurants_RestaurantName" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("RestaurantName", RestaurantDataModel.RestaurantName);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void DelElement(string id)
{
try
{
var element = GetRestaurantById(id) ?? throw new ElementNotFoundException(id);
_dbContext.Restaurants.Remove(element);
_dbContext.SaveChanges();
}
catch (ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
private Restaurant? GetRestaurantById(string id) => _dbContext.Restaurants.FirstOrDefault(x => x.Id == id);
}

View File

@@ -0,0 +1,57 @@
using AutoMapper;
using SPiluSZharuContracts.DataModels;
using SPiluSZharuContracts.Exceptions;
using SPiluSZharuContracts.StorageContracts;
using SPiluSZharuDatabase.Models;
namespace SPiluSZharuDatabase.Implementations;
internal class SalaryStorageContract : ISalaryStorageContract
{
private readonly SPiluSZharuDbContext _dbContext;
private readonly Mapper _mapper;
public SalaryStorageContract(SPiluSZharuDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Salary, SalaryDataModel>();
cfg.CreateMap<SalaryDataModel, Salary>()
.ForMember(dest => dest.WorkerSalary, opt => opt.MapFrom(src => src.Salary));
});
_mapper = new Mapper(config);
}
public List<SalaryDataModel> GetList(DateTime startDate, DateTime endDate, string? workerId = null)
{
try
{
var query = _dbContext.Salaries.Where(x => x.SalaryDate >= startDate && x.SalaryDate <= endDate);
if (workerId is not null)
{
query = query.Where(x => x.WorkerId == workerId);
}
return [.. query.Select(x => _mapper.Map<SalaryDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void AddElement(SalaryDataModel salaryDataModel)
{
try
{
_dbContext.Salaries.Add(_mapper.Map<Salary>(salaryDataModel));
_dbContext.SaveChanges();
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
}

View File

@@ -0,0 +1,112 @@
using AutoMapper;
using Microsoft.EntityFrameworkCore;
using SPiluSZharuContracts.DataModels;
using SPiluSZharuContracts.Exceptions;
using SPiluSZharuContracts.StorageContracts;
using SPiluSZharuDatabase.Models;
namespace SPiluSZharuDatabase.Implementations;
internal class SaleStorageContract : ISaleStorageContract
{
private readonly SPiluSZharuDbContext _dbContext;
private readonly Mapper _mapper;
public SaleStorageContract(SPiluSZharuDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<SaleProduct, SaleProductDataModel>();
cfg.CreateMap<SaleProductDataModel, SaleProduct>();
cfg.CreateMap<Sale, SaleDataModel>();
cfg.CreateMap<SaleDataModel, Sale>()
.ForMember(x => x.IsCancel, x => x.MapFrom(src => false))
.ForMember(x => x.SaleProducts, x => x.MapFrom(src => src.Products));
});
_mapper = new Mapper(config);
}
public List<SaleDataModel> GetList(DateTime? startDate = null, DateTime? endDate = null, string? workerId = null, string? restaurantId = null, string? productId = null)
{
try
{
var query = _dbContext.Sales.Include(x => x.SaleProducts).AsQueryable();
if (startDate is not null && endDate is not null)
{
query = query.Where(x => x.SaleDate >= startDate && x.SaleDate < endDate);
}
if (workerId is not null)
{
query = query.Where(x => x.WorkerId == workerId);
}
if (restaurantId is not null)
{
query = query.Where(x => x.RestaurantId == restaurantId);
}
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,153 @@
using AutoMapper;
using SPiluSZharuContracts.DataModels;
using SPiluSZharuContracts.Exceptions;
using SPiluSZharuContracts.StorageContracts;
using SPiluSZharuDatabase.Models;
namespace SPiluSZharuDatabase.Implementations;
internal class WorkerStorageContract : IWorkerStorageContract
{
private readonly SPiluSZharuDbContext _dbContext;
private readonly Mapper _mapper;
public WorkerStorageContract(SPiluSZharuDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.AddMaps(typeof(SPiluSZharuDbContext).Assembly);
});
_mapper = new Mapper(config);
}
public List<WorkerDataModel> GetList(bool onlyActive = true, string? postId = null, DateTime? fromBirthDate = null, DateTime? toBirthDate = null, DateTime? fromEmploymentDate = null, DateTime? toEmploymentDate = null)
{
try
{
var query = _dbContext.Workers.AsQueryable();
if (onlyActive)
{
query = query.Where(x => !x.IsDeleted);
}
if (postId is not null)
{
query = query.Where(x => x.PostId == postId);
}
if (fromBirthDate is not null && toBirthDate is not null)
{
query = query.Where(x => x.BirthDate >= fromBirthDate && x.BirthDate <= toBirthDate);
}
if (fromEmploymentDate is not null && toEmploymentDate is not null)
{
query = query.Where(x => x.EmploymentDate >= fromEmploymentDate && x.EmploymentDate <= toEmploymentDate);
}
return [.. query.Select(x => _mapper.Map<WorkerDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public WorkerDataModel? GetElementById(string id)
{
try
{
return _mapper.Map<WorkerDataModel>(GetWorkerById(id));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public WorkerDataModel? GetElementByFIO(string fio)
{
try
{
return _mapper.Map<WorkerDataModel>(_dbContext.Workers.FirstOrDefault(x => x.FIO == fio));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public WorkerDataModel? GetElementByPhoneNumber(string phoneNumber)
{
try
{
return _mapper.Map<WorkerDataModel>(_dbContext.Workers.FirstOrDefault(x => x.PhoneNumber == phoneNumber));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void AddElement(WorkerDataModel workerDataModel)
{
try
{
_dbContext.Workers.Add(_mapper.Map<Worker>(workerDataModel));
_dbContext.SaveChanges();
}
catch (InvalidOperationException ex) when (ex.TargetSite?.Name == "ThrowIdentityConflict")
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("Id", workerDataModel.Id);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void UpdElement(WorkerDataModel workerDataModel)
{
try
{
var element = GetWorkerById(workerDataModel.Id) ?? throw new ElementNotFoundException(workerDataModel.Id);
_dbContext.Workers.Update(_mapper.Map(workerDataModel, element));
_dbContext.SaveChanges();
}
catch (ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void DelElement(string id)
{
try
{
var element = GetWorkerById(id) ?? throw new ElementNotFoundException(id);
element.IsDeleted = true;
_dbContext.SaveChanges();
}
catch (ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
private Worker? GetWorkerById(string id) => _dbContext.Workers.FirstOrDefault(x => x.Id == id && !x.IsDeleted);
}

View File

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

View File

@@ -0,0 +1,23 @@
using SPiluSZharuContracts.Enums;
using System.ComponentModel.DataAnnotations.Schema;
namespace SPiluSZharuDatabase.Models;
internal class Product
{
public required string Id { get; set; }
public required string ProductName { get; set; }
public ProductType ProductType { get; set; }
public double Price { get; set; }
public bool IsDeleted { get; set; }
[ForeignKey("ProductId")]
public List<ProductHistory>? ProductHistories { get; set; }
[ForeignKey("ProductId")]
public List<SaleProduct>? SaleProducts { get; set; }
}

View File

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

View File

@@ -0,0 +1,16 @@
using AutoMapper;
using SPiluSZharuContracts.DataModels;
namespace SPiluSZharuDatabase.Models;
[AutoMap(typeof(RestaurantDataModel), ReverseMap = true)]
internal class Restaurant
{
public required string Id { get; set; }
public required string RestaurantName { get; set; }
public string? PrevRestaurantName { get; set; }
public string? PrevPrevRestaurantName { get; set; }
}

View File

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

View File

@@ -0,0 +1,27 @@
using System.ComponentModel.DataAnnotations.Schema;
using System;
using SPiluSZharuContracts.DataModels;
namespace SPiluSZharuDatabase.Models;
internal class Sale
{
public string Id { get; set; } = Guid.NewGuid().ToString();
public required string WorkerId { get; set; }
public string? RestaurantId { get; set; }
public DateTime SaleDate { get; set; }
public double Sum { get; set; }
public bool IsCancel { get; set; }
public Worker? Worker { get; set; }
public Restaurant? Restaurant { get; set; }
[ForeignKey("SaleId")]
public List<SaleProduct>? SaleProducts { get; set; }
}

View File

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

View File

@@ -0,0 +1,28 @@
using AutoMapper;
using SPiluSZharuContracts.DataModels;
using System.ComponentModel.DataAnnotations.Schema;
namespace SPiluSZharuDatabase.Models;
[AutoMap(typeof(WorkerDataModel), ReverseMap = true)]
internal class Worker
{
public required string Id { get; set; }
public required string FIO { get; set; }
public required string PostId { get; set; }
public required string PhoneNumber { get; set; }
public DateTime BirthDate { get; set; }
public DateTime EmploymentDate { get; set; }
public bool IsDeleted { get; set; }
[ForeignKey("WorkerId")]
public List<Salary>? Salaries { get; set; }
[ForeignKey("WorkerId")]
public List<Sale>? Sales { get; set; }
}

View File

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

View File

@@ -0,0 +1,59 @@
using SPiluSZharuContratcs.Infrastructure;
using Microsoft.EntityFrameworkCore;
using SPiluSZharuDatabase.Models;
using System;
namespace SPiluSZharuDatabase;
internal class SPiluSZharuDbContext(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<Restaurant>().HasIndex(x => x.RestaurantName).IsUnique();
modelBuilder.Entity<Post>()
.HasIndex(e => new { e.PostName, e.IsActual })
.IsUnique()
.HasFilter($"\"{nameof(Post.IsActual)}\" = TRUE");
modelBuilder.Entity<Post>()
.HasIndex(e => new { e.PostId, e.IsActual })
.IsUnique()
.HasFilter($"\"{nameof(Post.IsActual)}\" = TRUE");
modelBuilder.Entity<Product>()
.HasIndex(x => new { x.ProductName, x.IsDeleted })
.IsUnique()
.HasFilter($"\"{nameof(Product.IsDeleted)}\" = FALSE");
modelBuilder.Entity<SaleProduct>().HasKey(x => new { x.SaleId, x.ProductId });
modelBuilder.Entity<Worker>().HasIndex(x => x.PhoneNumber).IsUnique();
}
public DbSet<Restaurant> Restaurants { get; set; }
public DbSet<Post> Posts { get; set; }
public DbSet<Product> Products { get; set; }
public DbSet<ProductHistory> ProductHistories { get; set; }
public DbSet<Salary> Salaries { get; set; }
public DbSet<Sale> Sales { get; set; }
public DbSet<SaleProduct> SaleProducts { get; set; }
public DbSet<Worker> Workers { get; set; }
}

View File

@@ -9,6 +9,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SPiluSZharuTests", "SPiluSZ
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SPiluSZharuBuisnessLogic", "SPiluSZharuBuisnessLogic\SPiluSZharuBuisnessLogic.csproj", "{B6AB6CA3-FE95-45BF-8E81-73FFA7EEF523}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SPiluSZharuDatabase", "SPiluSZharuDatabase\SPiluSZharuDatabase.csproj", "{BCE267DF-2D6F-44B2-AC99-0070B7C5A4BC}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@@ -27,6 +29,10 @@ Global
{B6AB6CA3-FE95-45BF-8E81-73FFA7EEF523}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B6AB6CA3-FE95-45BF-8E81-73FFA7EEF523}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B6AB6CA3-FE95-45BF-8E81-73FFA7EEF523}.Release|Any CPU.Build.0 = Release|Any CPU
{BCE267DF-2D6F-44B2-AC99-0070B7C5A4BC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{BCE267DF-2D6F-44B2-AC99-0070B7C5A4BC}.Debug|Any CPU.Build.0 = Debug|Any CPU
{BCE267DF-2D6F-44B2-AC99-0070B7C5A4BC}.Release|Any CPU.ActiveCfg = Release|Any CPU
{BCE267DF-2D6F-44B2-AC99-0070B7C5A4BC}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE

View File

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

View File

@@ -13,7 +13,7 @@
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.Extensions.Logging" Version="9.0.2" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="9.0.3" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.13.0" />
<PackageReference Include="Moq" Version="4.20.72" />
<PackageReference Include="NUnit" Version="4.3.2" />
@@ -27,6 +27,7 @@
<ItemGroup>
<ProjectReference Include="..\SPiluSZharuBuisnessLogic\SPiluSZharuBuisnessLogic.csproj" />
<ProjectReference Include="..\SPiluSZharuContracts\SPiluSZharuContracts.csproj" />
<ProjectReference Include="..\SPiluSZharuDatabase\SPiluSZharuDatabase.csproj" />
</ItemGroup>
<ItemGroup>

View File

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

View File

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

View File

@@ -0,0 +1,306 @@
using Microsoft.EntityFrameworkCore;
using SPiluSZharuContracts.DataModels;
using SPiluSZharuContracts.Enums;
using SPiluSZharuContracts.Exceptions;
using SPiluSZharuDatabase.Implementations;
using SPiluSZharuDatabase.Models;
namespace SPiluSZharuTests.StoragesContracts;
[TestFixture]
internal class ProductStorageContractTests : BaseStorageContractTest
{
private ProductStorageContract _productStorageContract;
[SetUp]
public void SetUp()
{
_productStorageContract = new ProductStorageContract(SPiluSZharuDbContext);
}
[TearDown]
public void TearDown()
{
SPiluSZharuDbContext.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_GetList_OnlyActual_Test()
{
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 1", isDeleted: true);
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 2", isDeleted: false);
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 3", isDeleted: false);
var list = _productStorageContract.GetList(onlyActive: true);
Assert.That(list, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(list, Has.Count.EqualTo(2));
Assert.That(!list.Any(x => x.IsDeleted));
});
}
[Test]
public void Try_GetList_IncludeNoActual_Test()
{
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 1", isDeleted: true);
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 2", isDeleted: true);
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 3", isDeleted: false);
var list = _productStorageContract.GetList(onlyActive: false);
Assert.That(list, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(list, Has.Count.EqualTo(3));
Assert.That(list.Count(x => x.IsDeleted), Is.EqualTo(2));
Assert.That(list.Count(x => !x.IsDeleted), Is.EqualTo(1));
});
}
[Test]
public void Try_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_GetElementById_WhenRecordHasDeleted_Test()
{
var product = InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), isDeleted: true);
Assert.That(() => _productStorageContract.GetElementById(product.Id), 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_GetElementByName_WhenRecordHasDeleted_Test()
{
var product = InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), isDeleted: true);
Assert.That(() => _productStorageContract.GetElementById(product.ProductName), Is.Null);
}
[Test]
public void Try_AddElement_Test()
{
var product = CreateModel(Guid.NewGuid().ToString(), isDeleted: false);
_productStorageContract.AddElement(product);
AssertElement(GetProductFromDatabaseById(product.Id), product);
}
[Test]
public void Try_AddElement_WhenIsDeletedIsTrue_Test()
{
var product = CreateModel(Guid.NewGuid().ToString(), isDeleted: true);
Assert.That(() => _productStorageContract.AddElement(product), Throws.Nothing);
AssertElement(GetProductFromDatabaseById(product.Id), CreateModel(product.Id, isDeleted: false));
}
[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", isDeleted: false);
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), productName: product.ProductName, isDeleted: false);
Assert.That(() => _productStorageContract.AddElement(product), Throws.TypeOf<ElementExistsException>());
}
[Test]
public void Try_AddElement_WhenHaveRecordWithSameNameButOneWasDeleted_Test()
{
var product = CreateModel(Guid.NewGuid().ToString(), "name unique", isDeleted: false);
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), productName: product.ProductName, isDeleted: true);
Assert.That(() => _productStorageContract.AddElement(product), Throws.Nothing);
}
[Test]
public void Try_UpdElement_Test()
{
var product = CreateModel(Guid.NewGuid().ToString(), isDeleted: false);
InsertProductToDatabaseAndReturn(product.Id, isDeleted: false);
_productStorageContract.UpdElement(product);
AssertElement(GetProductFromDatabaseById(product.Id), product);
}
[Test]
public void Try_UpdElement_WhenIsDeletedIsTrue_Test()
{
var product = CreateModel(Guid.NewGuid().ToString(), isDeleted: true);
InsertProductToDatabaseAndReturn(product.Id, isDeleted: false);
_productStorageContract.UpdElement(product);
AssertElement(GetProductFromDatabaseById(product.Id), CreateModel(product.Id, isDeleted: false));
}
[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", isDeleted: false);
InsertProductToDatabaseAndReturn(product.Id, productName: "name");
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), productName: product.ProductName);
Assert.That(() => _productStorageContract.UpdElement(product), Throws.TypeOf<ElementExistsException>());
}
[Test]
public void Try_UpdElement_WhenHaveRecordWithSameNameButOneWasDeleted_Test()
{
var product = CreateModel(Guid.NewGuid().ToString(), "name unique", isDeleted: false);
InsertProductToDatabaseAndReturn(product.Id, productName: "name");
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), productName: product.ProductName, isDeleted: true);
Assert.That(() => _productStorageContract.UpdElement(product), Throws.Nothing);
}
[Test]
public void Try_UpdElement_WhenRecordWasDeleted_Test()
{
var product = CreateModel(Guid.NewGuid().ToString());
InsertProductToDatabaseAndReturn(product.Id, isDeleted: true);
Assert.That(() => _productStorageContract.UpdElement(product), Throws.TypeOf<ElementNotFoundException>());
}
[Test]
public void Try_DelElement_Test()
{
var product = InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), isDeleted: false);
_productStorageContract.DelElement(product.Id);
var element = GetProductFromDatabaseById(product.Id);
Assert.Multiple(() =>
{
Assert.That(element, Is.Not.Null);
Assert.That(element!.IsDeleted);
});
}
[Test]
public void Try_DelElement_WhenNoRecordWithThisId_Test()
{
Assert.That(() => _productStorageContract.DelElement(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
}
[Test]
public void Try_DelElement_WhenRecordWasDeleted_Test()
{
var product = InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), isDeleted: true);
Assert.That(() => _productStorageContract.DelElement(product.Id), Throws.TypeOf<ElementNotFoundException>());
}
private Product InsertProductToDatabaseAndReturn(string id, string productName = "test", ProductType productType = ProductType.Burgers, double price = 1, bool isDeleted = false)
{
var product = new Product() { Id = id, ProductName = productName, ProductType = productType, Price = price, IsDeleted = isDeleted };
SPiluSZharuDbContext.Products.Add(product);
SPiluSZharuDbContext.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 };
SPiluSZharuDbContext.ProductHistories.Add(productHistory);
SPiluSZharuDbContext.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.ProductType, Is.EqualTo(expected.ProductType));
Assert.That(actual.Price, Is.EqualTo(expected.Price));
Assert.That(actual.IsDeleted, Is.EqualTo(expected.IsDeleted));
});
}
private static ProductDataModel CreateModel(string id, string productName = "test", ProductType productType = ProductType.Burgers, double price = 1, bool isDeleted = false)
=> new(id, productName, productType, price, isDeleted);
private Product? GetProductFromDatabaseById(string id) => SPiluSZharuDbContext.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.ProductType, Is.EqualTo(expected.ProductType));
Assert.That(actual.Price, Is.EqualTo(expected.Price));
Assert.That(actual.IsDeleted, Is.EqualTo(expected.IsDeleted));
});
}
}

View File

@@ -0,0 +1,188 @@
using Microsoft.EntityFrameworkCore;
using SPiluSZharuContracts.DataModels;
using SPiluSZharuContracts.Exceptions;
using SPiluSZharuDatabase.Implementations;
using SPiluSZharuDatabase.Models;
namespace SPiluSZharuTests.StoragesContracts;
[TestFixture]
internal class RestaurantStorageContractTest : BaseStorageContractTest
{
private RestaurantStorageContract _restaurantStorageContract;
[SetUp]
public void SetUp()
{
_restaurantStorageContract = new RestaurantStorageContract(SPiluSZharuDbContext);
}
[TearDown]
public void TearDown()
{
SPiluSZharuDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Restaurants\" CASCADE;");
}
[Test]
public void Try_GetList_WhenHaveRecords_Test()
{
var restaurant = InsertRestaurantToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 1");
InsertRestaurantToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 2");
InsertRestaurantToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 3");
var list = _restaurantStorageContract.GetList();
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(3));
AssertElement(list.First(x => x.Id == restaurant.Id), restaurant);
}
[Test]
public void Try_GetList_WhenNoRecords_Test()
{
var list = _restaurantStorageContract.GetList();
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.Empty);
}
[Test]
public void Try_GetElementById_WhenHaveRecord_Test()
{
var restaurant = InsertRestaurantToDatabaseAndReturn(Guid.NewGuid().ToString());
AssertElement(_restaurantStorageContract.GetElementById(restaurant.Id), restaurant);
}
[Test]
public void Try_GetElementById_WhenNoRecord_Test()
{
InsertRestaurantToDatabaseAndReturn(Guid.NewGuid().ToString());
Assert.That(() => _restaurantStorageContract.GetElementById(Guid.NewGuid().ToString()), Is.Null);
}
[Test]
public void Try_GetElementByName_WhenHaveRecord_Test()
{
var restaurant = InsertRestaurantToDatabaseAndReturn(Guid.NewGuid().ToString());
AssertElement(_restaurantStorageContract.GetElementByName(restaurant.RestaurantName), restaurant);
}
[Test]
public void Try_GetElementByName_WhenNoRecord_Test()
{
InsertRestaurantToDatabaseAndReturn(Guid.NewGuid().ToString());
Assert.That(() => _restaurantStorageContract.GetElementByName("name"), Is.Null);
}
[Test]
public void Try_GetElementByOldName_WhenHaveRecord_Test()
{
var restaurant = InsertRestaurantToDatabaseAndReturn(Guid.NewGuid().ToString());
AssertElement(_restaurantStorageContract.GetElementByOldName(restaurant.PrevRestaurantName!), restaurant);
AssertElement(_restaurantStorageContract.GetElementByOldName(restaurant.PrevPrevRestaurantName!), restaurant);
}
[Test]
public void Try_GetElementByOldName_WhenNoRecord_Test()
{
InsertRestaurantToDatabaseAndReturn(Guid.NewGuid().ToString());
Assert.That(() => _restaurantStorageContract.GetElementByOldName("name"), Is.Null);
}
[Test]
public void Try_AddElement_Test()
{
var restaurant = CreateModel(Guid.NewGuid().ToString());
_restaurantStorageContract.AddElement(restaurant);
AssertElement(GetRestaurantFromDatabase(restaurant.Id), restaurant);
}
[Test]
public void Try_AddElement_WhenHaveRecordWithSameId_Test()
{
var restaurant = CreateModel(Guid.NewGuid().ToString(), "name unique");
InsertRestaurantToDatabaseAndReturn(restaurant.Id);
Assert.That(() => _restaurantStorageContract.AddElement(restaurant), Throws.TypeOf<ElementExistsException>());
}
[Test]
public void Try_AddElement_WhenHaveRecordWithSameRestaurantName_Test()
{
var restaurant = CreateModel(Guid.NewGuid().ToString(), "name unique");
InsertRestaurantToDatabaseAndReturn(Guid.NewGuid().ToString(), restaurantName: restaurant.RestaurantName);
Assert.That(() => _restaurantStorageContract.AddElement(restaurant), Throws.TypeOf<ElementExistsException>());
}
[Test]
public void Try_UpdElement_Test()
{
var restaurant = CreateModel(Guid.NewGuid().ToString(), "name new", "test", "prev");
InsertRestaurantToDatabaseAndReturn(restaurant.Id, restaurantName: restaurant.PrevRestaurantName!, prevRestaurantName: restaurant.PrevPrevRestaurantName!);
_restaurantStorageContract.UpdElement(CreateModel(restaurant.Id, "name new", "some name", "some name"));
AssertElement(GetRestaurantFromDatabase(restaurant.Id), restaurant);
}
[Test]
public void Try_UpdElement_WhenNoChangeRestaurantName_Test()
{
var restaurant = CreateModel(Guid.NewGuid().ToString(), "name new", "test", "prev");
InsertRestaurantToDatabaseAndReturn(restaurant.Id, restaurantName: restaurant.RestaurantName!, prevRestaurantName: restaurant.PrevRestaurantName!, prevPrevRestaurantName: restaurant.PrevPrevRestaurantName!);
_restaurantStorageContract.UpdElement(restaurant);
AssertElement(GetRestaurantFromDatabase(restaurant.Id), restaurant);
}
[Test]
public void Try_UpdElement_WhenNoRecordWithThisId_Test()
{
Assert.That(() => _restaurantStorageContract.UpdElement(CreateModel(Guid.NewGuid().ToString())), Throws.TypeOf<ElementNotFoundException>());
}
[Test]
public void Try_UpdElement_WhenHaveRecordWithSameRestaurantName_Test()
{
var restaurant = CreateModel(Guid.NewGuid().ToString(), "name unique");
InsertRestaurantToDatabaseAndReturn(restaurant.Id, restaurantName: "some name");
InsertRestaurantToDatabaseAndReturn(Guid.NewGuid().ToString(), restaurantName: restaurant.RestaurantName);
Assert.That(() => _restaurantStorageContract.UpdElement(restaurant), Throws.TypeOf<ElementExistsException>());
}
[Test]
public void Try_DelElement_WhenNoRecordWithThisId_Test()
{
Assert.That(() => _restaurantStorageContract.DelElement(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
}
private Restaurant InsertRestaurantToDatabaseAndReturn(string id, string restaurantName = "test", string prevRestaurantName = "prev", string prevPrevRestaurantName = "prevPrev")
{
var restaurant = new Restaurant() { Id = id, RestaurantName = restaurantName, PrevRestaurantName = prevRestaurantName, PrevPrevRestaurantName = prevPrevRestaurantName };
SPiluSZharuDbContext.Restaurants.Add(restaurant);
SPiluSZharuDbContext.SaveChanges();
return restaurant;
}
private static void AssertElement(RestaurantDataModel? actual, Restaurant expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.Id, Is.EqualTo(expected.Id));
Assert.That(actual.RestaurantName, Is.EqualTo(expected.RestaurantName));
Assert.That(actual.PrevRestaurantName, Is.EqualTo(expected.PrevRestaurantName));
Assert.That(actual.PrevPrevRestaurantName, Is.EqualTo(expected.PrevPrevRestaurantName));
});
}
private static RestaurantDataModel CreateModel(string id, string restaurantName = "test", string prevRestaurantName = "prev", string prevPrevRestaurantName = "prevPrev")
=> new(id, restaurantName, prevRestaurantName, prevPrevRestaurantName);
private Restaurant? GetRestaurantFromDatabase(string id) => SPiluSZharuDbContext.Restaurants.FirstOrDefault(x => x.Id == id);
private static void AssertElement(Restaurant? actual, RestaurantDataModel expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.Id, Is.EqualTo(expected.Id));
Assert.That(actual.RestaurantName, Is.EqualTo(expected.RestaurantName));
Assert.That(actual.PrevRestaurantName, Is.EqualTo(expected.PrevRestaurantName));
Assert.That(actual.PrevPrevRestaurantName, Is.EqualTo(expected.PrevPrevRestaurantName));
});
}
}

View File

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

View File

@@ -0,0 +1,296 @@
using Microsoft.EntityFrameworkCore;
using SPiluSZharuContracts.DataModels;
using SPiluSZharuContracts.Enums;
using SPiluSZharuContracts.Exceptions;
using SPiluSZharuDatabase.Implementations;
using SPiluSZharuDatabase.Models;
namespace SPiluSZharuTests.StoragesContracts;
[TestFixture]
internal class SaleStorageContractTests : BaseStorageContractTest
{
private SaleStorageContract _saletStorageContract;
private Restaurant _restaurant;
private Worker _worker;
private Product _product;
[SetUp]
public void SetUp()
{
_saletStorageContract = new SaleStorageContract(SPiluSZharuDbContext);
_restaurant = InsertRestaurantToDatabaseAndReturn();
_worker = InsertWorkerToDatabaseAndReturn();
_product = InsertProductToDatabaseAndReturn();
}
[TearDown]
public void TearDown()
{
SPiluSZharuDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Sales\" CASCADE;");
SPiluSZharuDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Restaurants\" CASCADE;");
SPiluSZharuDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Workers\" CASCADE;");
SPiluSZharuDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Products\" CASCADE;");
}
[Test]
public void Try_GetList_WhenHaveRecords_Test()
{
var sale = InsertSaleToDatabaseAndReturn(_worker.Id, _restaurant.Id, products: [(_product.Id, 1)]);
InsertSaleToDatabaseAndReturn(_worker.Id, _restaurant.Id, products: [(_product.Id, 5)]);
InsertSaleToDatabaseAndReturn(_worker.Id, null, products: [(_product.Id, 10)]);
var list = _saletStorageContract.GetList();
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(3));
AssertElement(list.First(x => x.Id == sale.Id), sale);
}
[Test]
public void Try_GetList_WhenNoRecords_Test()
{
var list = _saletStorageContract.GetList();
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.Empty);
}
[Test]
public void Try_GetList_ByPeriod_Test()
{
InsertSaleToDatabaseAndReturn(_worker.Id, _restaurant.Id, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(-3), products: [(_product.Id, 1)]);
InsertSaleToDatabaseAndReturn(_worker.Id, _restaurant.Id, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(3), products: [(_product.Id, 1)]);
InsertSaleToDatabaseAndReturn(_worker.Id, null, saleDate: DateTime.UtcNow.AddDays(1).AddMinutes(-3), products: [(_product.Id, 1)]);
InsertSaleToDatabaseAndReturn(_worker.Id, null, saleDate: DateTime.UtcNow.AddDays(1).AddMinutes(3), products: [(_product.Id, 1)]);
var list = _saletStorageContract.GetList(startDate: DateTime.UtcNow.AddDays(-1), endDate: DateTime.UtcNow.AddDays(1));
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(2));
}
[Test]
public void Try_GetList_ByWorkerId_Test()
{
var worker = InsertWorkerToDatabaseAndReturn("Other worker", "+7(555)555-55-55");
InsertSaleToDatabaseAndReturn(_worker.Id, _restaurant.Id, products: [(_product.Id, 1)]);
InsertSaleToDatabaseAndReturn(_worker.Id, _restaurant.Id, products: [(_product.Id, 1)]);
InsertSaleToDatabaseAndReturn(worker.Id, null, products: [(_product.Id, 1)]);
var list = _saletStorageContract.GetList(workerId: _worker.Id);
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(2));
Assert.That(list.All(x => x.WorkerId == _worker.Id));
}
[Test]
public void Try_GetList_ByRestaurantId_Test()
{
var restaurant = InsertRestaurantToDatabaseAndReturn("Other restaurant");
InsertSaleToDatabaseAndReturn(_worker.Id, _restaurant.Id, products: [(_product.Id, 1)]);
InsertSaleToDatabaseAndReturn(_worker.Id, _restaurant.Id, products: [(_product.Id, 1)]);
InsertSaleToDatabaseAndReturn(_worker.Id, restaurant.Id, products: [(_product.Id, 1)]);
InsertSaleToDatabaseAndReturn(_worker.Id, null, products: [(_product.Id, 1)]);
var list = _saletStorageContract.GetList(restaurantId: _restaurant.Id);
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(2));
Assert.That(list.All(x => x.RestaurantId == _restaurant.Id));
}
[Test]
public void Try_GetList_ByProductId_Test()
{
var product = InsertProductToDatabaseAndReturn("Other name");
InsertSaleToDatabaseAndReturn(_worker.Id, _restaurant.Id, products: [(_product.Id, 5)]);
InsertSaleToDatabaseAndReturn(_worker.Id, _restaurant.Id, products: [(_product.Id, 1), (product.Id, 4)]);
InsertSaleToDatabaseAndReturn(_worker.Id, null, products: [(product.Id, 1)]);
InsertSaleToDatabaseAndReturn(_worker.Id, null, products: [(product.Id, 1), (_product.Id, 1)]);
var list = _saletStorageContract.GetList(productId: _product.Id);
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(3));
Assert.That(list.All(x => x.Products.Any(y => y.ProductId == _product.Id)));
}
[Test]
public void Try_GetList_ByAllParameters_Test()
{
var worker = InsertWorkerToDatabaseAndReturn("Other worker", "+7(555)555-55-55");
var restaurant = InsertRestaurantToDatabaseAndReturn("Other restaurant");
var product = InsertProductToDatabaseAndReturn("Other name");
InsertSaleToDatabaseAndReturn(_worker.Id, _restaurant.Id, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(-3), products: [(_product.Id, 1)]);
InsertSaleToDatabaseAndReturn(worker.Id, null, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(3), products: [(_product.Id, 1)]);
InsertSaleToDatabaseAndReturn(worker.Id, _restaurant.Id, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(3), products: [(_product.Id, 1)]);
InsertSaleToDatabaseAndReturn(worker.Id, _restaurant.Id, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(3), products: [(product.Id, 1)]);
InsertSaleToDatabaseAndReturn(_worker.Id, restaurant.Id, saleDate: DateTime.UtcNow.AddDays(1).AddMinutes(-3), products: [(_product.Id, 1)]);
InsertSaleToDatabaseAndReturn(_worker.Id, _restaurant.Id, saleDate: DateTime.UtcNow.AddDays(1).AddMinutes(-3), products: [(product.Id, 1)]);
InsertSaleToDatabaseAndReturn(worker.Id, null, saleDate: DateTime.UtcNow.AddDays(1).AddMinutes(-3), products: [(_product.Id, 1)]);
var list = _saletStorageContract.GetList(startDate: DateTime.UtcNow.AddDays(-1), endDate: DateTime.UtcNow.AddDays(1), workerId: _worker.Id, restaurantId: _restaurant.Id, productId: product.Id);
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(1));
}
[Test]
public void Try_GetElementById_WhenHaveRecord_Test()
{
var sale = InsertSaleToDatabaseAndReturn(_worker.Id, _restaurant.Id, products: [(_product.Id, 1)]);
AssertElement(_saletStorageContract.GetElementById(sale.Id), sale);
}
[Test]
public void Try_GetElementById_WhenNoRecord_Test()
{
InsertSaleToDatabaseAndReturn(_worker.Id, _restaurant.Id, products: [(_product.Id, 1)]);
Assert.That(() => _saletStorageContract.GetElementById(Guid.NewGuid().ToString()), Is.Null);
}
[Test]
public void Try_GetElementById_WhenRecordHasCanceled_Test()
{
var sale = InsertSaleToDatabaseAndReturn(_worker.Id, _restaurant.Id, products: [(_product.Id, 1)], isCancel: true);
AssertElement(_saletStorageContract.GetElementById(sale.Id), sale);
}
[Test]
public void Try_AddElement_Test()
{
var sale = CreateModel(Guid.NewGuid().ToString(), _worker.Id, _restaurant.Id, 1, false, [_product.Id]);
_saletStorageContract.AddElement(sale);
AssertElement(GetSaleFromDatabaseById(sale.Id), sale);
}
[Test]
public void Try_AddElement_WhenIsDeletedIsTrue_Test()
{
var sale = CreateModel(Guid.NewGuid().ToString(), _worker.Id, _restaurant.Id, 1, true, [_product.Id]);
Assert.That(() => _saletStorageContract.AddElement(sale), Throws.Nothing);
AssertElement(GetSaleFromDatabaseById(sale.Id), CreateModel(sale.Id, _worker.Id, _restaurant.Id, 1, false, [_product.Id]));
}
[Test]
public void Try_DelElement_Test()
{
var sale = InsertSaleToDatabaseAndReturn(_worker.Id, _restaurant.Id, products: [(_product.Id, 1)], isCancel: false);
_saletStorageContract.DelElement(sale.Id);
var element = GetSaleFromDatabaseById(sale.Id);
Assert.Multiple(() =>
{
Assert.That(element, Is.Not.Null);
Assert.That(element!.IsCancel);
});
}
[Test]
public void Try_DelElement_WhenNoRecordWithThisId_Test()
{
Assert.That(() => _saletStorageContract.DelElement(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
}
[Test]
public void Try_DelElement_WhenRecordWasCanceled_Test()
{
var sale = InsertSaleToDatabaseAndReturn(_worker.Id, _restaurant.Id, products: [(_product.Id, 1)], isCancel: true);
Assert.That(() => _saletStorageContract.DelElement(sale.Id), Throws.TypeOf<ElementDeletedException>());
}
private Restaurant InsertRestaurantToDatabaseAndReturn(string restaurantName = "test")
{
var restaurant = new Restaurant() { Id = Guid.NewGuid().ToString(), RestaurantName = restaurantName };
SPiluSZharuDbContext.Restaurants.Add(restaurant);
SPiluSZharuDbContext.SaveChanges();
return restaurant;
}
private Worker InsertWorkerToDatabaseAndReturn(string fio = "test", string phoneNumber = "+7(777)777-77-77")
{
var worker = new Worker() { Id = Guid.NewGuid().ToString(), FIO = fio, PostId = Guid.NewGuid().ToString(), PhoneNumber = phoneNumber };
SPiluSZharuDbContext.Workers.Add(worker);
SPiluSZharuDbContext.SaveChanges();
return worker;
}
private Product InsertProductToDatabaseAndReturn(string productName = "test", ProductType productType = ProductType.Burgers, double price = 1, bool isDeleted = false)
{
var product = new Product() { Id = Guid.NewGuid().ToString(), ProductName = productName, ProductType = productType, Price = price, IsDeleted = isDeleted };
SPiluSZharuDbContext.Products.Add(product);
SPiluSZharuDbContext.SaveChanges();
return product;
}
private Sale InsertSaleToDatabaseAndReturn(string workerId, string? restaurantId, DateTime? saleDate = null, double sum = 1, bool isCancel = false, List<(string, int)>? products = null)
{
var sale = new Sale() { WorkerId = workerId, RestaurantId = restaurantId, SaleDate = saleDate ?? DateTime.UtcNow, Sum = sum, 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 });
}
}
SPiluSZharuDbContext.Sales.Add(sale);
SPiluSZharuDbContext.SaveChanges();
return sale;
}
private static void AssertElement(SaleDataModel? actual, Sale expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.Id, Is.EqualTo(expected.Id));
Assert.That(actual.WorkerId, Is.EqualTo(expected.WorkerId));
Assert.That(actual.RestaurantId, Is.EqualTo(expected.RestaurantId));
Assert.That(actual.IsCancel, Is.EqualTo(expected.IsCancel));
});
if (expected.SaleProducts is not null)
{
Assert.That(actual.Products, Is.Not.Null);
Assert.That(actual.Products, Has.Count.EqualTo(expected.SaleProducts.Count));
for (int i = 0; i < actual.Products.Count; ++i)
{
Assert.Multiple(() =>
{
Assert.That(actual.Products[i].ProductId, Is.EqualTo(expected.SaleProducts[i].ProductId));
Assert.That(actual.Products[i].Count, Is.EqualTo(expected.SaleProducts[i].Count));
});
}
}
else
{
Assert.That(actual.Products, Is.Null);
}
}
private static SaleDataModel CreateModel(string id, string workerId, string? restaurantId, double sum, bool isCancel, List<string> productIds)
{
var products = productIds.Select(x => new SaleProductDataModel(id, x, 1)).ToList();
return new(id, workerId, restaurantId, sum, isCancel, products);
}
private Sale? GetSaleFromDatabaseById(string id) => SPiluSZharuDbContext.Sales.Include(x => x.SaleProducts).FirstOrDefault(x => x.Id == id);
private static void AssertElement(Sale? actual, SaleDataModel expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.Id, Is.EqualTo(expected.Id));
Assert.That(actual.WorkerId, Is.EqualTo(expected.WorkerId));
Assert.That(actual.RestaurantId, Is.EqualTo(expected.RestaurantId));
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,239 @@
using Microsoft.EntityFrameworkCore;
using SPiluSZharuContracts.DataModels;
using SPiluSZharuContracts.Exceptions;
using SPiluSZharuDatabase.Implementations;
using SPiluSZharuDatabase.Models;
namespace SPiluSZharuTests.StoragesContracts;
[TestFixture]
internal class WorkerStorageContractTests : BaseStorageContractTest
{
private WorkerStorageContract _workerStorageContract;
[SetUp]
public void SetUp()
{
_workerStorageContract = new WorkerStorageContract(SPiluSZharuDbContext);
}
[TearDown]
public void TearDown()
{
SPiluSZharuDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Workers\" CASCADE;");
}
[Test]
public void Try_GetList_WhenHaveRecords_Test()
{
var worker = InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 1", phoneNumber:"+7(555)555-55-55");
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 2", phoneNumber: "+7(333)333-33-33");
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 3", phoneNumber: "+7(111)111-11-11");
var list = _workerStorageContract.GetList();
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(3));
AssertElement(list.First(), worker);
}
[Test]
public void Try_GetList_WhenNoRecords_Test()
{
var list = _workerStorageContract.GetList();
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.Empty);
}
[Test]
public void Try_GetList_ByPostId_Test()
{
var postId = Guid.NewGuid().ToString();
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 1", postId, "+7(555)555-55-55");
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 2", postId, "+7(333)333-33-33");
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 3", phoneNumber: "+7(111)111-11-11");
var list = _workerStorageContract.GetList(postId: postId);
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(2));
Assert.That(list.All(x => x.PostId == postId));
}
[Test]
public void Try_GetList_ByBirthDate_Test()
{
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 1", phoneNumber: "+7(555)555-55-55", birthDate: DateTime.UtcNow.AddYears(-25));
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 2", phoneNumber: "+7(333)333-33-33", birthDate: DateTime.UtcNow.AddYears(-21));
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 3", phoneNumber: "+7(111)111-11-11", birthDate: DateTime.UtcNow.AddYears(-20));
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 4", phoneNumber: "+7(222)222-22-22", birthDate: DateTime.UtcNow.AddYears(-19));
var list = _workerStorageContract.GetList(fromBirthDate: DateTime.UtcNow.AddYears(-21).AddMinutes(-1), toBirthDate: DateTime.UtcNow.AddYears(-20).AddMinutes(1));
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(2));
}
[Test]
public void Try_GetList_ByEmploymentDate_Test()
{
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 1", phoneNumber: "+7(555)555-55-55", employmentDate: DateTime.UtcNow.AddDays(-2));
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 2", phoneNumber: "+7(333)333-33-33", employmentDate: DateTime.UtcNow.AddDays(-1));
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 3", phoneNumber: "+7(111)111-11-11", employmentDate: DateTime.UtcNow.AddDays(1));
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 4", phoneNumber: "+7(222)222-22-22", employmentDate: DateTime.UtcNow.AddDays(2));
var list = _workerStorageContract.GetList(fromEmploymentDate: DateTime.UtcNow.AddDays(-1).AddMinutes(-1), toEmploymentDate: DateTime.UtcNow.AddDays(1).AddMinutes(1));
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(2));
}
[Test]
public void Try_GetList_ByAllParameters_Test()
{
var postId = Guid.NewGuid().ToString();
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 1", postId, "+7(555)555-55-55", birthDate: DateTime.UtcNow.AddYears(-25), employmentDate: DateTime.UtcNow.AddDays(-2));
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 2", postId, "+7(333)333-33-33", birthDate: DateTime.UtcNow.AddYears(-22), employmentDate: DateTime.UtcNow.AddDays(-1));
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 3", postId, "+7(111)111-11-11", birthDate: DateTime.UtcNow.AddYears(-21), employmentDate: DateTime.UtcNow.AddDays(-1));
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 4", phoneNumber: "+7(222)222-22-22", birthDate: DateTime.UtcNow.AddYears(-20), employmentDate: DateTime.UtcNow.AddDays(1));
var list = _workerStorageContract.GetList(postId: postId, fromBirthDate: DateTime.UtcNow.AddYears(-21).AddMinutes(-1), toBirthDate: DateTime.UtcNow.AddYears(-20).AddMinutes(1), fromEmploymentDate: DateTime.UtcNow.AddDays(-1).AddMinutes(-1), toEmploymentDate: DateTime.UtcNow.AddDays(1).AddMinutes(1));
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(1));
}
[Test]
public void Try_GetElementById_WhenHaveRecord_Test()
{
var worker = InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString());
AssertElement(_workerStorageContract.GetElementById(worker.Id), worker);
}
[Test]
public void Try_GetElementById_WhenNoRecord_Test()
{
Assert.That(() => _workerStorageContract.GetElementById(Guid.NewGuid().ToString()), Is.Null);
}
[Test]
public void Try_GetElementByFIO_WhenHaveRecord_Test()
{
var worker = InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString());
AssertElement(_workerStorageContract.GetElementByFIO(worker.FIO), worker);
}
[Test]
public void Try_GetElementByFIO_WhenNoRecord_Test()
{
Assert.That(() => _workerStorageContract.GetElementByFIO("New Fio"), Is.Null);
}
[Test]
public void Try_GetElementByPhoneNumber_WhenHaveRecord_Test()
{
var worker = InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString());
AssertElement(_workerStorageContract.GetElementByPhoneNumber(worker.PhoneNumber), worker);
}
[Test]
public void Try_GetElementByPhoneNumber_WhenNoRecord_Test()
{
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString());
Assert.That(() => _workerStorageContract.GetElementByPhoneNumber("+7(888)888-88-88"), Is.Null);
}
[Test]
public void Try_AddElement_Test()
{
var worker = CreateModel(Guid.NewGuid().ToString());
_workerStorageContract.AddElement(worker);
AssertElement(GetWorkerFromDatabase(worker.Id), worker);
}
[Test]
public void Try_AddElement_WhenHaveRecordWithSameId_Test()
{
var worker = CreateModel(Guid.NewGuid().ToString());
InsertWorkerToDatabaseAndReturn(worker.Id);
Assert.That(() => _workerStorageContract.AddElement(worker), Throws.TypeOf<ElementExistsException>());
}
[Test]
public void Try_UpdElement_Test()
{
var worker = CreateModel(Guid.NewGuid().ToString(), "New Fio", "+7(555)555-55-55");
InsertWorkerToDatabaseAndReturn(worker.Id);
_workerStorageContract.UpdElement(worker);
AssertElement(GetWorkerFromDatabase(worker.Id), worker);
}
[Test]
public void Try_UpdElement_WhenNoRecordWithThisId_Test()
{
Assert.That(() => _workerStorageContract.UpdElement(CreateModel(Guid.NewGuid().ToString())), Throws.TypeOf<ElementNotFoundException>());
}
[Test]
public void Try_UpdElement_WhenNoRecordWasDeleted_Test()
{
var worker = CreateModel(Guid.NewGuid().ToString(), "+7(555)555-55-55");
InsertWorkerToDatabaseAndReturn(worker.Id, isDeleted: true);
Assert.That(() => _workerStorageContract.UpdElement(worker), Throws.TypeOf<ElementNotFoundException>());
}
[Test]
public void Try_DelElement_Test()
{
var worker = InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString());
_workerStorageContract.DelElement(worker.Id);
var element = GetWorkerFromDatabase(worker.Id);
Assert.That(element, Is.Not.Null);
Assert.That(element.IsDeleted);
}
[Test]
public void Try_DelElement_WhenNoRecordWithThisId_Test()
{
Assert.That(() => _workerStorageContract.DelElement(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
}
[Test]
public void Try_DelElement_WhenNoRecordWasDeleted_Test()
{
var worker = CreateModel(Guid.NewGuid().ToString());
InsertWorkerToDatabaseAndReturn(worker.Id, isDeleted: true);
Assert.That(() => _workerStorageContract.DelElement(worker.Id), Throws.TypeOf<ElementNotFoundException>());
}
private Worker InsertWorkerToDatabaseAndReturn(string id, string fio = "test", string? postId = null, string phoneNumber = "+7(777)777-77-77", DateTime? birthDate = null, DateTime? employmentDate = null, bool isDeleted = false)
{
var worker = new Worker() { Id = id, FIO = fio, PostId = postId ?? Guid.NewGuid().ToString(), PhoneNumber = phoneNumber, BirthDate = birthDate ?? DateTime.UtcNow.AddYears(-20), EmploymentDate = employmentDate ?? DateTime.UtcNow, IsDeleted = isDeleted };
SPiluSZharuDbContext.Workers.Add(worker);
SPiluSZharuDbContext.SaveChanges();
return worker;
}
private static void AssertElement(WorkerDataModel? actual, Worker expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.Id, Is.EqualTo(expected.Id));
Assert.That(actual.PostId, Is.EqualTo(expected.PostId));
Assert.That(actual.FIO, Is.EqualTo(expected.FIO));
Assert.That(actual.BirthDate, Is.EqualTo(expected.BirthDate));
Assert.That(actual.EmploymentDate, Is.EqualTo(expected.EmploymentDate));
Assert.That(actual.IsDeleted, Is.EqualTo(expected.IsDeleted));
});
}
private static WorkerDataModel CreateModel(string id, string fio = "fio", string? postId = null, string phoneNumber = "+7(777)777-77-77", DateTime? birthDate = null, DateTime? employmentDate = null, bool isDeleted = false) =>
new(id, fio, postId ?? Guid.NewGuid().ToString(), phoneNumber, birthDate ?? DateTime.UtcNow.AddYears(-20), employmentDate ?? DateTime.UtcNow, isDeleted);
private Worker? GetWorkerFromDatabase(string id) => SPiluSZharuDbContext.Workers.FirstOrDefault(x => x.Id == id);
private static void AssertElement(Worker? actual, WorkerDataModel expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.Id, Is.EqualTo(expected.Id));
Assert.That(actual.PostId, Is.EqualTo(expected.PostId));
Assert.That(actual.FIO, Is.EqualTo(expected.FIO));
Assert.That(actual.BirthDate, Is.EqualTo(expected.BirthDate));
Assert.That(actual.EmploymentDate, Is.EqualTo(expected.EmploymentDate));
Assert.That(actual.IsDeleted, Is.EqualTo(expected.IsDeleted));
});
}
}