PIbd-23_MarinenkovaVA_Lab3 #3

Closed
marva wants to merge 5 commits from Task_3_Storage into Task_2_BuisnessLogic
32 changed files with 2794 additions and 3 deletions

View File

@@ -8,7 +8,12 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="AutoMapper" Version="12.0.0" />
<PackageReference Include="EntityFramework" Version="6.5.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.15" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="9.0.3" />
<PackageReference Include="Npgsql" Version="7.0.10" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="7.0.11" />
</ItemGroup>
<ItemGroup>

View File

@@ -0,0 +1,27 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<LangVersion>preview</LangVersion>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="AutoMapper" Version="12.0.0" />
<PackageReference Include="EntityFramework" Version="6.5.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.15" />
<PackageReference Include="Npgsql" Version="7.0.10" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="7.0.11" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\AndDietCokeProject\AndDietCokeContracts.csproj" />
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="AndDietCokeTests" />
<InternalsVisibleTo Include="DynamicProxyGenAssembly2" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,58 @@
using AndDietCokeDatabase.Models;
using AndDietCokeContracts.Infrastrusture;
using Microsoft.EntityFrameworkCore;
namespace AndDietCokeDatabase;
internal class AndDietCokeDbContext(IConfigurationDatabase configurationDatabase) : DbContext
{
private readonly IConfigurationDatabase? _configurationDatabase = configurationDatabase;
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseNpgsql(_configurationDatabase?.ConnectionString, o => o.SetPostgresVersion(12, 2));
base.OnConfiguring(optionsBuilder);
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Buyer>()
.HasIndex(x => x.PhoneNumber).IsUnique();
modelBuilder.Entity<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<Dish>()
.HasIndex(x => new { x.DishName, x.IsDeleted })
.IsUnique()
.HasFilter($"\"{nameof(Dish.IsDeleted)}\" = FALSE");
modelBuilder.Entity<OrderDish>()
.HasKey(x => new { x.OrderId, x.DishId });
}
public DbSet<Buyer> Buyers { get; set; }
public DbSet<Post> Posts { get; set; }
public DbSet<Dish> Dishes { get; set; }
public DbSet<DishHistory> DishHistories { get; set; }
public DbSet<Salary> Salaries { get; set; }
public DbSet<Sale> Sales { get; set; }
public DbSet<OrderDish> OrderDishes { get; set; }
public DbSet<Worker> Workers { get; set; }
}

View File

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

View File

@@ -0,0 +1,176 @@
using AndDietCokeContracts.DataModels;
using AndDietCokeContracts.Exceptions;
using AndDietCokeContracts.StoragesContracts;
using AndDietCokeDatabase.Models;
using AutoMapper;
using Microsoft.EntityFrameworkCore;
using Npgsql;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AndDietCokeDatabase.Implementations;
internal class DishStorageContract : IDishStorageContract
{
private readonly AndDietCokeDbContext _dbContext;
private readonly Mapper _mapper;
public DishStorageContract(AndDietCokeDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Dish, DishDataModel>();
cfg.CreateMap<DishDataModel, Dish>()
.ForMember(x => x.IsDeleted, x => x.MapFrom(src => false));
cfg.CreateMap<DishHistory, DishHistoryDataModel>();
});
_mapper = new Mapper(config);
}
public List<DishDataModel> GetList(bool onlyActive = true)
{
try
{
var query = _dbContext.Dishes.AsQueryable();
if (onlyActive)
{
query = query.Where(x => !x.IsDeleted);
}
return [.. query.Select(x => _mapper.Map<DishDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public List<DishHistoryDataModel> GetHistoryByDishId(string dishId)
{
try
{
return [.. _dbContext.DishHistories.Where(x => x.DishId == dishId).OrderByDescending(x => x.ChangeDate).Select(x => _mapper.Map<DishHistoryDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public DishDataModel? GetElementById(string id)
{
try
{
return _mapper.Map<DishDataModel>(GetDishById(id));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public DishDataModel? GetElementByName(string name)
{
try
{
return _mapper.Map<DishDataModel>(_dbContext.Dishes.FirstOrDefault(x => x.DishName == name && !x.IsDeleted));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void AddElement(DishDataModel dishDataModel)
{
try
{
_dbContext.Dishes.Add(_mapper.Map<Dish>(dishDataModel));
_dbContext.SaveChanges();
}
catch (InvalidOperationException ex) when (ex.TargetSite?.Name == "ThrowIdentityConflict")
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("Id", dishDataModel.Id);
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Dishes_DishName_IsDeleted" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("DishName", dishDataModel.DishName);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void UpdElement(DishDataModel dishDataModel)
{
try
{
var transaction = _dbContext.Database.BeginTransaction();
try
{
var element = GetDishById(dishDataModel.Id) ?? throw new ElementNotFoundException(dishDataModel.Id);
if (element.Price != dishDataModel.Price)
{
_dbContext.DishHistories.Add(new DishHistory() { DishId = element.Id, OldPrice = element.Price });
_dbContext.SaveChanges();
}
_dbContext.Dishes.Update(_mapper.Map(dishDataModel, element));
_dbContext.SaveChanges();
transaction.Commit();
}
catch
{
transaction.Rollback();
throw;
}
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Dishes_DishName_IsDeleted" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("DishName", dishDataModel.DishName);
}
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 = GetDishById(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 Dish? GetDishById(string id) => _dbContext.Dishes.FirstOrDefault(x => x.Id == id && !x.IsDeleted);
}

View File

@@ -0,0 +1,195 @@
using AndDietCokeContracts.DataModels;
using AndDietCokeContracts.Exceptions;
using AndDietCokeContracts.StoragesContracts;
using AndDietCokeDatabase.Models;
using AutoMapper;
using Microsoft.EntityFrameworkCore;
using Npgsql;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AndDietCokeDatabase.Implementations;
internal class PostStorageContract : IPostStorageContract
{
private readonly AndDietCokeDbContext _dbContext;
private readonly Mapper _mapper;
public PostStorageContract(AndDietCokeDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Post, PostDataModel>()
.ForMember(x => x.Id, opt => opt.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,62 @@
using AndDietCokeContracts.DataModels;
using AndDietCokeContracts.Exceptions;
using AndDietCokeContracts.StoragesContracts;
using AndDietCokeDatabase.Models;
using AutoMapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AndDietCokeDatabase.Implementations;
internal class SalaryStorageContract : ISalaryStorageContract
{
private readonly AndDietCokeDbContext _dbContext;
private readonly Mapper _mapper;
public SalaryStorageContract(AndDietCokeDbContext 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,144 @@
using AndDietCokeContracts.DataModels;
using AndDietCokeContracts.Exceptions;
using AndDietCokeContracts.StoragesContracts;
using AndDietCokeDatabase.Models;
using AutoMapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
namespace AndDietCokeDatabase.Implementations;
internal class SaleStorageContract : ISaleStorageContract
{
private readonly AndDietCokeDbContext _dbContext;
private readonly Mapper _mapper;
public SaleStorageContract(AndDietCokeDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<OrderDish, OrderDishDataModel>()
.ConstructUsing(od => new OrderDishDataModel(
od.OrderId,
od.DishId,
od.Count
));
cfg.CreateMap<Sale, SaleDataModel>()
.ConstructUsing(src => new SaleDataModel(
src.Id,
src.WorkerId,
src.BuyerId,
src.Sum,
src.IsConstantClient,
src.IsCancel,
src.OrderDishes != null
? src.OrderDishes.Select(od => new OrderDishDataModel(
od.OrderId,
od.DishId,
od.Count
)).ToList()
: new List<OrderDishDataModel>()
));
cfg.CreateMap<OrderDishDataModel, OrderDish>()
.ForMember(dest => dest.OrderId, opt => opt.MapFrom(src => src.OrderId))
.ForMember(dest => dest.DishId, opt => opt.MapFrom(src => src.DishId))
.ForMember(dest => dest.Count, opt => opt.MapFrom(src => src.Count));
cfg.CreateMap<SaleDataModel, Sale>()
.ForMember(x => x.IsCancel, x => x.MapFrom(src => false))
.ForMember(x => x.OrderDishes, x => x.MapFrom(src => src.Dishes));
});
_mapper = new Mapper(config);
}
public List<SaleDataModel> GetList(DateTime? startDate = null, DateTime? endDate = null, string? workerId = null, string? buyerId = null, string? dishId = null)
{
try
{
var query = _dbContext.Sales.Include(x => x.OrderDishes).AsQueryable();
if (startDate is not null && endDate is not null)
{
query = query.Where(x => x.SaleDate >= startDate && x.SaleDate < endDate);
}
if (workerId is not null)
{
query = query.Where(x => x.WorkerId == workerId);
}
if (buyerId is not null)
{
query = query.Where(x => x.BuyerId == buyerId);
}
if (dishId is not null)
{
query = query.Where(x => x.OrderDishes!.Any(y => y.DishId == dishId));
}
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,145 @@
using AndDietCokeContracts.DataModels;
using AndDietCokeContracts.Exceptions;
using AndDietCokeContracts.StoragesContracts;
using AndDietCokeDatabase.Models;
using AutoMapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AndDietCokeDatabase.Implementations;
internal class WorkerStorageContract : IWorkerStorageContract
{
private readonly AndDietCokeDbContext _dbContext;
private readonly Mapper _mapper;
public WorkerStorageContract(AndDietCokeDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.AddMaps(typeof(AndDietCokeDbContext).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 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,25 @@
using AndDietCokeContracts.DataModels;
using AutoMapper;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AndDietCokeDatabase.Models;
[AutoMap(typeof(BuyerDataModel), ReverseMap = true)]
public class Buyer
{
public required string Id { get; set; }
public required string FIO { get; set; }
public required string PhoneNumber { get; set; }
public double DiscountSize { get; set; }
[ForeignKey("BuyerId")]
public List<Sale>? Sales { get; set; }
}

View File

@@ -0,0 +1,26 @@
using AndDietCokeContracts.Enums;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AndDietCokeDatabase.Models;
public class Dish
{
public required string Id { get; set; }
public required string DishName { get; set; }
public DishType DishType { get; set; }
public double Price { get; set; }
public bool IsDeleted { get; set; }
[ForeignKey("DishId")]
public List<DishHistory>? DishHistories { get; set; }
}

View File

@@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AndDietCokeDatabase.Models;
public class DishHistory
{
public string Id { get; set; } = Guid.NewGuid().ToString();
public required string DishId { get; set; }
public double OldPrice { get; set; }
public DateTime ChangeDate { get; set; }
public Dish? Dish { get; set; }
}

View File

@@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AndDietCokeDatabase.Models;
public class OrderDish
{
public required string OrderId { get; set; }
public required string DishId { get; set; }
public int Count { get; set; }
public Sale? Sale { get; set; }
public Dish? Dish { get; set; }
}

View File

@@ -0,0 +1,25 @@
using AndDietCokeContracts.Enums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AndDietCokeDatabase.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,20 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AndDietCokeDatabase.Models;
public 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,32 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AndDietCokeDatabase.Models;
public class Sale
{
public string Id { get; set; } = Guid.NewGuid().ToString();
public required string WorkerId { get; set; }
public string? BuyerId { get; set; }
public DateTime SaleDate { get; set; }
public double Sum { get; set; }
public bool IsConstantClient { get; set; }
public bool IsCancel { get; set; }
public Worker? Worker { get; set; }
public Buyer? Buyer { get; set; }
[ForeignKey("SaleId")]
public List<OrderDish>? OrderDishes { get; set; }
}

View File

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

View File

@@ -7,7 +7,12 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AndDietCokeContracts", "And
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AndDietCokeTests", "AndDietCokeTests\AndDietCokeTests.csproj", "{EABA3AD5-7690-448A-BEE6-010499DD8790}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AndDietCokeBuisnessLogic", "AndDietCokeBuisnessLogic\AndDietCokeBuisnessLogic.csproj", "{3C1C0E8F-5CB4-4E93-B20C-86FF4B248ECF}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AndDietCokeBuisnessLogic", "AndDietCokeBuisnessLogic\AndDietCokeBuisnessLogic.csproj", "{3C1C0E8F-5CB4-4E93-B20C-86FF4B248ECF}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AndDietCokeDatabase", "AndDietCokeDatabase\AndDietCokeDatabase.csproj", "{4AFC4FDC-F8CA-4CC5-84E2-162ADA98EDD4}"
ProjectSection(ProjectDependencies) = postProject
{624595D1-D7AA-4448-AA30-4D5AA21AE6D6} = {624595D1-D7AA-4448-AA30-4D5AA21AE6D6}
EndProjectSection
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
@@ -27,6 +32,10 @@ Global
{3C1C0E8F-5CB4-4E93-B20C-86FF4B248ECF}.Debug|Any CPU.Build.0 = Debug|Any CPU
{3C1C0E8F-5CB4-4E93-B20C-86FF4B248ECF}.Release|Any CPU.ActiveCfg = Release|Any CPU
{3C1C0E8F-5CB4-4E93-B20C-86FF4B248ECF}.Release|Any CPU.Build.0 = Release|Any CPU
{4AFC4FDC-F8CA-4CC5-84E2-162ADA98EDD4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{4AFC4FDC-F8CA-4CC5-84E2-162ADA98EDD4}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4AFC4FDC-F8CA-4CC5-84E2-162ADA98EDD4}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4AFC4FDC-F8CA-4CC5-84E2-162ADA98EDD4}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE

View File

@@ -7,4 +7,12 @@
<LangVersion>preview</LangVersion>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="AutoMapper" Version="12.0.0" />
<PackageReference Include="EntityFramework" Version="6.5.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.15" />
<PackageReference Include="Npgsql" Version="7.0.10" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="7.0.11" />
</ItemGroup>
</Project>

View File

@@ -18,7 +18,7 @@ postType, double salary, bool isActual, DateTime changeDate) : IValidation
public string PostName { get; private set; } = postName;
public PostType PostType { get; private set; } = postType;
public double Salary { get; private set; } = salary;
public bool isActual { get; private set; } = isActual;
public bool IsActual { get; private set; } = isActual;
public DateTime ChangeDate { get; private set; } = changeDate;
public void Validate()
{

View File

@@ -21,6 +21,7 @@ public class SaleDataModel(string id, string workerId, string? buyerId, double s
public bool IsConstantClient { get; private set; } = isConstantClient;
public bool IsCancel { get; private set; } = isCancel;
public List<OrderDishDataModel> Dishes { get; private set; } = dishes;
public void Validate()
{
if (Id.IsEmpty())

View File

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

View File

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

View File

@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
@@ -11,9 +11,14 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="AutoMapper" Version="12.0.0" />
<PackageReference Include="EntityFramework" Version="6.5.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.15" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="9.0.3" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.6.0" />
<PackageReference Include="Moq" Version="4.20.72" />
<PackageReference Include="Npgsql" Version="7.0.10" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="7.0.11" />
<PackageReference Include="NUnit" Version="3.13.3" />
<PackageReference Include="NUnit3TestAdapter" Version="4.4.2" />
<PackageReference Include="NUnit.Analyzers" Version="3.6.1" />
@@ -22,6 +27,7 @@
<ItemGroup>
<ProjectReference Include="..\AndDietCokeBuisnessLogic\AndDietCokeBuisnessLogic.csproj" />
<ProjectReference Include="..\AndDietCokeDatabase\AndDietCokeDatabase.csproj" />
<ProjectReference Include="..\AndDietCokeProject\AndDietCokeContracts.csproj" />
</ItemGroup>

View File

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

View File

@@ -0,0 +1,31 @@
using AndDietCokeTests.Infrastructure;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AndDietCokeDatabase;
namespace AndDietCokeTests.StoragesContracts;
internal abstract class BaseStorageContractTest
{
protected AndDietCokeDbContext AndDietCokeDbContext { get; private set; }
[OneTimeSetUp]
public void OneTimeSetUp()
{
AndDietCokeDbContext = new AndDietCokeDbContext(new ConfigurationDatabaseTest());
AndDietCokeDbContext.Database.EnsureDeleted();
AndDietCokeDbContext.Database.EnsureCreated();
}
[OneTimeTearDown]
public void OneTimeTearDown()
{
AndDietCokeDbContext.Database.EnsureDeleted();
AndDietCokeDbContext.Dispose();
}
}

View File

@@ -0,0 +1,215 @@
using AndDietCokeContracts.DataModels;
using AndDietCokeContracts.Exceptions;
using AndDietCokeContracts.StoragesContracts;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AndDietCokeDatabase.Implementations;
using AndDietCokeDatabase.Models;
using Microsoft.EntityFrameworkCore;
namespace AndDietCokeTests.StoragesContracts;
[TestFixture]
internal class BuyerStorageContractTests : BaseStorageContractTest
{
private BuyerStorageContract _buyerStorageContract;
[SetUp]
public void SetUp()
{
_buyerStorageContract = new BuyerStorageContract(AndDietCokeDbContext);
}
[TearDown]
public void TearDown()
{
AndDietCokeDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Sales\" CASCADE;");
AndDietCokeDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Workers\" CASCADE;");
AndDietCokeDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Buyers\" CASCADE;");
}
[Test]
public void Try_GetList_WhenHaveRecords_Test()
{
var buyer = InsertBuyerToDatabaseAndReturn(Guid.NewGuid().ToString(), "FIO", "+5-555-555-55-55", 10);
InsertBuyerToDatabaseAndReturn(Guid.NewGuid().ToString(), "FIO", "+6-666-666-66-66", 10);
InsertBuyerToDatabaseAndReturn(Guid.NewGuid().ToString(), "FIO", "+7-777-777-77-77", 10);
var list = _buyerStorageContract.GetList();
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(3));
AssertElement(list.First(x => x.Id == buyer.Id), buyer);
}
[Test]
public void Try_GetList_WhenNoRecords_Test()
{
var list = _buyerStorageContract.GetList();
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.Empty);
}
[Test]
public void Try_GetElementById_WhenHaveRecord_Test()
{
var buyer = InsertBuyerToDatabaseAndReturn(Guid.NewGuid().ToString());
AssertElement(_buyerStorageContract.GetElementById(buyer.Id), buyer);
}
[Test]
public void Try_GetElementById_WhenNoRecord_Test()
{
InsertBuyerToDatabaseAndReturn(Guid.NewGuid().ToString());
Assert.That(() => _buyerStorageContract.GetElementById(Guid.NewGuid().ToString()), Is.Null);
}
[Test]
public void Try_GetElementByFIO_WhenHaveRecord_Test()
{
var buyer = InsertBuyerToDatabaseAndReturn(Guid.NewGuid().ToString());
AssertElement(_buyerStorageContract.GetElementByFIO(buyer.FIO), buyer);
}
[Test]
public void Try_GetElementByFIO_WhenNoRecord_Test()
{
InsertBuyerToDatabaseAndReturn(Guid.NewGuid().ToString());
Assert.That(() => _buyerStorageContract.GetElementByFIO("New Fio"), Is.Null);
}
[Test]
public void Try_GetElementByPhoneNumber_WhenHaveRecord_Test()
{
var buyer = InsertBuyerToDatabaseAndReturn(Guid.NewGuid().ToString());
AssertElement(_buyerStorageContract.GetElementByPhoneNumber(buyer.PhoneNumber), buyer);
}
[Test]
public void Try_GetElementByPhoneNumber_WhenNoRecord_Test()
{
InsertBuyerToDatabaseAndReturn(Guid.NewGuid().ToString());
Assert.That(() => _buyerStorageContract.GetElementByPhoneNumber("+8-888-888-88-88"), Is.Null);
}
[Test]
public void Try_AddElement_Test()
{
var buyer = CreateModel(Guid.NewGuid().ToString());
_buyerStorageContract.AddElement(buyer);
AssertElement(GetBuyerFromDatabase(buyer.Id), buyer);
}
[Test]
public void Try_AddElement_WhenHaveRecordWithSameId_Test()
{
var buyer = CreateModel(Guid.NewGuid().ToString(), "New Fio", "+5-555-555-55-55");
InsertBuyerToDatabaseAndReturn(buyer.Id);
Assert.That(() => _buyerStorageContract.AddElement(buyer), Throws.TypeOf<ElementExistsException>());
}
[Test]
public void Try_AddElement_WhenHaveRecordWithSamePhoneNumber_Test()
{
var buyer = CreateModel(Guid.NewGuid().ToString(), "New Fio", "+5-555-555-55-55");
InsertBuyerToDatabaseAndReturn(Guid.NewGuid().ToString(), phoneNumber: buyer.PhoneNumber);
Assert.That(() => _buyerStorageContract.AddElement(buyer), Throws.TypeOf<ElementExistsException>());
}
[Test]
public void Try_UpdElement_Test()
{
var buyer = CreateModel(Guid.NewGuid().ToString(), "New Fio", "+5-555-555-55-55");
InsertBuyerToDatabaseAndReturn(buyer.Id);
_buyerStorageContract.UpdElement(buyer);
AssertElement(GetBuyerFromDatabase(buyer.Id), buyer);
}
[Test]
public void Try_UpdElement_WhenNoRecordWithThisId_Test()
{
Assert.That(() => _buyerStorageContract.UpdElement(CreateModel(Guid.NewGuid().ToString())), Throws.TypeOf<ElementNotFoundException>());
}
[Test]
public void Try_UpdElement_WhenHaveRecordWithSamePhoneNumber_Test()
{
var buyer = CreateModel(Guid.NewGuid().ToString(), "New Fio", "+5-555-555-55-55");
InsertBuyerToDatabaseAndReturn(buyer.Id, phoneNumber: "+7-777-777-77-77");
InsertBuyerToDatabaseAndReturn(Guid.NewGuid().ToString(), phoneNumber: buyer.PhoneNumber);
Assert.That(() => _buyerStorageContract.UpdElement(buyer), Throws.TypeOf<ElementExistsException>());
}
[Test]
public void Try_DelElement_Test()
{
var buyer = InsertBuyerToDatabaseAndReturn(Guid.NewGuid().ToString());
_buyerStorageContract.DelElement(buyer.Id);
var element = GetBuyerFromDatabase(buyer.Id);
Assert.That(element, Is.Null);
}
[Test]
public void Try_DelElement_WhenHaveSalesByThisBuyer_Test()
{
var buyer = InsertBuyerToDatabaseAndReturn(Guid.NewGuid().ToString());
var workerId = Guid.NewGuid().ToString();
AndDietCokeDbContext.Workers.Add(new Worker() { Id = workerId, FIO = "test", PostId = Guid.NewGuid().ToString() });
AndDietCokeDbContext.Sales.Add(new Sale() { Id = Guid.NewGuid().ToString(), WorkerId = workerId, BuyerId = buyer.Id, Sum = 10, IsConstantClient = true });
AndDietCokeDbContext.Sales.Add(new Sale() { Id = Guid.NewGuid().ToString(), WorkerId = workerId, BuyerId = buyer.Id, Sum = 10, IsConstantClient = true });
AndDietCokeDbContext.SaveChanges();
var salesBeforeDelete = AndDietCokeDbContext.Sales.Where(x => x.BuyerId == buyer.Id).ToArray();
_buyerStorageContract.DelElement(buyer.Id);
var element = GetBuyerFromDatabase(buyer.Id);
var salesAfterDelete = AndDietCokeDbContext.Sales.Where(x => x.BuyerId == buyer.Id).ToArray();
Assert.Multiple(() =>
{
Assert.That(element, Is.Null);
Assert.That(salesBeforeDelete, Has.Length.EqualTo(2));
Assert.That(salesAfterDelete, Is.Empty);
Assert.That(AndDietCokeDbContext.Sales.Count(), Is.EqualTo(2));
});
}
[Test]
public void Try_DelElement_WhenNoRecordWithThisId_Test()
{
Assert.That(() => _buyerStorageContract.DelElement(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
}
private Buyer InsertBuyerToDatabaseAndReturn(string id, string fio = "test", string phoneNumber = "+7-777-777-77-77", double discountSize = 10)
{
var buyer = new Buyer() { Id = id, FIO = fio, PhoneNumber = phoneNumber, DiscountSize = discountSize };
AndDietCokeDbContext.Buyers.Add(buyer);
AndDietCokeDbContext.SaveChanges();
return buyer;
}
private static void AssertElement(BuyerDataModel? actual, Buyer expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.Id, Is.EqualTo(expected.Id));
Assert.That(actual.FIO, Is.EqualTo(expected.FIO));
Assert.That(actual.PhoneNumber, Is.EqualTo(expected.PhoneNumber));
});
}
private static BuyerDataModel CreateModel(string id, string fio = "test", string phoneNumber = "+7-777-777-77-77") => new(id, fio, phoneNumber);
private Buyer? GetBuyerFromDatabase(string id) => AndDietCokeDbContext.Buyers.FirstOrDefault(x => x.Id == id);
private static void AssertElement(Buyer? actual, BuyerDataModel expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.Id, Is.EqualTo(expected.Id));
Assert.That(actual.FIO, Is.EqualTo(expected.FIO));
Assert.That(actual.PhoneNumber, Is.EqualTo(expected.PhoneNumber));
});
}
}

View File

@@ -0,0 +1,313 @@
using AndDietCokeContracts.Enums;
using AndDietCokeContracts.Exceptions;
using AndDietCokeDatabase.Implementations;
using AndDietCokeDatabase.Models;
using AndDietCokeContracts.DataModels;
using Microsoft.EntityFrameworkCore;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static NUnit.Framework.Internal.OSPlatform;
namespace AndDietCokeTests.StoragesContracts;
[TestFixture]
internal class DishStorageContractTests : BaseStorageContractTest
{
private DishStorageContract _dishStorageContract;
[SetUp]
public void SetUp()
{
_dishStorageContract = new DishStorageContract(AndDietCokeDbContext);
}
[TearDown]
public void TearDown()
{
AndDietCokeDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Dishes\" CASCADE;");
}
[Test]
public void Try_GetList_WhenHaveRecords_Test()
{
var dish = InsertDishToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 1");
InsertDishToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 2");
InsertDishToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 3");
var list = _dishStorageContract.GetList();
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(3));
AssertElement(list.First(x => x.Id == dish.Id), dish);
}
[Test]
public void Try_GetList_WhenNoRecords_Test()
{
var list = _dishStorageContract.GetList();
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.Empty);
}
[Test]
public void Try_GetList_OnlyActual_Test()
{
InsertDishToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 1", isDeleted: true);
InsertDishToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 2", isDeleted: false);
InsertDishToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 3", isDeleted: false);
var list = _dishStorageContract.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()
{
InsertDishToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 1", isDeleted: true);
InsertDishToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 2", isDeleted: true);
InsertDishToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 3", isDeleted: false);
var list = _dishStorageContract.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_GetHistoryByDishId_WhenHaveRecords_Test()
{
var dish = InsertDishToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 1");
InsertDishHistoryToDatabaseAndReturn(dish.Id, 20, DateTime.UtcNow.AddDays(-1));
InsertDishHistoryToDatabaseAndReturn(dish.Id, 30, DateTime.UtcNow.AddMinutes(-10));
InsertDishHistoryToDatabaseAndReturn(dish.Id, 40, DateTime.UtcNow.AddDays(1));
var list = _dishStorageContract.GetHistoryByDishId(dish.Id);
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(3));
}
[Test]
public void Try_GetHistoryByDishId_WhenNoRecords_Test()
{
var dish = InsertDishToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 1");
InsertDishHistoryToDatabaseAndReturn(dish.Id, 20, DateTime.UtcNow.AddDays(-1));
InsertDishHistoryToDatabaseAndReturn(dish.Id, 30, DateTime.UtcNow.AddMinutes(-10));
InsertDishHistoryToDatabaseAndReturn(dish.Id, 40, DateTime.UtcNow.AddDays(1));
var list = _dishStorageContract.GetHistoryByDishId(Guid.NewGuid().ToString());
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
}
[Test]
public void Try_GetElementById_WhenHaveRecord_Test()
{
var dish = InsertDishToDatabaseAndReturn(Guid.NewGuid().ToString());
AssertElement(_dishStorageContract.GetElementById(dish.Id), dish);
}
[Test]
public void Try_GetElementById_WhenNoRecord_Test()
{
InsertDishToDatabaseAndReturn(Guid.NewGuid().ToString());
Assert.That(() => _dishStorageContract.GetElementById(Guid.NewGuid().ToString()), Is.Null);
}
[Test]
public void Try_GetElementById_WhenRecordHasDeleted_Test()
{
var dish = InsertDishToDatabaseAndReturn(Guid.NewGuid().ToString(), isDeleted: true);
Assert.That(() => _dishStorageContract.GetElementById(dish.Id), Is.Null);
}
[Test]
public void Try_GetElementByName_WhenHaveRecord_Test()
{
var dish = InsertDishToDatabaseAndReturn(Guid.NewGuid().ToString());
AssertElement(_dishStorageContract.GetElementByName(dish.DishName), dish);
}
[Test]
public void Try_GetElementByName_WhenNoRecord_Test()
{
InsertDishToDatabaseAndReturn(Guid.NewGuid().ToString());
Assert.That(() => _dishStorageContract.GetElementByName("name"), Is.Null);
}
[Test]
public void Try_GetElementByName_WhenRecordHasDeleted_Test()
{
var dish = InsertDishToDatabaseAndReturn(Guid.NewGuid().ToString(), isDeleted: true);
Assert.That(() => _dishStorageContract.GetElementById(dish.DishName), Is.Null);
}
[Test]
public void Try_AddElement_Test()
{
var dish = CreateModel(Guid.NewGuid().ToString(), isDeleted: false);
_dishStorageContract.AddElement(dish);
AssertElement(GetDishFromDatabaseById(dish.Id), dish);
}
[Test]
public void Try_AddElement_WhenIsDeletedIsTrue_Test()
{
var dish = CreateModel(Guid.NewGuid().ToString(), isDeleted: true);
Assert.That(() => _dishStorageContract.AddElement(dish), Throws.Nothing);
AssertElement(GetDishFromDatabaseById(dish.Id), CreateModel(dish.Id, isDeleted: false));
}
[Test]
public void Try_AddElement_WhenHaveRecordWithSameId_Test()
{
var dish = CreateModel(Guid.NewGuid().ToString());
InsertDishToDatabaseAndReturn(dish.Id, dishName: "name unique");
Assert.That(() => _dishStorageContract.AddElement(dish), Throws.TypeOf<ElementExistsException>());
}
[Test]
public void Try_AddElement_WhenHaveRecordWithSameName_Test()
{
var dish = CreateModel(Guid.NewGuid().ToString(), "name unique", isDeleted: false);
InsertDishToDatabaseAndReturn(Guid.NewGuid().ToString(), dishName: dish.DishName, isDeleted: false);
Assert.That(() => _dishStorageContract.AddElement(dish), Throws.TypeOf<ElementExistsException>());
}
[Test]
public void Try_AddElement_WhenHaveRecordWithSameNameButOneWasDeleted_Test()
{
var dish = CreateModel(Guid.NewGuid().ToString(), "name unique", isDeleted: false);
InsertDishToDatabaseAndReturn(Guid.NewGuid().ToString(), dishName: dish.DishName, isDeleted: true);
Assert.That(() => _dishStorageContract.AddElement(dish), Throws.Nothing);
}
[Test]
public void Try_UpdElement_Test()
{
var dish = CreateModel(Guid.NewGuid().ToString(), isDeleted: false);
InsertDishToDatabaseAndReturn(dish.Id, isDeleted: false);
_dishStorageContract.UpdElement(dish);
AssertElement(GetDishFromDatabaseById(dish.Id), dish);
}
[Test]
public void Try_UpdElement_WhenIsDeletedIsTrue_Test()
{
var dish = CreateModel(Guid.NewGuid().ToString(), isDeleted: true);
InsertDishToDatabaseAndReturn(dish.Id, isDeleted: false);
_dishStorageContract.UpdElement(dish);
AssertElement(GetDishFromDatabaseById(dish.Id), CreateModel(dish.Id, isDeleted: false));
}
[Test]
public void Try_UpdElement_WhenNoRecordWithThisId_Test()
{
Assert.That(() => _dishStorageContract.UpdElement(CreateModel(Guid.NewGuid().ToString())), Throws.TypeOf<ElementNotFoundException>());
}
[Test]
public void Try_UpdElement_WhenHaveRecordWithSameName_Test()
{
var dish = CreateModel(Guid.NewGuid().ToString(), "name unique", isDeleted: false);
InsertDishToDatabaseAndReturn(dish.Id, dishName: "name");
InsertDishToDatabaseAndReturn(Guid.NewGuid().ToString(), dishName: dish.DishName);
Assert.That(() => _dishStorageContract.UpdElement(dish), Throws.TypeOf<ElementExistsException>());
}
[Test]
public void Try_UpdElement_WhenHaveRecordWithSameNameButOneWasDeleted_Test()
{
var dish = CreateModel(Guid.NewGuid().ToString(), "name unique", isDeleted: false);
InsertDishToDatabaseAndReturn(dish.Id, dishName: "name");
InsertDishToDatabaseAndReturn(Guid.NewGuid().ToString(), dishName: dish.DishName, isDeleted: true);
Assert.That(() => _dishStorageContract.UpdElement(dish), Throws.Nothing);
}
[Test]
public void Try_UpdElement_WhenRecordWasDeleted_Test()
{
var dish = CreateModel(Guid.NewGuid().ToString());
InsertDishToDatabaseAndReturn(dish.Id, isDeleted: true);
Assert.That(() => _dishStorageContract.UpdElement(dish), Throws.TypeOf<ElementNotFoundException>());
}
[Test]
public void Try_DelElement_Test()
{
var dish = InsertDishToDatabaseAndReturn(Guid.NewGuid().ToString(), isDeleted: false);
_dishStorageContract.DelElement(dish.Id);
var element = GetDishFromDatabaseById(dish.Id);
Assert.Multiple(() =>
{
Assert.That(element, Is.Not.Null);
Assert.That(element!.IsDeleted);
});
}
[Test]
public void Try_DelElement_WhenNoRecordWithThisId_Test()
{
Assert.That(() => _dishStorageContract.DelElement(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
}
[Test]
public void Try_DelElement_WhenRecordWasDeleted_Test()
{
var dish = InsertDishToDatabaseAndReturn(Guid.NewGuid().ToString(), isDeleted: true);
Assert.That(() => _dishStorageContract.DelElement(dish.Id), Throws.TypeOf<ElementNotFoundException>());
}
private Dish InsertDishToDatabaseAndReturn(string id, string dishName = "test", DishType dishType = DishType.Drink, double price = 1, bool isDeleted = false)
{
var dish = new Dish() { Id = id, DishName = dishName, DishType = dishType, Price = price, IsDeleted = isDeleted };
AndDietCokeDbContext.Dishes.Add(dish);
AndDietCokeDbContext.SaveChanges();
return dish;
}
private DishHistory InsertDishHistoryToDatabaseAndReturn(string dishId, double price, DateTime changeDate)
{
var dishHistory = new DishHistory() { Id = Guid.NewGuid().ToString(), DishId = dishId, OldPrice = price, ChangeDate = changeDate };
AndDietCokeDbContext.DishHistories.Add(dishHistory);
AndDietCokeDbContext.SaveChanges();
return dishHistory;
}
private static void AssertElement(DishDataModel? actual, Dish expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.Id, Is.EqualTo(expected.Id));
Assert.That(actual.DishName, Is.EqualTo(expected.DishName));
Assert.That(actual.DishType, Is.EqualTo(expected.DishType));
Assert.That(actual.Price, Is.EqualTo(expected.Price));
Assert.That(actual.IsDeleted, Is.EqualTo(expected.IsDeleted));
});
}
private static DishDataModel CreateModel(string id, string dishName = "test", DishType dishType = DishType.Drink, double price = 1, bool isDeleted = false)
=> new(id, dishName, dishType, price, isDeleted);
private Dish? GetDishFromDatabaseById(string id) => AndDietCokeDbContext.Dishes.FirstOrDefault(x => x.Id == id);
private static void AssertElement(Dish? actual, DishDataModel expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.Id, Is.EqualTo(expected.Id));
Assert.That(actual.DishName, Is.EqualTo(expected.DishName));
Assert.That(actual.DishType, Is.EqualTo(expected.DishType));
Assert.That(actual.Price, Is.EqualTo(expected.Price));
Assert.That(actual.IsDeleted, Is.EqualTo(expected.IsDeleted));
});
}
}

View File

@@ -0,0 +1,325 @@
using AndDietCokeContracts.DataModels;
using AndDietCokeContracts.Enums;
using AndDietCokeContracts.Exceptions;
using AndDietCokeContracts.StoragesContracts;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AndDietCokeDatabase.Implementations;
using Microsoft.EntityFrameworkCore;
using AndDietCokeDatabase.Models;
namespace AndDietCokeTests.StoragesContracts;
[TestFixture]
internal class PostStorageContractTests : BaseStorageContractTest
{
private PostStorageContract _postStorageContract;
[SetUp]
public void SetUp()
{
_postStorageContract = new PostStorageContract(AndDietCokeDbContext);
}
[TearDown]
public void TearDown()
{
AndDietCokeDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Posts\" CASCADE;");
}
[Test]
public void Try_GetList_WhenHaveRecords_Test()
{
var post = InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 1", PostType.Chef, 20, true, DateTime.MinValue);
InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 2", PostType.Chef, 20, true, DateTime.MinValue);
InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 3", PostType.Chef, 20, true, DateTime.MinValue);
var list = _postStorageContract.GetList();
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(3));
AssertElement(list.First(x => x.Id == post.Id), 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 nonExistentId = Guid.NewGuid().ToString();
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(nonExistentId);
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 = AndDietCokeDbContext.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.Waiter, 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 };
AndDietCokeDbContext.Posts.Add(post);
AndDietCokeDbContext.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.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));
});
}
private static PostDataModel CreateModel(string postId, string postName = "test", PostType postType = PostType.Waiter, double salary = 10, bool isActual = false, DateTime? changeDate = null)
=> new(postId, postName, postType, salary, isActual, changeDate ?? DateTime.UtcNow);
private Post? GetPostFromDatabaseByPostId(string id) => AndDietCokeDbContext.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,155 @@
using AndDietCokeContracts.DataModels;
using AndDietCokeContracts.StoragesContracts;
using AndDietCokeDatabase.Models;
using AndDietCokeDatabase.Implementations;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
namespace AndDietCokeTests.StoragesContracts;
[TestFixture]
internal class SalaryStorageContractTests : BaseStorageContractTest
{
private SalaryStorageContract _salaryStorageContract;
private Worker _worker;
[SetUp]
public void SetUp()
{
_salaryStorageContract = new SalaryStorageContract(AndDietCokeDbContext);
_worker = InsertWorkerToDatabaseAndReturn();
}
[TearDown]
public void TearDown()
{
AndDietCokeDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Salaries\" CASCADE;");
AndDietCokeDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Workers\" CASCADE;");
}
[Test]
public void Try_GetList_WhenHaveRecords_Test()
{
var salary = InsertSalaryToDatabaseAndReturn(_worker.Id, workerSalary: 100);
InsertSalaryToDatabaseAndReturn(_worker.Id);
InsertSalaryToDatabaseAndReturn(_worker.Id);
var list = _salaryStorageContract.GetList(DateTime.UtcNow.AddDays(-10), DateTime.UtcNow.AddDays(10));
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(3));
AssertElement(list.First(), salary);
}
[Test]
public void Try_GetList_WhenNoRecords_Test()
{
var list = _salaryStorageContract.GetList(DateTime.UtcNow.AddDays(-10), DateTime.UtcNow.AddDays(10));
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.Empty);
}
[Test]
public void Try_GetList_OnlyInDatePeriod_Test()
{
InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate: DateTime.UtcNow.AddDays(-2));
InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate: DateTime.UtcNow.AddDays(-1).AddMinutes(-5));
InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate: DateTime.UtcNow.AddDays(-1).AddMinutes(5));
InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate: DateTime.UtcNow.AddDays(1).AddMinutes(-5));
InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate: DateTime.UtcNow.AddDays(1).AddMinutes(5));
InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate: DateTime.UtcNow.AddDays(-2));
var list = _salaryStorageContract.GetList(DateTime.UtcNow.AddDays(-1), DateTime.UtcNow.AddDays(1));
Assert.That(list, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(list, Has.Count.EqualTo(2));
});
}
[Test]
public void Try_GetList_ByWorker_Test()
{
var worker = InsertWorkerToDatabaseAndReturn("name 2");
InsertSalaryToDatabaseAndReturn(_worker.Id);
InsertSalaryToDatabaseAndReturn(_worker.Id);
InsertSalaryToDatabaseAndReturn(worker.Id);
var list = _salaryStorageContract.GetList(DateTime.UtcNow.AddDays(-1), DateTime.UtcNow.AddDays(1), _worker.Id);
Assert.That(list, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(list, Has.Count.EqualTo(2));
Assert.That(list.All(x => x.WorkerId == _worker.Id));
});
}
[Test]
public void Try_GetList_ByWorkerOnlyInDatePeriod_Test()
{
var worker = InsertWorkerToDatabaseAndReturn("name 2");
InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate: DateTime.UtcNow.AddDays(-2));
InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate: DateTime.UtcNow.AddDays(-1).AddMinutes(5));
InsertSalaryToDatabaseAndReturn(worker.Id, salaryDate: DateTime.UtcNow.AddDays(-1).AddMinutes(5));
InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate: DateTime.UtcNow.AddDays(1).AddMinutes(-5));
InsertSalaryToDatabaseAndReturn(worker.Id, salaryDate: DateTime.UtcNow.AddDays(1).AddMinutes(-5));
InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate: DateTime.UtcNow.AddDays(-2));
var list = _salaryStorageContract.GetList(DateTime.UtcNow.AddDays(-1), DateTime.UtcNow.AddDays(1), _worker.Id);
Assert.That(list, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(list, Has.Count.EqualTo(2));
Assert.That(list.All(x => x.WorkerId == _worker.Id));
});
}
[Test]
public void Try_AddElement_Test()
{
var salary = CreateModel(_worker.Id);
_salaryStorageContract.AddElement(salary);
AssertElement(GetSalaryFromDatabaseByWorkerId(_worker.Id), salary);
}
private Worker InsertWorkerToDatabaseAndReturn(string workerFIO = "fio")
{
var worker = new Worker() { Id = Guid.NewGuid().ToString(), PostId = Guid.NewGuid().ToString(), FIO = workerFIO, IsDeleted = false };
AndDietCokeDbContext.Workers.Add(worker);
AndDietCokeDbContext.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 };
AndDietCokeDbContext.Salaries.Add(salary);
AndDietCokeDbContext.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) => AndDietCokeDbContext.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,298 @@
using AndDietCokeContracts.DataModels;
using AndDietCokeContracts.Exceptions;
using AndDietCokeContracts.StoragesContracts;
using AndDietCokeDatabase.Models;
using AndDietCokeDatabase.Implementations;
using NUnit.Framework;
using Microsoft.EntityFrameworkCore;
using AndDietCokeContracts.Enums;
namespace AndDietCokeTests.StoragesContracts;
[TestFixture]
internal class SaleStorageContractTests : BaseStorageContractTest
{
private SaleStorageContract _saletStorageContract;
private Buyer _buyer;
private Worker _worker;
private Dish _dish;
[SetUp]
public void SetUp()
{
_saletStorageContract = new SaleStorageContract(AndDietCokeDbContext);
_buyer = InsertBuyerToDatabaseAndReturn();
_worker = InsertWorkerToDatabaseAndReturn();
_dish = InsertDishToDatabaseAndReturn();
}
[TearDown]
public void TearDown()
{
AndDietCokeDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Sales\" CASCADE;");
AndDietCokeDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Buyers\" CASCADE;");
AndDietCokeDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Workers\" CASCADE;");
AndDietCokeDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Dishes\" CASCADE;");
}
[Test]
public void Try_GetList_WhenHaveRecords_Test()
{
var sale = InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, dishes: [(_dish.Id, 1)]);
InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, dishes: [(_dish.Id, 5)]);
InsertSaleToDatabaseAndReturn(_worker.Id, null, dishes: [(_dish.Id, 10)]);
var list = _saletStorageContract.GetList();
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(3));
AssertElement(list.First(x => x.Id == sale.Id), sale);
}
[Test]
public void Try_GetList_WhenNoRecords_Test()
{
var list = _saletStorageContract.GetList();
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.Empty);
}
[Test]
public void Try_GetList_ByPeriod_Test()
{
InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(-3), dishes: [(_dish.Id, 1)]);
InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(3), dishes: [(_dish.Id, 1)]);
InsertSaleToDatabaseAndReturn(_worker.Id, null, saleDate: DateTime.UtcNow.AddDays(1).AddMinutes(-3), dishes: [(_dish.Id, 1)]);
InsertSaleToDatabaseAndReturn(_worker.Id, null, saleDate: DateTime.UtcNow.AddDays(1).AddMinutes(3), dishes: [(_dish.Id, 1)]);
var list = _saletStorageContract.GetList(startDate: DateTime.UtcNow.AddDays(-1), endDate: DateTime.UtcNow.AddDays(1));
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(2));
}
[Test]
public void Try_GetList_ByWorkerId_Test()
{
var worker = InsertWorkerToDatabaseAndReturn("Other worker");
InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, dishes: [(_dish.Id, 1)]);
InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, dishes: [(_dish.Id, 1)]);
InsertSaleToDatabaseAndReturn(worker.Id, null, dishes: [(_dish.Id, 1)]);
var list = _saletStorageContract.GetList(workerId: _worker.Id);
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(2));
Assert.That(list.All(x => x.WorkerId == _worker.Id));
}
[Test]
public void Try_GetList_ByBuyerId_Test()
{
var buyer = InsertBuyerToDatabaseAndReturn("Other fio", "+8-888-888-88-88");
InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, dishes: [(_dish.Id, 1)]);
InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, dishes: [(_dish.Id, 1)]);
InsertSaleToDatabaseAndReturn(_worker.Id, buyer.Id, dishes: [(_dish.Id, 1)]);
InsertSaleToDatabaseAndReturn(_worker.Id, null, dishes: [(_dish.Id, 1)]);
var list = _saletStorageContract.GetList(buyerId: _buyer.Id);
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(2));
Assert.That(list.All(x => x.BuyerId == _buyer.Id));
}
[Test]
public void Try_GetList_ByDishId_Test()
{
var dish = InsertDishToDatabaseAndReturn("Other name");
InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, dishes: [(_dish.Id, 5)]);
InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, dishes: [(_dish.Id, 1), (dish.Id, 4)]);
InsertSaleToDatabaseAndReturn(_worker.Id, null, dishes: [(dish.Id, 1)]);
InsertSaleToDatabaseAndReturn(_worker.Id, null, dishes: [(dish.Id, 1), (_dish.Id, 1)]);
var list = _saletStorageContract.GetList(dishId: _dish.Id);
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(3));
Assert.That(list.All(x => x.Dishes.Any(y => y.DishId == _dish.Id)));
}
[Test]
public void Try_GetList_ByAllParameters_Test()
{
var worker = InsertWorkerToDatabaseAndReturn("Other worker");
var buyer = InsertBuyerToDatabaseAndReturn("Other fio", "+8-888-888-88-88");
var dish = InsertDishToDatabaseAndReturn("Other name");
InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(-3), dishes: [(_dish.Id, 1)]);
InsertSaleToDatabaseAndReturn(worker.Id, null, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(3), dishes: [(_dish.Id, 1)]);
InsertSaleToDatabaseAndReturn(worker.Id, _buyer.Id, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(3), dishes: [(_dish.Id, 1)]);
InsertSaleToDatabaseAndReturn(worker.Id, _buyer.Id, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(3), dishes: [(dish.Id, 1)]);
InsertSaleToDatabaseAndReturn(_worker.Id, buyer.Id, saleDate: DateTime.UtcNow.AddDays(1).AddMinutes(-3), dishes: [(_dish.Id, 1)]);
InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, saleDate: DateTime.UtcNow.AddDays(1).AddMinutes(-3), dishes: [(dish.Id, 1)]);
InsertSaleToDatabaseAndReturn(worker.Id, null, saleDate: DateTime.UtcNow.AddDays(1).AddMinutes(-3), dishes: [(_dish.Id, 1)]);
var list = _saletStorageContract.GetList(startDate: DateTime.UtcNow.AddDays(-1), endDate: DateTime.UtcNow.AddDays(1), workerId: _worker.Id, buyerId: _buyer.Id, dishId: dish.Id);
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(1));
}
[Test]
public void Try_GetElementById_WhenHaveRecord_Test()
{
var sale = InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, dishes: [(_dish.Id, 1)]);
AssertElement(_saletStorageContract.GetElementById(sale.Id), sale);
}
[Test]
public void Try_GetElementById_WhenNoRecord_Test()
{
InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, dishes: [(_dish.Id, 1)]);
Assert.That(() => _saletStorageContract.GetElementById(Guid.NewGuid().ToString()), Is.Null);
}
[Test]
public void Try_GetElementById_WhenRecordHasCanceled_Test()
{
var sale = InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, dishes: [(_dish.Id, 1)], isCancel: true);
AssertElement(_saletStorageContract.GetElementById(sale.Id), sale);
}
[Test]
public void Try_AddElement_Test()
{
var sale = CreateModel(Guid.NewGuid().ToString(), _worker.Id, _buyer.Id, 1, true, false, [_dish.Id]);
_saletStorageContract.AddElement(sale);
AssertElement(GetSaleFromDatabaseById(sale.Id), sale);
}
[Test]
public void Try_AddElement_WhenIsDeletedIsTrue_Test()
{
var sale = CreateModel(Guid.NewGuid().ToString(), _worker.Id, _buyer.Id, 1, true, false, [_dish.Id]);
Assert.That(() => _saletStorageContract.AddElement(sale), Throws.Nothing);
AssertElement(GetSaleFromDatabaseById(sale.Id), CreateModel(sale.Id, _worker.Id, _buyer.Id, 1, true, false, [_dish.Id]));
}
[Test]
public void Try_DelElement_Test()
{
var sale = InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, dishes: [(_dish.Id, 1)], isCancel: false);
_saletStorageContract.DelElement(sale.Id);
var element = GetSaleFromDatabaseById(sale.Id);
Assert.Multiple(() =>
{
Assert.That(element, Is.Not.Null);
Assert.That(element!.IsCancel);
});
}
[Test]
public void Try_DelElement_WhenNoRecordWithThisId_Test()
{
Assert.That(() => _saletStorageContract.DelElement(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
}
[Test]
public void Try_DelElement_WhenRecordWasCanceled_Test()
{
var sale = InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, dishes: [(_dish.Id, 1)], isCancel: true);
Assert.That(() => _saletStorageContract.DelElement(sale.Id), Throws.TypeOf<ElementDeletedException>());
}
private Buyer InsertBuyerToDatabaseAndReturn(string fio = "test", string phoneNumber = "+7-777-777-77-77")
{
var buyer = new Buyer() { Id = Guid.NewGuid().ToString(), FIO = fio, PhoneNumber = phoneNumber, DiscountSize = 10 };
AndDietCokeDbContext.Buyers.Add(buyer);
AndDietCokeDbContext.SaveChanges();
return buyer;
}
private Worker InsertWorkerToDatabaseAndReturn(string fio = "test")
{
var worker = new Worker() { Id = Guid.NewGuid().ToString(), FIO = fio, PostId = Guid.NewGuid().ToString() };
AndDietCokeDbContext.Workers.Add(worker);
AndDietCokeDbContext.SaveChanges();
return worker;
}
private Dish InsertDishToDatabaseAndReturn(string dishName = "test", DishType dishType = DishType.Base, double price = 1, bool isDeleted = false)
{
var dish = new Dish() { Id = Guid.NewGuid().ToString(), DishName = dishName, DishType = dishType, Price = price, IsDeleted = isDeleted };
AndDietCokeDbContext.Dishes.Add(dish);
AndDietCokeDbContext.SaveChanges();
return dish;
}
private Sale InsertSaleToDatabaseAndReturn(string workerId, string? buyerId, DateTime? saleDate = null, double sum = 1, bool isConstantClient = true, bool isCancel = false, List<(string, int)>? dishes = null)
{
var sale = new Sale() { WorkerId = workerId, BuyerId = buyerId, SaleDate = saleDate ?? DateTime.UtcNow, Sum = sum, IsConstantClient = isConstantClient, IsCancel = isCancel, OrderDishes = [] };
if (dishes is not null)
{
foreach (var elem in dishes)
{
sale.OrderDishes.Add(new OrderDish { DishId = elem.Item1, OrderId = sale.Id, Count = elem.Item2 });
}
}
AndDietCokeDbContext.Sales.Add(sale);
AndDietCokeDbContext.SaveChanges();
return sale;
}
private static void AssertElement(SaleDataModel? actual, Sale expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.Id, Is.EqualTo(expected.Id));
Assert.That(actual.WorkerId, Is.EqualTo(expected.WorkerId));
Assert.That(actual.BuyerId, Is.EqualTo(expected.BuyerId));
Assert.That(actual.IsCancel, Is.EqualTo(expected.IsCancel));
});
if (expected.OrderDishes is not null)
{
Assert.That(actual.Dishes, Is.Not.Null);
Assert.That(actual.Dishes, Has.Count.EqualTo(expected.OrderDishes.Count));
for (int i = 0; i < actual.Dishes.Count; ++i)
{
Assert.Multiple(() =>
{
Assert.That(actual.Dishes[i].DishId, Is.EqualTo(expected.OrderDishes[i].DishId));
Assert.That(actual.Dishes[i].Count, Is.EqualTo(expected.OrderDishes[i].Count));
});
}
}
else
{
Assert.That(actual.Dishes, Is.Null);
}
}
private static SaleDataModel CreateModel(string id, string workerId, string? buyerId, double sum, bool isConstantClient, bool isCancel, List<string> dishIds)
{
var dishes = dishIds.Select(x => new OrderDishDataModel(id, x, 1)).ToList();
return new(id, workerId, buyerId, sum, isConstantClient, isCancel, dishes);
}
private Sale? GetSaleFromDatabaseById(string id) => AndDietCokeDbContext.Sales.Include(x => x.OrderDishes).FirstOrDefault(x => x.Id == id);
private static void AssertElement(Sale? actual, SaleDataModel expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.Id, Is.EqualTo(expected.Id));
Assert.That(actual.WorkerId, Is.EqualTo(expected.WorkerId));
Assert.That(actual.BuyerId, Is.EqualTo(expected.BuyerId));
Assert.That(actual.IsCancel, Is.EqualTo(expected.IsCancel));
});
if (expected.Dishes is not null)
{
Assert.That(actual.OrderDishes, Is.Not.Null);
Assert.That(actual.OrderDishes, Has.Count.EqualTo(expected.Dishes.Count));
for (int i = 0; i < actual.OrderDishes.Count; ++i)
{
Assert.Multiple(() =>
{
Assert.That(actual.OrderDishes[i].DishId, Is.EqualTo(expected.Dishes[i].DishId));
Assert.That(actual.OrderDishes[i].Count, Is.EqualTo(expected.Dishes[i].Count));
});
}
}
else
{
Assert.That(actual.OrderDishes, Is.Null);
}
}
}

View File

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