12 Commits

Author SHA1 Message Date
3c4b226736 что-то последнее 2025-04-11 15:57:50 +04:00
4190d6516a что-то еще 2025-04-10 14:46:52 +04:00
e15838f479 что-то 2025-04-10 13:12:41 +04:00
dd2cd0d2fb Тесты 2025-04-05 19:43:06 +04:00
f0e2f4f781 Модели 2025-04-05 16:36:23 +04:00
58aa5accf3 Последние изменения 2025-03-27 14:35:58 +04:00
1176597c24 Последние изменения 2025-03-27 12:57:25 +04:00
866c5c2a00 Последние изменения 2025-03-27 01:03:08 +04:00
6675880e03 Тесты + еще по мелочи 2025-03-26 17:36:36 +04:00
e2dcb86b02 Изменение по должности 2025-03-13 13:40:15 +04:00
bcde0d8310 Заготовки реализаций 2025-03-13 13:23:30 +04:00
d29912621f Контракты 2025-03-13 12:23:17 +04:00
63 changed files with 6301 additions and 24 deletions

View File

@@ -0,0 +1,28 @@
<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="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>
<ProjectReference Include="..\AndDietCokeProject\AndDietCokeContracts.csproj" />
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="AndDietCokeTests" />
<InternalsVisibleTo Include="DynamicProxyGenAssembly2" />
</ItemGroup>
</Project>

View File

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

View File

@@ -0,0 +1,80 @@
using AndDietCokeContracts.BisnessLogicsContracts;
using AndDietCokeContracts.DataModels;
using AndDietCokeContracts.Enums;
using AndDietCokeContracts.Exceptions;
using AndDietCokeContracts.Extensions;
using AndDietCokeContracts.StoragesContracts;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
namespace AndDietCokeBuisnessLogic.Implementations;
internal class DishBusinessLogicContract(IDishStorageContract dishStorageContract, ILogger logger) : IDishBusinessLogicContract
{
private readonly ILogger _logger = logger;
private readonly IDishStorageContract _dishStorageContract = dishStorageContract;
public List<DishDataModel> GetAllDishes(bool onlyActive)
{
_logger.LogInformation("GetAllDishes params: {onlyActive}", onlyActive);
return _dishStorageContract.GetList(onlyActive) ?? throw new NullListException();
}
public List<DishHistoryDataModel> GetDishHistoryByDish(string dishId)
{
_logger.LogInformation("GetProductHistoryByProduct for {dishId}", dishId);
if (dishId.IsEmpty())
{
throw new ArgumentNullException(nameof(dishId));
}
if (!dishId.IsGuid())
{
throw new ValidationException("The value in the field dishId is not a unique identifier.");
}
return _dishStorageContract.GetHistoryByDishId(dishId) ?? throw new NullListException();
}
public DishDataModel GetDishByData(string data)
{
_logger.LogInformation("Get element by data: {data}", data);
if (data.IsEmpty())
{
throw new ArgumentNullException(nameof(data));
}
if (data.IsGuid())
{
return _dishStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data);
}
return _dishStorageContract.GetElementByName(data) ?? throw new ElementNotFoundException(data);
}
public void InsertDish(DishDataModel dishDataModel)
{
_logger.LogInformation("New data: {json}", JsonSerializer.Serialize(dishDataModel));
ArgumentNullException.ThrowIfNull(dishDataModel);
dishDataModel.Validate();
_dishStorageContract.AddElement(dishDataModel);
}
public void UpdateDish(DishDataModel dishDataModel)
{
_logger.LogInformation("Update data: {json}", JsonSerializer.Serialize(dishDataModel));
ArgumentNullException.ThrowIfNull(dishDataModel);
dishDataModel.Validate();
_dishStorageContract.UpdElement(dishDataModel);
}
public void DeleteDish(string id)
{
_logger.LogInformation("Delete by id: {id}", id);
if (id.IsEmpty())
{
throw new ArgumentNullException(nameof(id));
}
if (!id.IsGuid())
{
throw new ValidationException("Id is not a unique identifier");
}
_dishStorageContract.DelElement(id);
}
}

View File

@@ -0,0 +1,99 @@
using AndDietCokeContracts.BisnessLogicsContracts;
using AndDietCokeContracts.DataModels;
using AndDietCokeContracts.Enums;
using AndDietCokeContracts.Exceptions;
using AndDietCokeContracts.Extensions;
using AndDietCokeContracts.StoragesContracts;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
namespace AndDietCokeBuisnessLogic.Implementations;
public class PostBusinessLogicContract(IPostStorageContract postStorageContract, ILogger logger) : IPostBusinessLogicContract
{
private readonly ILogger _logger = logger;
private readonly IPostStorageContract _postStorageContract = postStorageContract;
public List<PostDataModel> GetAllPosts(bool onlyActive = true)
{
_logger.LogInformation("GetAllPosts params: {onlyActive}", onlyActive);
return _postStorageContract.GetList(onlyActive) ?? throw new NullListException();
}
public List<PostDataModel> GetAllDataOfPost(string postId)
{
_logger.LogInformation("GetAllDataOfPost for {postId}", postId);
if (postId.IsEmpty())
{
throw new ArgumentNullException(nameof(postId));
}
if (!postId.IsGuid())
{
throw new ValidationException("The value in the field postId is not a unique identifier.");
}
return _postStorageContract.GetPostWithHistory(postId) ?? throw new NullListException();
}
public PostDataModel GetPostByData(string data)
{
_logger.LogInformation("Get element by data: {data}", data);
if (data.IsEmpty())
{
throw new ArgumentNullException(nameof(data));
}
if (data.IsGuid())
{
return _postStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data);
}
return _postStorageContract.GetElementByName(data) ?? throw new ElementNotFoundException(data);
}
public void InsertPost(PostDataModel postDataModel)
{
_logger.LogInformation("New data: {json}", JsonSerializer.Serialize(postDataModel));
ArgumentNullException.ThrowIfNull(postDataModel);
postDataModel.Validate();
_postStorageContract.AddElement(postDataModel);
}
public void UpdatePost(PostDataModel postDataModel)
{
_logger.LogInformation("Update data: {json}", JsonSerializer.Serialize(postDataModel));
ArgumentNullException.ThrowIfNull(postDataModel);
postDataModel.Validate();
_postStorageContract.UpdElement(postDataModel);
}
public void DeletePost(string id)
{
_logger.LogInformation("Delete by id: {id}", id);
if (id.IsEmpty())
{
throw new ArgumentNullException(nameof(id));
}
if (!id.IsGuid())
{
throw new ValidationException("Id is not a unique identifier");
}
_postStorageContract.DelElement(id);
}
public void RestorePost(string id)
{
_logger.LogInformation("Restore by id: {id}", id);
if (id.IsEmpty())
{
throw new ArgumentNullException(nameof(id));
}
if (!id.IsGuid())
{
throw new ValidationException("Id is not a unique identifier");
}
_postStorageContract.ResElement(id);
}
}

View File

@@ -0,0 +1,71 @@
using AndDietCokeContracts.BisnessLogicsContracts;
using AndDietCokeContracts.DataModels;
using AndDietCokeContracts.Exceptions;
using AndDietCokeContracts.Extensions;
using AndDietCokeContracts.StoragesContracts;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static AndDietCokeBuisnessLogic.Implementations.SalaryBusinessLogicContract;
namespace AndDietCokeBuisnessLogic.Implementations;
internal class SalaryBusinessLogicContract(ISalaryStorageContract salaryStorageContract,
ISaleStorageContract saleStorageContract, IPostStorageContract postStorageContract, IWorkerStorageContract workerStorageContract, ILogger logger) : ISalaryBusinessLogicContract
{
private readonly ILogger _logger = logger;
private readonly ISalaryStorageContract _salaryStorageContract = salaryStorageContract;
private readonly ISaleStorageContract _saleStorageContract = saleStorageContract;
private readonly IPostStorageContract _postStorageContract = postStorageContract;
private readonly IWorkerStorageContract _workerStorageContract = workerStorageContract;
public List<SalaryDataModel> GetAllSalariesByPeriod(DateTime fromDate, DateTime toDate)
{
_logger.LogInformation("GetAllSalaries params: {fromDate}, {toDate}", fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate);
}
return _salaryStorageContract.GetList(fromDate, toDate) ?? throw new NullListException();
}
public List<SalaryDataModel> GetAllSalariesByPeriodByWorker(DateTime fromDate, DateTime toDate, string workerId)
{
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate);
}
if (workerId.IsEmpty())
{
throw new ArgumentNullException(nameof(workerId));
}
if (!workerId.IsGuid())
{
throw new ValidationException("The value in the field workerId is not a unique identifier.");
}
_logger.LogInformation("GetAllSalaries params: {fromDate}, {toDate}, {workerId}", fromDate, toDate, workerId);
return _salaryStorageContract.GetList(fromDate, toDate, workerId) ?? throw new NullListException();
}
public void CalculateSalaryByMounth(DateTime date)
{
_logger.LogInformation("CalculateSalaryByMounth: {date}", date);
var startDate = new DateTime(date.Year, date.Month, 1);
var finishDate = new DateTime(date.Year, date.Month, DateTime.DaysInMonth(date.Year, date.Month));
var workers = _workerStorageContract.GetList() ?? throw new NullListException();
foreach (var worker in workers)
{
var sales = _saleStorageContract.GetList(startDate, finishDate, workerId: worker.Id)?.Sum(x => x.Sum) ??
throw new NullListException();
var post = _postStorageContract.GetElementById(worker.PostId) ??
throw new NullListException();
var salary = post.Salary + sales * 0.1;
_logger.LogDebug("The employee {workerId} was paid a salary of {salary}", worker.Id, salary);
_salaryStorageContract.AddElement(new SalaryDataModel(worker.Id, finishDate, salary));
}
}
}

View File

@@ -0,0 +1,120 @@
using AndDietCokeContracts.BisnessLogicsContracts;
using AndDietCokeContracts.DataModels;
using AndDietCokeContracts.Exceptions;
using AndDietCokeContracts.Extensions;
using AndDietCokeContracts.StoragesContracts;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
namespace AndDietCokeBuisnessLogic.Implementations;
internal class SaleBusinessLogicContract(ISaleStorageContract saleStorageContract, ILogger logger) : ISaleBusinessLogicContract
{
private readonly ILogger _logger = logger;
private readonly ISaleStorageContract _saleStorageContract = saleStorageContract;
public List<SaleDataModel> GetAllSalesByPeriod(DateTime fromDate, DateTime toDate)
{
_logger.LogInformation("GetAllSales params: {fromDate}, {toDate}", fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate);
}
return _saleStorageContract.GetList(fromDate, toDate) ?? throw new NullListException();
}
public List<SaleDataModel> GetAllSalesByWorkerByPeriod(string workerId, DateTime fromDate, DateTime toDate)
{
_logger.LogInformation("GetAllSales params: {workerId}, {fromDate}, {toDate}", workerId, fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate);
}
if (workerId.IsEmpty())
{
throw new ArgumentNullException(nameof(workerId));
}
if (!workerId.IsGuid())
{
throw new ValidationException("The value in the field workerId is not a unique identifier.");
}
return _saleStorageContract.GetList(fromDate, toDate, workerId: workerId) ?? throw new NullListException();
}
public List<SaleDataModel> GetAllSalesByBuyerByPeriod(string buyerId, DateTime fromDate, DateTime toDate)
{
_logger.LogInformation("GetAllSales params: {buyerId}, {fromDate}, {toDate}", buyerId, fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate);
}
if (buyerId.IsEmpty())
{
throw new ArgumentNullException(nameof(buyerId));
}
if (!buyerId.IsGuid())
{
throw new ValidationException("The value in the field buyerId is not a unique identifier.");
}
return _saleStorageContract.GetList(fromDate, toDate, buyerId: buyerId) ?? throw new NullListException();
}
public List<SaleDataModel> GetAllSalesByDishByPeriod(string dishId, DateTime fromDate, DateTime toDate)
{
_logger.LogInformation("GetAllSales params: {dishId}, {fromDate}, {toDate}", dishId, fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate);
}
if (dishId.IsEmpty())
{
throw new ArgumentNullException(nameof(dishId));
}
if (!dishId.IsGuid())
{
throw new ValidationException("The value in the field productId is not a unique identifier.");
}
return _saleStorageContract.GetList(fromDate, toDate, productId: dishId) ?? throw new NullListException();
}
public SaleDataModel GetSaleByData(string data)
{
_logger.LogInformation("Get element by data: {data}", data);
if (data.IsEmpty())
{
throw new ArgumentNullException(nameof(data));
}
if (!data.IsGuid())
{
throw new ValidationException("Id is not a unique identifier");
}
return _saleStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data);
}
public void InsertSale(SaleDataModel saleDataModel)
{
_logger.LogInformation("New data: {json}", JsonSerializer.Serialize(saleDataModel));
ArgumentNullException.ThrowIfNull(saleDataModel);
saleDataModel.Validate();
_saleStorageContract.AddElement(saleDataModel);
}
public void CancelSale(string id)
{
_logger.LogInformation("Cancel by id: {id}", id);
if (id.IsEmpty())
{
throw new ArgumentNullException(nameof(id));
}
if (!id.IsGuid())
{
throw new ValidationException("Id is not a unique identifier");
}
_saleStorageContract.DelElement(id);
}
}

View File

@@ -0,0 +1,104 @@
using AndDietCokeContracts.BisnessLogicsContracts;
using AndDietCokeContracts.DataModels;
using AndDietCokeContracts.Exceptions;
using AndDietCokeContracts.Extensions;
using AndDietCokeContracts.StoragesContracts;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
namespace AndDietCokeBuisnessLogic.Implementations;
internal class WorkerBusinessLogicContract(IWorkerStorageContract workerStorageContract, ILogger logger) : IWorkerBusinessLogicContract
{
private readonly ILogger _logger = logger;
private readonly IWorkerStorageContract _workerStorageContract = workerStorageContract;
public List<WorkerDataModel> GetAllWorkers(bool onlyActive = true)
{
_logger.LogInformation("GetAllWorkers params: {onlyActive}", onlyActive);
return _workerStorageContract.GetList(onlyActive) ?? throw new NullListException();
}
public List<WorkerDataModel> GetAllWorkersByPost(string postId, bool onlyActive = true)
{
_logger.LogInformation("GetAllWorkers params: {postId}, {onlyActive},", postId, onlyActive);
if (postId.IsEmpty())
{
throw new ArgumentNullException(nameof(postId));
}
if (!postId.IsGuid())
{
throw new ValidationException("The value in the field postId is not a unique identifier.");
}
return _workerStorageContract.GetList(onlyActive, postId) ?? throw new NullListException();
}
public List<WorkerDataModel> GetAllWorkersByBirthDate(DateTime fromDate, DateTime toDate, bool onlyActive = true)
{
_logger.LogInformation("GetAllWorkers params: {onlyActive}, {fromDate}, {toDate}", onlyActive, fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate);
}
return _workerStorageContract.GetList(onlyActive, fromBirthDate: fromDate, toBirthDate: toDate) ?? throw new NullListException();
}
public List<WorkerDataModel> GetAllWorkersByEmploymentDate(DateTime fromDate, DateTime toDate, bool onlyActive = true)
{
_logger.LogInformation("GetAllWorkers params: {onlyActive}, {fromDate}, {toDate}", onlyActive, fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate);
}
return _workerStorageContract.GetList(onlyActive, fromEmploymentDate: fromDate, toEmploymentDate: toDate) ?? throw new NullListException();
}
public WorkerDataModel GetWorkerByData(string data)
{
_logger.LogInformation("Get element by data: {data}", data);
if (data.IsEmpty())
{
throw new ArgumentNullException(nameof(data));
}
if (data.IsGuid())
{
return _workerStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data);
}
return _workerStorageContract.GetElementByFIO(data) ?? throw new ElementNotFoundException(data);
}
public void InsertWorker(WorkerDataModel workerDataModel)
{
_logger.LogInformation("New data: {json}", JsonSerializer.Serialize(workerDataModel));
ArgumentNullException.ThrowIfNull(workerDataModel);
workerDataModel.Validate();
_workerStorageContract.AddElement(workerDataModel);
}
public void UpdateWorker(WorkerDataModel workerDataModel)
{
_logger.LogInformation("Update data: {json}", JsonSerializer.Serialize(workerDataModel));
ArgumentNullException.ThrowIfNull(workerDataModel);
workerDataModel.Validate();
_workerStorageContract.UpdElement(workerDataModel);
}
public void DeleteWorker(string id)
{
_logger.LogInformation("Delete by id: {id}", id);
if (id.IsEmpty())
{
throw new ArgumentNullException(nameof(id));
}
if (!id.IsGuid())
{
throw new ValidationException("Id is not a unique identifier");
}
_workerStorageContract.DelElement(id);
}
}

View File

@@ -0,0 +1,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

@@ -5,7 +5,14 @@ VisualStudioVersion = 17.7.34024.191
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AndDietCokeContracts", "AndDietCokeProject\AndDietCokeContracts.csproj", "{624595D1-D7AA-4448-AA30-4D5AA21AE6D6}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AndDietCokeTests", "AndDietCokeTests\AndDietCokeTests.csproj", "{EABA3AD5-7690-448A-BEE6-010499DD8790}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AndDietCokeTests", "AndDietCokeTests\AndDietCokeTests.csproj", "{EABA3AD5-7690-448A-BEE6-010499DD8790}"
EndProject
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
@@ -21,6 +28,14 @@ Global
{EABA3AD5-7690-448A-BEE6-010499DD8790}.Debug|Any CPU.Build.0 = Debug|Any CPU
{EABA3AD5-7690-448A-BEE6-010499DD8790}.Release|Any CPU.ActiveCfg = Release|Any CPU
{EABA3AD5-7690-448A-BEE6-010499DD8790}.Release|Any CPU.Build.0 = Release|Any CPU
{3C1C0E8F-5CB4-4E93-B20C-86FF4B248ECF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{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

@@ -0,0 +1,18 @@
using AndDietCokeContracts.DataModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AndDietCokeContracts.BisnessLogicsContracts;
public interface IBuyerBusinessLogicContract
{
List<BuyerDataModel> GetAllBuyers();
BuyerDataModel GetBuyerByData(string data);
void InsertBuyer(BuyerDataModel buyerDataModel);
void UpdateBuyer(BuyerDataModel buyerDataModel);
void DeleteBuyer(string id);
}

View File

@@ -0,0 +1,19 @@
using AndDietCokeContracts.DataModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AndDietCokeContracts.BisnessLogicsContracts;
public interface IDishBusinessLogicContract
{
List<DishDataModel> GetAllDishes(bool onlyActive = true);
List<DishHistoryDataModel> GetDishHistoryByDish(string dishId);
DishDataModel GetDishByData(string data);
void InsertDish(DishDataModel dishDataModel);
void UpdateDish(DishDataModel dishDataModel);
void DeleteDish(string id);
}

View File

@@ -0,0 +1,20 @@
using AndDietCokeContracts.DataModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AndDietCokeContracts.BisnessLogicsContracts;
public interface IPostBusinessLogicContract
{
List<PostDataModel> GetAllPosts(bool onlyActive);
List<PostDataModel> GetAllDataOfPost(string postId);
PostDataModel GetPostByData(string data);
void InsertPost(PostDataModel postDataModel);
void UpdatePost(PostDataModel postDataModel);
void DeletePost(string id);
void RestorePost(string id);
}

View File

@@ -0,0 +1,15 @@
using AndDietCokeContracts.DataModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AndDietCokeContracts.BisnessLogicsContracts;
public interface ISalaryBusinessLogicContract
{
List<SalaryDataModel> GetAllSalariesByPeriod(DateTime fromDate, DateTime toDate);
List<SalaryDataModel> GetAllSalariesByPeriodByWorker(DateTime fromDate, DateTime toDate, string workerId);
void CalculateSalaryByMounth(DateTime date);
}

View File

@@ -0,0 +1,20 @@
using AndDietCokeContracts.DataModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AndDietCokeContracts.BisnessLogicsContracts;
public interface ISaleBusinessLogicContract
{
List<SaleDataModel> GetAllSalesByPeriod(DateTime fromDate, DateTime toDate);
List<SaleDataModel> GetAllSalesByWorkerByPeriod(string workerId, DateTime fromDate, DateTime toDate);
List<SaleDataModel> GetAllSalesByBuyerByPeriod(string buyerId, DateTime fromDate, DateTime toDate);
List<SaleDataModel> GetAllSalesByDishByPeriod(string dishId, DateTime fromDate, DateTime toDate);
SaleDataModel GetSaleByData(string data);
void InsertSale(SaleDataModel saleDataModel);
void CancelSale(string id);
}

View File

@@ -0,0 +1,20 @@
using AndDietCokeContracts.DataModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AndDietCokeContracts.BisnessLogicsContracts;
public interface IWorkerBusinessLogicContract
{
List<WorkerDataModel> GetAllWorkers(bool onlyActive = true);
List<WorkerDataModel> GetAllWorkersByPost(string postId, bool onlyActive = true);
List<WorkerDataModel> GetAllWorkersByBirthDate(DateTime fromDate, DateTime toDate, bool onlyActive = true);
List<WorkerDataModel> GetAllWorkersByEmploymentDate(DateTime fromDate, DateTime toDate, bool onlyActive = true);
WorkerDataModel GetWorkerByData(string data);
void InsertWorker(WorkerDataModel workerDataModel);
void UpdateWorker(WorkerDataModel workerDataModel);
void DeleteWorker(string id);
}

View File

@@ -11,11 +11,10 @@ using System.Xml;
namespace AndDietCokeContracts.DataModels;
public class PostDataModel(string id, string postId, string postName, PostType
public class PostDataModel(string id, string postName, PostType
postType, double salary, bool isActual, DateTime changeDate) : IValidation
{
public string Id { get; private set; } = id;
public string PostId { get; private set; } = postId;
public string PostName { get; private set; } = postName;
public PostType PostType { get; private set; } = postType;
public double Salary { get; private set; } = salary;
@@ -27,10 +26,6 @@ postType, double salary, bool isActual, DateTime changeDate) : IValidation
throw new ValidationException("Field Id is empty");
if (!Id.IsGuid())
throw new ValidationException("The value in the field Id is not a unique identifier");
if (PostId.IsEmpty())
throw new ValidationException("Field PostId is empty");
if (!PostId.IsGuid())
throw new ValidationException("The value in the field PostId is not a unique identifier");
if (PostName.IsEmpty())
throw new ValidationException("Field PostName is empty");
if (PostType == PostType.None)

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,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AndDietCokeContracts.Exceptions;
public class ElementExistsException : Exception
{
public string ParamName { get; private set; }
public string ParamValue { get; private set; }
public ElementExistsException(string paramName, string paramValue) : base($"There is already an element with value{paramValue} of parameter { paramName}")
{
ParamName = paramName;
ParamValue = paramValue;
}
}

View File

@@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AndDietCokeContracts.Exceptions;
public class ElementNotFoundException : Exception
{
public string Value { get; private set; }
public ElementNotFoundException(string value) : base($"Element not found at value = { value}")
{
Value = value;
}
}

View File

@@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Runtime.InteropServices.JavaScript.JSType;
namespace AndDietCokeContracts.Exceptions;
public class IncorrectDatesException : Exception
{
public IncorrectDatesException(DateTime start, DateTime end) : base($"The end date must be later than the start date..StartDate: { start: dd.MM.YYYY}. EndDate: {end:dd.MM.YYYY}") { }
}

View File

@@ -0,0 +1,12 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AndDietCokeContracts.Exceptions;
public class NullListException : Exception
{
public NullListException() : base("The returned list is null") { }
}

View File

@@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AndDietCokeContracts.Exceptions;
public class StorageException : Exception
{
public StorageException(Exception ex) : base($"Error while working in storage: { ex.Message}", ex) { }
}

View File

@@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AndDietCokeContracts.Extensions;
public static class DateTimeExtensions
{
public static bool IsDateNotOlder(this DateTime date, DateTime olderDate)
{
return date >= olderDate;
}
}

View File

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

View File

@@ -0,0 +1,19 @@
using AndDietCokeContracts.DataModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AndDietCokeContracts.StoragesContracts;
public interface IBuyerStorageContract
{
List<BuyerDataModel> GetList();
BuyerDataModel? GetElementById(string id);
BuyerDataModel? GetElementByPhoneNumber(string phoneNumber);
BuyerDataModel? GetElementByFIO(string fio);
void AddElement(BuyerDataModel buyerDataModel);
void UpdElement(BuyerDataModel buyerDataModel);
void DelElement(string id);
}

View File

@@ -0,0 +1,18 @@
using AndDietCokeContracts.DataModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AndDietCokeContracts.StoragesContracts;
public interface IDishStorageContract
{
List<DishDataModel> GetList(bool onlyActive = true);
List<DishHistoryDataModel> GetHistoryByDishId(string dishId);
DishDataModel? GetElementById(string id);
DishDataModel? GetElementByName(string name);
void AddElement(DishDataModel dishDataModel);
void UpdElement(DishDataModel dishDataModel);
void DelElement(string id);
}

View File

@@ -0,0 +1,21 @@
using AndDietCokeContracts.DataModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AndDietCokeContracts.StoragesContracts;
public interface IPostStorageContract
{
List<PostDataModel> GetList(bool onlyActual = true);
List<PostDataModel> GetPostWithHistory(string postId);
PostDataModel? GetElementById(string id);
PostDataModel? GetElementByName(string name);
void AddElement(PostDataModel postDataModel);
void UpdElement(PostDataModel postDataModel);
void DelElement(string id);
void ResElement(string id);
}

View File

@@ -0,0 +1,15 @@
using AndDietCokeContracts.DataModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AndDietCokeContracts.StoragesContracts;
public interface ISalaryStorageContract
{
List<SalaryDataModel> GetList(DateTime startDate, DateTime endDate, string?
workerId = null);
void AddElement(SalaryDataModel salaryDataModel);
}

View File

@@ -0,0 +1,17 @@
using AndDietCokeContracts.DataModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AndDietCokeContracts.StoragesContracts;
public interface ISaleStorageContract
{
List<SaleDataModel> GetList(DateTime? startDate = null, DateTime? endDate = null, string? workerId = null, string? buyerId = null, string? productId = null);
SaleDataModel? GetElementById(string id);
void AddElement(SaleDataModel saleDataModel);
void DelElement(string id);
}

View File

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

View File

@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
@@ -7,10 +7,18 @@
<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
<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="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" />
@@ -18,6 +26,8 @@
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\AndDietCokeBuisnessLogic\AndDietCokeBuisnessLogic.csproj" />
<ProjectReference Include="..\AndDietCokeDatabase\AndDietCokeDatabase.csproj" />
<ProjectReference Include="..\AndDietCokeProject\AndDietCokeContracts.csproj" />
</ItemGroup>

View File

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

View File

@@ -0,0 +1,404 @@
using AndDietCokeContracts.Exceptions;
using AndDietCokeBuisnessLogic.Implementations;
using AndDietCokeContracts.StoragesContracts;
using AndDietCokeContracts.DataModels;
using AndDietCokeContracts.Enums;
using Moq;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Extensions.Logging;
using System.Threading.Tasks;
using static NUnit.Framework.Internal.OSPlatform;
namespace AndDietCokeTests.BuisnessLogicsContractsTests;
internal class DishBusinessLogicContractTests
{
private DishBusinessLogicContract _dishBusinessLogicContract;
private Mock<IDishStorageContract> _dishStorageContract;
[OneTimeSetUp]
public void OneTimeSetUp()
{
_dishStorageContract = new Mock<IDishStorageContract>();
_dishBusinessLogicContract = new DishBusinessLogicContract(_dishStorageContract.Object, new Mock<ILogger>().Object);
}
[SetUp]
public void SetUp()
{
_dishStorageContract.Reset();
}
[Test]
public void GetAllDishes_ReturnListOfRecords_Test()
{
//Arrange
var listOriginal = new List<DishDataModel>()
{
new(Guid.NewGuid().ToString(), "name 1", DishType.Dessert, 10, false),
new(Guid.NewGuid().ToString(), "name 2", DishType.Dessert, 10, true),
new(Guid.NewGuid().ToString(), "name 3", DishType.Dessert, 10, false),
};
_dishStorageContract.Setup(x => x.GetList(It.IsAny<bool>())).Returns(listOriginal);
//Act
var listOnlyActive = _dishBusinessLogicContract.GetAllDishes(true);
var list = _dishBusinessLogicContract.GetAllDishes(false);
//Assert
Assert.Multiple(() =>
{
Assert.That(listOnlyActive, Is.Not.Null);
Assert.That(list, Is.Not.Null);
Assert.That(listOnlyActive, Is.EquivalentTo(listOriginal));
Assert.That(list, Is.EquivalentTo(listOriginal));
});
_dishStorageContract.Verify(x => x.GetList(true), Times.Once);
_dishStorageContract.Verify(x => x.GetList(false), Times.Once);
}
[Test]
public void GetAllDishes_ReturnEmptyList_Test()
{
//Arrange
_dishStorageContract.Setup(x => x.GetList(It.IsAny<bool>())).Returns([]);
//Act
var listOnlyActive = _dishBusinessLogicContract.GetAllDishes(true);
var list = _dishBusinessLogicContract.GetAllDishes(false);
//Assert
Assert.Multiple(() =>
{
Assert.That(listOnlyActive, Is.Not.Null);
Assert.That(list, Is.Not.Null);
Assert.That(listOnlyActive, Has.Count.EqualTo(0));
Assert.That(list, Has.Count.EqualTo(0));
});
_dishStorageContract.Verify(x => x.GetList(It.IsAny<bool>()), Times.Exactly(2));
}
[Test]
public void GetAllDishes_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _dishBusinessLogicContract.GetAllDishes(It.IsAny<bool>()), Throws.TypeOf<NullListException>());
_dishStorageContract.Verify(x => x.GetList(It.IsAny<bool>()), Times.Once);
}
[Test]
public void GetAllDishes_StorageThrowError_ThrowException_Test()
{
//Arrange
_dishStorageContract.Setup(x => x.GetList(It.IsAny<bool>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _dishBusinessLogicContract.GetAllDishes(It.IsAny<bool>()), Throws.TypeOf<StorageException>());
_dishStorageContract.Verify(x => x.GetList(It.IsAny<bool>()), Times.Once);
}
[Test]
public void GetDishHistoryByDish_ReturnListOfRecords_Test()
{
//Arrange
var dishId = Guid.NewGuid().ToString();
var listOriginal = new List<DishHistoryDataModel>()
{
new(Guid.NewGuid().ToString(), 10),
new(Guid.NewGuid().ToString(), 15),
new(Guid.NewGuid().ToString(), 10),
};
_dishStorageContract.Setup(x => x.GetHistoryByDishId(It.IsAny<string>())).Returns(listOriginal);
//Act
var list = _dishBusinessLogicContract.GetDishHistoryByDish(dishId);
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.EquivalentTo(listOriginal));
_dishStorageContract.Verify(x => x.GetHistoryByDishId(dishId), Times.Once);
}
[Test]
public void GetDishHistoryByDish_ReturnEmptyList_Test()
{
//Arrange
_dishStorageContract.Setup(x => x.GetHistoryByDishId(It.IsAny<string>())).Returns([]);
//Act
var list = _dishBusinessLogicContract.GetDishHistoryByDish(Guid.NewGuid().ToString());
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
_dishStorageContract.Verify(x => x.GetHistoryByDishId(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetDishHistoryByDish_DishIdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _dishBusinessLogicContract.GetDishHistoryByDish(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _dishBusinessLogicContract.GetDishHistoryByDish(string.Empty), Throws.TypeOf<ArgumentNullException>());
_dishStorageContract.Verify(x => x.GetHistoryByDishId(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetDishHistoryByDish_DishIdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _dishBusinessLogicContract.GetDishHistoryByDish("dishId"), Throws.TypeOf<ValidationException>());
_dishStorageContract.Verify(x => x.GetHistoryByDishId(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetDishHistoryByDish_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _dishBusinessLogicContract.GetDishHistoryByDish(Guid.NewGuid().ToString()), Throws.TypeOf<NullListException>());
_dishStorageContract.Verify(x => x.GetHistoryByDishId(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetDishHistoryByDish_StorageThrowError_ThrowException_Test()
{
//Arrange
_dishStorageContract.Setup(x => x.GetHistoryByDishId(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _dishBusinessLogicContract.GetDishHistoryByDish(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_dishStorageContract.Verify(x => x.GetHistoryByDishId(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetDishByData_GetById_ReturnRecord_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
var record = new DishDataModel(id, "name", DishType.Dessert, 10, false);
_dishStorageContract.Setup(x => x.GetElementById(id)).Returns(record);
//Act
var element = _dishBusinessLogicContract.GetDishByData(id);
//Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.Id, Is.EqualTo(id));
_dishStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetDishByData_GetByName_ReturnRecord_Test()
{
//Arrange
var name = "name";
var record = new DishDataModel(Guid.NewGuid().ToString(), name, DishType.Dessert, 10, false);
_dishStorageContract.Setup(x => x.GetElementByName(name)).Returns(record);
//Act
var element = _dishBusinessLogicContract.GetDishByData(name);
//Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.DishName, Is.EqualTo(name));
_dishStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetDishByData_EmptyData_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _dishBusinessLogicContract.GetDishByData(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _dishBusinessLogicContract.GetDishByData(string.Empty), Throws.TypeOf<ArgumentNullException>());
_dishStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Never);
_dishStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetDishByData_GetById_NotFoundRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _dishBusinessLogicContract.GetDishByData(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_dishStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetDishByData_GetByName_NotFoundRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _dishBusinessLogicContract.GetDishByData("name"), Throws.TypeOf<ElementNotFoundException>());
_dishStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetDishByData_StorageThrowError_ThrowException_Test()
{
//Arrange
_dishStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
_dishStorageContract.Setup(x => x.GetElementByName(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _dishBusinessLogicContract.GetDishByData(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
Assert.That(() => _dishBusinessLogicContract.GetDishByData("name"), Throws.TypeOf<StorageException>());
_dishStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
_dishStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Once);
}
[Test]
public void InsertDish_CorrectRecord_Test()
{
//Arrange
var flag = false;
var record = new DishDataModel(Guid.NewGuid().ToString(), "name", DishType.Dessert, 10, false);
_dishStorageContract.Setup(x => x.AddElement(It.IsAny<DishDataModel>()))
.Callback((DishDataModel x) =>
{
flag = x.Id == record.Id && x.DishName == record.DishName && x.DishType == record.DishType && x.Price == record.Price && x.IsDeleted == record.IsDeleted;
});
//Act
_dishBusinessLogicContract.InsertDish(record);
//Assert
_dishStorageContract.Verify(x => x.AddElement(It.IsAny<DishDataModel>()), Times.Once);
Assert.That(flag);
}
[Test]
public void InsertDish_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_dishStorageContract.Setup(x => x.AddElement(It.IsAny<DishDataModel>())).Throws(new ElementExistsException("Data", "Data"));
//Act&Assert
Assert.That(() => _dishBusinessLogicContract.InsertDish(new(Guid.NewGuid().ToString(), "name", DishType.Dessert, 10, false)), Throws.TypeOf<ElementExistsException>());
_dishStorageContract.Verify(x => x.AddElement(It.IsAny<DishDataModel>()), Times.Once);
}
[Test]
public void InsertDish_NullRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _dishBusinessLogicContract.InsertDish(null), Throws.TypeOf<ArgumentNullException>());
_dishStorageContract.Verify(x => x.AddElement(It.IsAny<DishDataModel>()), Times.Never);
}
[Test]
public void InsertDish_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _dishBusinessLogicContract.InsertDish(new DishDataModel("id", "name", DishType.Dessert, 10, false)), Throws.TypeOf<ValidationException>());
_dishStorageContract.Verify(x => x.AddElement(It.IsAny<DishDataModel>()), Times.Never);
}
[Test]
public void InsertDish_StorageThrowError_ThrowException_Test()
{
//Arrange
_dishStorageContract.Setup(x => x.AddElement(It.IsAny<DishDataModel>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _dishBusinessLogicContract.InsertDish(new(Guid.NewGuid().ToString(), "name", DishType.Dessert, 10, false)), Throws.TypeOf<StorageException>());
_dishStorageContract.Verify(x => x.AddElement(It.IsAny<DishDataModel>()), Times.Once);
}
[Test]
public void UpdateDish_CorrectRecord_Test()
{
//Arrange
var flag = false;
var record = new DishDataModel(Guid.NewGuid().ToString(), "name", DishType.Dessert, 10, false);
_dishStorageContract.Setup(x => x.UpdElement(It.IsAny<DishDataModel>()))
.Callback((DishDataModel x) =>
{
flag = x.Id == record.Id && x.DishName == record.DishName && x.DishType == record.DishType && x.Price == record.Price && x.IsDeleted == record.IsDeleted;
});
//Act
_dishBusinessLogicContract.UpdateDish(record);
//Assert
_dishStorageContract.Verify(x => x.UpdElement(It.IsAny<DishDataModel>()), Times.Once);
Assert.That(flag);
}
[Test]
public void UpdateDish_RecordWithIncorrectData_ThrowException_Test()
{
//Arrange
_dishStorageContract.Setup(x => x.UpdElement(It.IsAny<DishDataModel>())).Throws(new ElementNotFoundException(""));
//Act&Assert
Assert.That(() => _dishBusinessLogicContract.UpdateDish(new(Guid.NewGuid().ToString(), "name", DishType.Dessert, 10, false)), Throws.TypeOf<ElementNotFoundException>());
_dishStorageContract.Verify(x => x.UpdElement(It.IsAny<DishDataModel>()), Times.Once);
}
[Test]
public void UpdateDish_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_dishStorageContract.Setup(x => x.UpdElement(It.IsAny<DishDataModel>())).Throws(new ElementExistsException("Data", "Data"));
//Act&Assert
Assert.That(() => _dishBusinessLogicContract.UpdateDish(new(Guid.NewGuid().ToString(), "anme", DishType.Dessert, 10, false)), Throws.TypeOf<ElementExistsException>());
_dishStorageContract.Verify(x => x.UpdElement(It.IsAny<DishDataModel>()), Times.Once);
}
[Test]
public void UpdateDish_NullRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _dishBusinessLogicContract.UpdateDish(null), Throws.TypeOf<ArgumentNullException>());
_dishStorageContract.Verify(x => x.UpdElement(It.IsAny<DishDataModel>()), Times.Never);
}
[Test]
public void UpdateDish_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _dishBusinessLogicContract.UpdateDish(new DishDataModel("id", "name", DishType.Dessert, 10, false)), Throws.TypeOf<ValidationException>());
_dishStorageContract.Verify(x => x.UpdElement(It.IsAny<DishDataModel>()), Times.Never);
}
[Test]
public void UpdateDish_StorageThrowError_ThrowException_Test()
{
//Arrange
_dishStorageContract.Setup(x => x.UpdElement(It.IsAny<DishDataModel>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _dishBusinessLogicContract.UpdateDish(new(Guid.NewGuid().ToString(), "name", DishType.Dessert, 10, false)), Throws.TypeOf<StorageException>());
_dishStorageContract.Verify(x => x.UpdElement(It.IsAny<DishDataModel>()), Times.Once);
}
[Test]
public void DeleteDish_CorrectRecord_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
var flag = false;
_dishStorageContract.Setup(x => x.DelElement(It.Is((string x) => x == id))).Callback(() => { flag = true; });
//Act
_dishBusinessLogicContract.DeleteDish(id);
//Assert
_dishStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
Assert.That(flag);
}
[Test]
public void DeleteDish_RecordWithIncorrectId_ThrowException_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
_dishStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new ElementNotFoundException(id));
//Act&Assert
Assert.That(() => _dishBusinessLogicContract.DeleteDish(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_dishStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
}
[Test]
public void DeleteDish_IdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _dishBusinessLogicContract.DeleteDish(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _dishBusinessLogicContract.DeleteDish(string.Empty), Throws.TypeOf<ArgumentNullException>());
_dishStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Never);
}
[Test]
public void DeleteDish_IdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _dishBusinessLogicContract.DeleteDish("id"), Throws.TypeOf<ValidationException>());
_dishStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Never);
}
[Test]
public void DeleteDish_StorageThrowError_ThrowException_Test()
{
//Arrange
_dishStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _dishBusinessLogicContract.DeleteDish(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_dishStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
}
}

View File

@@ -0,0 +1,425 @@
using AndDietCokeContracts.BisnessLogicsContracts;
using AndDietCokeContracts.DataModels;
using AndDietCokeContracts.Enums;
using AndDietCokeContracts.StoragesContracts;
using AndDietCokeBuisnessLogic.Implementations;
using Moq;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using AndDietCokeContracts.Exceptions;
namespace AndDietCokeTests.BuisnessLogicsContractsTests;
[TestFixture]
internal class PostBusinessLogicContractTests
{
private PostBusinessLogicContract _postBusinessLogicContract;
private Mock<IPostStorageContract> _postStorageContract;
[OneTimeSetUp]
public void OneTimeSetUp()
{
_postStorageContract = new Mock<IPostStorageContract>();
_postBusinessLogicContract = new
PostBusinessLogicContract(_postStorageContract.Object, new Mock<ILogger>().Object);
}
[SetUp]
public void SetUp()
{
_postStorageContract.Reset();
}
[Test]
public void GetAllPosts_ReturnListOfRecords_Test()
{
//Arrange
var listOriginal = new List<PostDataModel>()
{
new(Guid.NewGuid().ToString(),"name 1", PostType.Chef, 10, true, DateTime.Now),
new(Guid.NewGuid().ToString(),"name 2", PostType.Chef, 10, true, DateTime.Now),
new(Guid.NewGuid().ToString(),"name 3", PostType.Chef, 10, true, DateTime.Now)
};
_postStorageContract.Setup(x => x.GetList(It.IsAny<bool>())).Returns(listOriginal);
//Act
var listOnlyActive = _postBusinessLogicContract.GetAllPosts(true);
var listAll = _postBusinessLogicContract.GetAllPosts(false);
//Assert
Assert.Multiple(() =>
{
Assert.That(listOnlyActive, Is.Not.Null);
Assert.That(listAll, Is.Not.Null);
Assert.That(listOnlyActive, Is.EquivalentTo(listOriginal));
Assert.That(listAll, Is.EquivalentTo(listOriginal));
});
_postStorageContract.Verify(x => x.GetList(true), Times.Once);
_postStorageContract.Verify(x => x.GetList(false), Times.Once);
}
[Test]
public void GetAllPosts_ReturnEmptyList_Test()
{
//Arrange
_postStorageContract.Setup(x => x.GetList(It.IsAny<bool>())).Returns([]);
//Act
var list = _postBusinessLogicContract.GetAllPosts(true);
//Assert
Assert.Multiple(() =>
{
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
});
}
[Test]
public void GetAllPosts_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.GetAllPosts(It.IsAny<bool>()), Throws.TypeOf<NullListException>());
_postStorageContract.Verify(x => x.GetList(It.IsAny<bool>()), Times.Once);
}
[Test]
public void GetAllPosts_StorageThrowError_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x => x.GetList(It.IsAny<bool>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.GetAllPosts(It.IsAny<bool>()), Throws.TypeOf<StorageException>());
_postStorageContract.Verify(x => x.GetList(It.IsAny<bool>()), Times.Once);
}
[Test]
public void GetAllDataOfPost_ReturnListOfRecords_Test()
{
//Arrange
var postId = Guid.NewGuid().ToString();
var listOriginal = new List<PostDataModel>()
{
new(postId,"name 1", PostType.Chef, 10, true, DateTime.Now),
new(postId,"name 2", PostType.Chef, 10, true, DateTime.Now)
};
_postStorageContract.Setup(x => x.GetPostWithHistory(It.IsAny<string>())).Returns(listOriginal);
//Act
var list = _postBusinessLogicContract.GetAllDataOfPost(postId);
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(2));
_postStorageContract.Verify(x => x.GetPostWithHistory(postId), Times.Once);
}
[Test]
public void GetAllDataOfPost_ReturnEmptyList_Test()
{
//Arrange
_postStorageContract.Setup(x => x.GetPostWithHistory(It.IsAny<string>())).Returns([]);
//Act
var list = _postBusinessLogicContract.GetAllDataOfPost(Guid.NewGuid().ToString());
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
_postStorageContract.Verify(x =>
x.GetPostWithHistory(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllDataOfPost_PostIdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.GetAllDataOfPost(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _postBusinessLogicContract.GetAllDataOfPost(string.Empty), Throws.TypeOf<ArgumentNullException>());
_postStorageContract.Verify(x => x.GetPostWithHistory(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllDataOfPost_PostIdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.GetAllDataOfPost("id"), Throws.TypeOf<ValidationException>());
_postStorageContract.Verify(x => x.GetPostWithHistory(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllDataOfPost_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.GetAllDataOfPost(Guid.NewGuid().ToString()),
Throws.TypeOf<NullListException>());
_postStorageContract.Verify(x => x.GetPostWithHistory(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllDataOfPost_StorageThrowError_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x => x.GetPostWithHistory(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.GetAllDataOfPost(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_postStorageContract.Verify(x =>
x.GetPostWithHistory(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetPostByData_GetById_ReturnRecord_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
var record = new PostDataModel(id,"name", PostType.Chef, 10, true, DateTime.Now);
_postStorageContract.Setup(x => x.GetElementById(id)).Returns(record);
//Act
var element = _postBusinessLogicContract.GetPostByData(id);
//Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.Id, Is.EqualTo(id));
_postStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetPostByData_GetByName_ReturnRecord_Test()
{
//Arrange
var postName = "name";
var record = new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Chef, 10, true, DateTime.Now);
_postStorageContract.Setup(x => x.GetElementByName(postName)).Returns(record);
//Act
var element = _postBusinessLogicContract.GetPostByData(postName);
//Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.PostName, Is.EqualTo(postName));
_postStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetPostByData_EmptyData_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.GetPostByData(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _postBusinessLogicContract.GetPostByData(string.Empty), Throws.TypeOf<ArgumentNullException>());
_postStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Never);
_postStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetPostByData_GetById_NotFoundRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.GetPostByData(Guid.NewGuid().ToString()),
Throws.TypeOf<ElementNotFoundException>());
_postStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
_postStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetPostByData_GetByName_NotFoundRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.GetPostByData("name"), Throws.TypeOf<ElementNotFoundException>());
_postStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Never);
_postStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetPostByData_StorageThrowError_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
_postStorageContract.Setup(x => x.GetElementByName(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.GetPostByData(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
Assert.That(() => _postBusinessLogicContract.GetPostByData("name"), Throws.TypeOf<StorageException>());
_postStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
_postStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Once);
}
[Test]
public void InsertPost_CorrectRecord_Test()
{
//Arrange
var flag = false;
var record = new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Chef, 10, true, DateTime.Now);
_postStorageContract.Setup(x => x.AddElement(It.IsAny<PostDataModel>()))
.Callback((PostDataModel x) =>
{
flag = x.Id == record.Id && x.PostName == record.PostName && x.PostType == record.PostType && x.Salary == record.Salary;
});
//Act
_postBusinessLogicContract.InsertPost(record);
//Assert
_postStorageContract.Verify(x => x.AddElement(It.IsAny<PostDataModel>()), Times.Once);
Assert.That(flag);
}
[Test]
public void InsertPost_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x => x.AddElement(It.IsAny<PostDataModel>())).Throws(new ElementExistsException("Data", "Data"));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.InsertPost(new(Guid.NewGuid().ToString(), "name", PostType.Chef, 10, true, DateTime.UtcNow)), Throws.TypeOf<ElementExistsException>());
_postStorageContract.Verify(x => x.AddElement(It.IsAny<PostDataModel>()), Times.Once);
}
[Test]
public void InsertPost_NullRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.InsertPost(null), Throws.TypeOf<ArgumentNullException>());
_postStorageContract.Verify(x => x.AddElement(It.IsAny<PostDataModel>()), Times.Never);
}
[Test]
public void InsertPost_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.InsertPost(new PostDataModel("id", "name", PostType.Chef, 10, true, DateTime.Now)), Throws.TypeOf<ValidationException>());
_postStorageContract.Verify(x => x.AddElement(It.IsAny<PostDataModel>()), Times.Never);
}
[Test]
public void InsertPost_StorageThrowError_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x => x.AddElement(It.IsAny<PostDataModel>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.InsertPost(new(Guid.NewGuid().ToString(), "name", PostType.Chef, 10, true, DateTime.UtcNow)), Throws.TypeOf<StorageException>());
_postStorageContract.Verify(x => x.AddElement(It.IsAny<PostDataModel>()), Times.Once);
}
[Test]
public void UpdatePost_CorrectRecord_Test()
{
//Arrange
var flag = false;
var record = new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Chef, 10, true, DateTime.Now);
_postStorageContract.Setup(x => x.UpdElement(It.IsAny<PostDataModel>()))
.Callback((PostDataModel x) =>
{
flag = x.Id == record.Id && x.PostName == record.PostName && x.PostType == record.PostType && x.Salary == record.Salary;
});
//Act
_postBusinessLogicContract.UpdatePost(record);
//Assert
_postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Once);
Assert.That(flag);
}
[Test]
public void UpdatePost_RecordWithIncorrectData_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x => x.UpdElement(It.IsAny<PostDataModel>())).Throws(new ElementNotFoundException(""));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "name", PostType.Chef, 10, true, DateTime.Now)), Throws.TypeOf<ElementNotFoundException>());
_postStorageContract.Verify(x =>
x.UpdElement(It.IsAny<PostDataModel>()), Times.Once);
}
[Test]
public void UpdatePost_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x => x.UpdElement(It.IsAny<PostDataModel>())).Throws(new ElementExistsException("Data", "Data"));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "name", PostType.Chef, 10, true, DateTime.Now)), Throws.TypeOf<ElementExistsException>());
_postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Once);
}
[Test]
public void UpdatePost_NullRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.UpdatePost(null), Throws.TypeOf<ArgumentNullException>());
_postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Never);
}
[Test]
public void UpdatePost_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.UpdatePost(new PostDataModel("id", "name", PostType.Chef, 10, true, DateTime.UtcNow)), Throws.TypeOf<ValidationException>());
_postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Never);
}
[Test]
public void UpdatePost_StorageThrowError_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x => x.UpdElement(It.IsAny<PostDataModel>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "name", PostType.Chef, 10, true, DateTime.Now)), Throws.TypeOf<StorageException>());
_postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Once);
}
[Test]
public void DeletePost_CorrectRecord_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
var flag = false;
_postStorageContract.Setup(x => x.DelElement(It.Is((string x) => x == id))).Callback(() => { flag = true; });
//Act
_postBusinessLogicContract.DeletePost(id);
//Assert
_postStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
Assert.That(flag);
}
[Test]
public void DeletePost_RecordWithIncorrectId_ThrowException_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
_postStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new ElementNotFoundException(id));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.DeletePost(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_postStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
}
[Test]
public void DeletePost_IdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.DeletePost(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _postBusinessLogicContract.DeletePost(string.Empty), Throws.TypeOf<ArgumentNullException>());
_postStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Never);
}
[Test]
public void DeletePost_IdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.DeletePost("id"), Throws.TypeOf<ValidationException>());
_postStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Never);
}
[Test]
public void DeletePost_StorageThrowError_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.DeletePost(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_postStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
}
[Test]
public void RestorePost_CorrectRecord_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
var flag = false;
_postStorageContract.Setup(x => x.ResElement(It.Is((string x) => x == id))).Callback(() => { flag = true; });
//Act
_postBusinessLogicContract.RestorePost(id);
//Assert
_postStorageContract.Verify(x => x.ResElement(It.IsAny<string>()), Times.Once);
Assert.That(flag);
}
[Test]
public void RestorePost_RecordWithIncorrectId_ThrowException_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
_postStorageContract.Setup(x => x.ResElement(It.IsAny<string>())).Throws(new ElementNotFoundException(id));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.RestorePost(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_postStorageContract.Verify(x => x.ResElement(It.IsAny<string>()), Times.Once);
}
[Test]
public void RestorePost_IdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.RestorePost(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _postBusinessLogicContract.RestorePost(string.Empty), Throws.TypeOf<ArgumentNullException>());
_postStorageContract.Verify(x => x.ResElement(It.IsAny<string>()), Times.Never);
}
[Test]
public void RestorePost_IdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.RestorePost("id"), Throws.TypeOf<ValidationException>());
_postStorageContract.Verify(x => x.ResElement(It.IsAny<string>()), Times.Never);
}
[Test]
public void RestorePost_StorageThrowError_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x => x.ResElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.RestorePost(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_postStorageContract.Verify(x => x.ResElement(It.IsAny<string>()), Times.Once);
}
}

View File

@@ -0,0 +1,352 @@
using AndDietCokeContracts.DataModels;
using AndDietCokeContracts.Enums;
using AndDietCokeContracts.Exceptions;
using AndDietCokeContracts.StoragesContracts;
using AndDietCokeBuisnessLogic.Implementations;
using Moq;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
namespace AndDietCokeTests.BuisnessLogicsContractsTests;
[TestFixture]
internal class SalaryBuisnessLogicContractTests
{
private SalaryBusinessLogicContract _salaryBusinessLogicContract;
private Mock<ISalaryStorageContract> _salaryStorageContract;
private Mock<ISaleStorageContract> _saleStorageContract;
private Mock<IPostStorageContract> _postStorageContract;
private Mock<IWorkerStorageContract> _workerStorageContract;
[OneTimeSetUp]
public void OneTimeSetUp()
{
_salaryStorageContract = new Mock<ISalaryStorageContract>();
_saleStorageContract = new Mock<ISaleStorageContract>();
_postStorageContract = new Mock<IPostStorageContract>();
_workerStorageContract = new Mock<IWorkerStorageContract>();
_salaryBusinessLogicContract = new SalaryBusinessLogicContract(_salaryStorageContract.Object,
_saleStorageContract.Object, _postStorageContract.Object, _workerStorageContract.Object, new Mock<ILogger>().Object);
}
[SetUp]
public void SetUp()
{
_salaryStorageContract.Reset();
_saleStorageContract.Reset();
_postStorageContract.Reset();
_workerStorageContract.Reset();
}
[Test]
public void GetAllSalaries_ReturnListOfRecords_Test()
{
//Arrange
var startDate = DateTime.UtcNow;
var endDate = DateTime.UtcNow.AddDays(1);
var listOriginal = new List<SalaryDataModel>()
{
new(Guid.NewGuid().ToString(), DateTime.UtcNow, 10),
new(Guid.NewGuid().ToString(), DateTime.UtcNow.AddDays(1), 14),
new(Guid.NewGuid().ToString(), DateTime.UtcNow.AddDays(-1), 30),
};
_salaryStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>())).Returns(listOriginal);
//Act
var list = _salaryBusinessLogicContract.GetAllSalariesByPeriod(startDate, endDate);
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.EquivalentTo(listOriginal));
_salaryStorageContract.Verify(x => x.GetList(startDate, endDate, null), Times.Once);
}
[Test]
public void GetAllSalaries_ReturnEmptyList_Test()
{
//Arrange
_salaryStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>())).Returns([]);
//Act
var list = _salaryBusinessLogicContract.GetAllSalariesByPeriod(DateTime.UtcNow, DateTime.UtcNow.AddDays(1));
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
_salaryStorageContract.Verify(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSalaries_IncorrectDates_ThrowException_Test()
{
//Arrange
var dateTime = DateTime.UtcNow;
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.GetAllSalariesByPeriod(dateTime, dateTime), Throws.TypeOf<IncorrectDatesException>());
Assert.That(() => _salaryBusinessLogicContract.GetAllSalariesByPeriod(dateTime, dateTime.AddSeconds(-1)), Throws.TypeOf<IncorrectDatesException>());
_salaryStorageContract.Verify(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSalaries_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.GetAllSalariesByPeriod(DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<NullListException>());
_salaryStorageContract.Verify(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSalaries_StorageThrowError_ThrowException_Test()
{
//Arrange
_salaryStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.GetAllSalariesByPeriod(DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<StorageException>());
_salaryStorageContract.Verify(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSalariesByWorker_ReturnListOfRecords_Test()
{
//Arrange
var startDate = DateTime.UtcNow;
var endDate = DateTime.UtcNow.AddDays(1);
var workerId = Guid.NewGuid().ToString();
var listOriginal = new List<SalaryDataModel>()
{
new(Guid.NewGuid().ToString(), DateTime.UtcNow, 10),
new(Guid.NewGuid().ToString(), DateTime.UtcNow.AddDays(1), 14),
new(Guid.NewGuid().ToString(), DateTime.UtcNow.AddDays(-1), 30),
};
_salaryStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>())).Returns(listOriginal);
//Act
var list = _salaryBusinessLogicContract.GetAllSalariesByPeriodByWorker(startDate, endDate, workerId);
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.EquivalentTo(listOriginal));
_salaryStorageContract.Verify(x => x.GetList(startDate, endDate, workerId), Times.Once);
}
[Test]
public void GetAllSalariesByWorker_ReturnEmptyList_Test()
{
//Arrange
_salaryStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>())).Returns([]);
//Act
var list = _salaryBusinessLogicContract.GetAllSalariesByPeriodByWorker(DateTime.UtcNow, DateTime.UtcNow.AddDays(1), Guid.NewGuid().ToString());
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
_salaryStorageContract.Verify(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSalariesByWorker_IncorrectDates_ThrowException_Test()
{
//Arrange
var dateTime = DateTime.UtcNow;
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.GetAllSalariesByPeriodByWorker(dateTime, dateTime, Guid.NewGuid().ToString()), Throws.TypeOf<IncorrectDatesException>());
Assert.That(() => _salaryBusinessLogicContract.GetAllSalariesByPeriodByWorker(dateTime, dateTime.AddSeconds(-1), Guid.NewGuid().ToString()), Throws.TypeOf<IncorrectDatesException>());
_salaryStorageContract.Verify(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSalariesByWorker_WorkerIdIsNUllOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.GetAllSalariesByPeriodByWorker(DateTime.UtcNow, DateTime.UtcNow.AddDays(1), null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _salaryBusinessLogicContract.GetAllSalariesByPeriodByWorker(DateTime.UtcNow, DateTime.UtcNow.AddDays(1), string.Empty), Throws.TypeOf<ArgumentNullException>());
_salaryStorageContract.Verify(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSalariesByWorker_WorkerIdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.GetAllSalariesByPeriodByWorker(DateTime.UtcNow, DateTime.UtcNow.AddDays(1), "workerId"), Throws.TypeOf<ValidationException>());
_salaryStorageContract.Verify(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSalariesByWorker_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.GetAllSalariesByPeriodByWorker(DateTime.UtcNow, DateTime.UtcNow.AddDays(1), Guid.NewGuid().ToString()), Throws.TypeOf<NullListException>());
_salaryStorageContract.Verify(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSalariesByWorker_StorageThrowError_ThrowException_Test()
{
//Arrange
_salaryStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.GetAllSalariesByPeriodByWorker(DateTime.UtcNow, DateTime.UtcNow.AddDays(1), Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_salaryStorageContract.Verify(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void CalculateSalaryByMounth_CalculateSalary_Test()
{
//Arrange
var workerId = Guid.NewGuid().ToString();
var saleSum = 200.0;
var postSalary = 2000.0;
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns([new SaleDataModel(Guid.NewGuid().ToString(), workerId, null, saleSum, true, false, [])]);
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Waiter, postSalary, true, DateTime.UtcNow));
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Returns([new WorkerDataModel(workerId, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)]);
var sum = 0.0;
var expectedSum = postSalary + saleSum * 0.1;
_salaryStorageContract.Setup(x => x.AddElement(It.IsAny<SalaryDataModel>()))
.Callback((SalaryDataModel x) =>
{
sum = x.Salary;
});
//Act
_salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow);
//Assert
Assert.That(sum, Is.EqualTo(expectedSum));
}
[Test]
public void CalculateSalaryByMounth_WithSeveralWorkers_Test()
{
//Arrange
var worker1Id = Guid.NewGuid().ToString();
var worker2Id = Guid.NewGuid().ToString();
var worker3Id = Guid.NewGuid().ToString();
var list = new List<WorkerDataModel>() {
new(worker1Id, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false),
new(worker2Id, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false),
new(worker3Id, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)
};
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns([new SaleDataModel(Guid.NewGuid().ToString(), worker1Id, null, 1, true, false, []),
new SaleDataModel(Guid.NewGuid().ToString(), worker1Id, null, 1, true, false, []),
new SaleDataModel(Guid.NewGuid().ToString(), worker2Id, null, 1, true, false, []),
new SaleDataModel(Guid.NewGuid().ToString(), worker3Id, null, 1, true, false, []),
new SaleDataModel(Guid.NewGuid().ToString(), worker3Id, null, 1, true, false, [])]);
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Chef, 2000, true, DateTime.UtcNow));
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Returns(list);
//Act
_salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow);
//Assert
_salaryStorageContract.Verify(x => x.AddElement(It.IsAny<SalaryDataModel>()), Times.Exactly(list.Count));
}
[Test]
public void CalculateSalaryByMounth_WithoitSalesByWorker_Test()
{
//Arrange
var postSalary = 2000.0;
var workerId = Guid.NewGuid().ToString();
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns([]);
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Chef, postSalary, true, DateTime.UtcNow));
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Returns([new WorkerDataModel(workerId, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)]);
var sum = 0.0;
var expectedSum = postSalary;
_salaryStorageContract.Setup(x => x.AddElement(It.IsAny<SalaryDataModel>()))
.Callback((SalaryDataModel x) =>
{
sum = x.Salary;
});
//Act
_salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow);
//Assert
Assert.That(sum, Is.EqualTo(expectedSum));
}
[Test]
public void CalculateSalaryByMounth_SaleStorageReturnNull_ThrowException_Test()
{
//Arrange
var workerId = Guid.NewGuid().ToString();
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Chef, 2000, true, DateTime.UtcNow));
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Returns([new WorkerDataModel(workerId, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)]);
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow), Throws.TypeOf<NullListException>());
}
[Test]
public void CalculateSalaryByMounth_PostStorageReturnNull_ThrowException_Test()
{
//Arrange
var workerId = Guid.NewGuid().ToString();
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns([new SaleDataModel(Guid.NewGuid().ToString(), workerId, null, 200, true, false, [])]);
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Returns([new WorkerDataModel(workerId, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)]);
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow), Throws.TypeOf<NullListException>());
}
[Test]
public void CalculateSalaryByMounth_WorkerStorageReturnNull_ThrowException_Test()
{
//Arrange
var workerId = Guid.NewGuid().ToString();
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns([new SaleDataModel(Guid.NewGuid().ToString(), workerId, null, 200, true, false, [])]);
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Chef, 2000, true, DateTime.UtcNow));
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow), Throws.TypeOf<NullListException>());
}
[Test]
public void CalculateSalaryByMounth_SaleStorageThrowException_ThrowException_Test()
{
//Arrange
var workerId = Guid.NewGuid().ToString();
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
.Throws(new StorageException(new InvalidOperationException()));
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Chef, 2000, true, DateTime.UtcNow));
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Returns([new WorkerDataModel(workerId, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)]);
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow), Throws.TypeOf<StorageException>());
}
[Test]
public void CalculateSalaryByMounth_PostStorageThrowException_ThrowException_Test()
{
//Arrange
var workerId = Guid.NewGuid().ToString();
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns([new SaleDataModel(Guid.NewGuid().ToString(), workerId, null, 200, true, false, [])]);
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Throws(new StorageException(new InvalidOperationException()));
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Returns([new WorkerDataModel(workerId, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)]);
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow), Throws.TypeOf<StorageException>());
}
[Test]
public void CalculateSalaryByMounth_WorkerStorageThrowException_ThrowException_Test()
{
//Arrange
var workerId = Guid.NewGuid().ToString();
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns([new SaleDataModel(Guid.NewGuid().ToString(), workerId, null, 200, true, false, [])]);
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Chef, 2000, true, DateTime.UtcNow));
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow), Throws.TypeOf<StorageException>());
}
}

View File

@@ -0,0 +1,503 @@
using AndDietCokeBuisnessLogic.Implementations;
using AndDietCokeContracts.DataModels;
using AndDietCokeContracts.Exceptions;
using AndDietCokeContracts.StoragesContracts;
using AndDietCokeContracts.Enums;
using Moq;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Extensions.Logging;
using System.Threading.Tasks;
namespace AndDietCokeTests.BuisnessLogicsContractsTests;
[TestFixture]
internal class SaleBuisnessLogicContractTests
{
private SaleBusinessLogicContract _saleBusinessLogicContract;
private Mock<ISaleStorageContract> _saleStorageContract;
[OneTimeSetUp]
public void OneTimeSetUp()
{
_saleStorageContract = new Mock<ISaleStorageContract>();
_saleBusinessLogicContract = new SaleBusinessLogicContract(_saleStorageContract.Object, new Mock<ILogger>().Object);
}
[SetUp]
public void SetUp()
{
_saleStorageContract.Reset();
}
[Test]
public void GetAllSalesByPeriod_ReturnListOfRecords_Test()
{
//Arrange
var date = DateTime.UtcNow;
var listOriginal = new List<SaleDataModel>()
{
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, true, false, []),
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, true, false, []),
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, true, false, []),
};
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Returns(listOriginal);
//Act
var list = _saleBusinessLogicContract.GetAllSalesByPeriod(date, date.AddDays(1));
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.EquivalentTo(listOriginal));
_saleStorageContract.Verify(x => x.GetList(date, date.AddDays(1), null, null, null), Times.Once);
}
[Test]
public void GetAllSalesByPeriod_ReturnEmptyList_Test()
{
//Arrange
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Returns([]);
//Act
var list = _saleBusinessLogicContract.GetAllSalesByPeriod(DateTime.UtcNow, DateTime.UtcNow.AddDays(1));
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSalesByPeriod_IncorrectDates_ThrowException_Test()
{
//Arrange
var date = DateTime.UtcNow;
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByPeriod(date, date), Throws.TypeOf<IncorrectDatesException>());
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByPeriod(date, date.AddSeconds(-1)), Throws.TypeOf<IncorrectDatesException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSalesByPeriod_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByPeriod(DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<NullListException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSalesByPeriod_StorageThrowError_ThrowException_Test()
{
//Arrange
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByPeriod(DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<StorageException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSalesByWorkerByPeriod_ReturnListOfRecords_Test()
{
//Arrange
var date = DateTime.UtcNow;
var workerId = Guid.NewGuid().ToString();
var listOriginal = new List<SaleDataModel>()
{
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, true, false,
[new OrderDishDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]),
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, true, false, []),
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, true, false, []),
};
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Returns(listOriginal);
//Act
var list = _saleBusinessLogicContract.GetAllSalesByWorkerByPeriod(workerId, date, date.AddDays(1));
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.EquivalentTo(listOriginal));
_saleStorageContract.Verify(x => x.GetList(date, date.AddDays(1), workerId, null, null), Times.Once);
}
[Test]
public void GetAllSalesByWorkerByPeriod_ReturnEmptyList_Test()
{
//Arrange
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Returns([]);
//Act
var list = _saleBusinessLogicContract.GetAllSalesByWorkerByPeriod(Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow.AddDays(1));
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSalesByWorkerByPeriod_IncorrectDates_ThrowException_Test()
{
//Arrange
var date = DateTime.UtcNow;
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByWorkerByPeriod(Guid.NewGuid().ToString(), date, date), Throws.TypeOf<IncorrectDatesException>());
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByWorkerByPeriod(Guid.NewGuid().ToString(), date, date.AddSeconds(-1)), Throws.TypeOf<IncorrectDatesException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSalesByWorkerByPeriod_WorkerIdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByWorkerByPeriod(null, DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByWorkerByPeriod(string.Empty, DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<ArgumentNullException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSalesByWorkerByPeriod_WorkerIdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByWorkerByPeriod("workerId", DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<ValidationException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSalesByWorkerByPeriod_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByWorkerByPeriod(Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<NullListException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSalesByWorkerByPeriod_StorageThrowError_ThrowException_Test()
{
//Arrange
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByWorkerByPeriod(Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<StorageException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSalesByBuyerByPeriod_ReturnListOfRecords_Test()
{
//Arrange
var date = DateTime.UtcNow;
var buyerId = Guid.NewGuid().ToString();
var listOriginal = new List<SaleDataModel>()
{
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, true, false,
[new OrderDishDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]),
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, true, false, []),
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, true, false, []),
};
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Returns(listOriginal);
//Act
var list = _saleBusinessLogicContract.GetAllSalesByBuyerByPeriod(buyerId, date, date.AddDays(1));
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.EquivalentTo(listOriginal));
_saleStorageContract.Verify(x => x.GetList(date, date.AddDays(1), null, buyerId, null), Times.Once);
}
[Test]
public void GetAllSalesByBuyerByPeriod_ReturnEmptyList_Test()
{
//Arrange
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Returns([]);
//Act
var list = _saleBusinessLogicContract.GetAllSalesByBuyerByPeriod(Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow.AddDays(1));
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSalesByBuyerByPeriod_IncorrectDates_ThrowException_Test()
{
//Arrange
var date = DateTime.UtcNow;
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByBuyerByPeriod(Guid.NewGuid().ToString(), date, date), Throws.TypeOf<IncorrectDatesException>());
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByBuyerByPeriod(Guid.NewGuid().ToString(), date, date.AddSeconds(-1)), Throws.TypeOf<IncorrectDatesException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSalesByBuyerByPeriod_BuyerIdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByBuyerByPeriod(null, DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByBuyerByPeriod(string.Empty, DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<ArgumentNullException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSalesByBuyerByPeriod_BuyerIdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByBuyerByPeriod("buyerId", DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<ValidationException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSalesByBuyerByPeriod_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByBuyerByPeriod(Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<NullListException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSalesByBuyerByPeriod_StorageThrowError_ThrowException_Test()
{
//Arrange
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByBuyerByPeriod(Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<StorageException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSalesByDishByPeriod_ReturnListOfRecords_Test()
{
//Arrange
var date = DateTime.UtcNow;
var productId = Guid.NewGuid().ToString();
var listOriginal = new List<SaleDataModel>()
{
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, true, false,
[new OrderDishDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]),
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, true, false, []),
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, true, false, []),
};
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Returns(listOriginal);
//Act
var list = _saleBusinessLogicContract.GetAllSalesByDishByPeriod(productId, date, date.AddDays(1));
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.EquivalentTo(listOriginal));
_saleStorageContract.Verify(x => x.GetList(date, date.AddDays(1), null, null, productId), Times.Once);
}
[Test]
public void GetAllSalesByDishByPeriod_ReturnEmptyList_Test()
{
//Arrange
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Returns([]);
//Act
var list = _saleBusinessLogicContract.GetAllSalesByDishByPeriod(Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow.AddDays(1));
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSalesByDishByPeriod_IncorrectDates_ThrowException_Test()
{
//Arrange
var date = DateTime.UtcNow;
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByDishByPeriod(Guid.NewGuid().ToString(), date, date), Throws.TypeOf<IncorrectDatesException>());
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByDishByPeriod(Guid.NewGuid().ToString(), date, date.AddSeconds(-1)), Throws.TypeOf<IncorrectDatesException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSalesByDishByPeriod_DishIdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByDishByPeriod(null, DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByDishByPeriod(string.Empty, DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<ArgumentNullException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSalesByDishByPeriod_DishIdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByDishByPeriod("productId", DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<ValidationException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSalesByDishByPeriod_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByDishByPeriod(Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<NullListException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSalesByDishByPeriod_StorageThrowError_ThrowException_Test()
{
//Arrange
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByDishByPeriod(Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<StorageException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetSaleByData_GetById_ReturnRecord_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
var record = new SaleDataModel(id, Guid.NewGuid().ToString(), null, 10, true, false,
[new OrderDishDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]);
_saleStorageContract.Setup(x => x.GetElementById(id)).Returns(record);
//Act
var element = _saleBusinessLogicContract.GetSaleByData(id);
//Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.Id, Is.EqualTo(id));
_saleStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetSaleByData_EmptyData_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetSaleByData(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _saleBusinessLogicContract.GetSaleByData(string.Empty), Throws.TypeOf<ArgumentNullException>());
_saleStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetSaleByData_IdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetSaleByData("saleId"), Throws.TypeOf<ValidationException>());
_saleStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetSaleByData_GetById_NotFoundRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetSaleByData(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_saleStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetSaleByData_StorageThrowError_ThrowException_Test()
{
//Arrange
_saleStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetSaleByData(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_saleStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void InsertSale_CorrectRecord_Test()
{
//Arrange
var flag = false;
var record = new SaleDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 10, true,
false, [new OrderDishDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]);
_saleStorageContract.Setup(x => x.AddElement(It.IsAny<SaleDataModel>()))
.Callback((SaleDataModel x) =>
{
flag = x.Id == record.Id && x.WorkerId == record.WorkerId && x.BuyerId == record.BuyerId &&
x.SaleDate == record.SaleDate && x.Sum == record.Sum && x.IsCancel == record.IsCancel && x.Dishes.Count == record.Dishes.Count &&
x.Dishes.First().DishId == record.Dishes.First().DishId &&
x.Dishes.First().Count == record.Dishes.First().Count;
});
//Act
_saleBusinessLogicContract.InsertSale(record);
//Assert
_saleStorageContract.Verify(x => x.AddElement(It.IsAny<SaleDataModel>()), Times.Once);
Assert.That(flag);
}
[Test]
public void InsertSale_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_saleStorageContract.Setup(x => x.AddElement(It.IsAny<SaleDataModel>())).Throws(new ElementExistsException("Data", "Data"));
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.InsertSale(new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(),
Guid.NewGuid().ToString(), 10, true, false, [new OrderDishDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<ElementExistsException>());
_saleStorageContract.Verify(x => x.AddElement(It.IsAny<SaleDataModel>()), Times.Once);
}
[Test]
public void InsertSale_NullRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.InsertSale(null), Throws.TypeOf<ArgumentNullException>());
_saleStorageContract.Verify(x => x.AddElement(It.IsAny<SaleDataModel>()), Times.Never);
}
[Test]
public void InsertSale_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.InsertSale(new SaleDataModel("id", Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 10, true, false, [])), Throws.TypeOf<ValidationException>());
_saleStorageContract.Verify(x => x.AddElement(It.IsAny<SaleDataModel>()), Times.Never);
}
[Test]
public void InsertSale_StorageThrowError_ThrowException_Test()
{
//Arrange
_saleStorageContract.Setup(x => x.AddElement(It.IsAny<SaleDataModel>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.InsertSale(new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(),
Guid.NewGuid().ToString(), 10, true, false, [new OrderDishDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<StorageException>());
_saleStorageContract.Verify(x => x.AddElement(It.IsAny<SaleDataModel>()), Times.Once);
}
[Test]
public void CancelSale_CorrectRecord_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
var flag = false;
_saleStorageContract.Setup(x => x.DelElement(It.Is((string x) => x == id))).Callback(() => { flag = true; });
//Act
_saleBusinessLogicContract.CancelSale(id);
//Assert
_saleStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
Assert.That(flag);
}
[Test]
public void CancelSale_RecordWithIncorrectId_ThrowException_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
_saleStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new ElementNotFoundException(id));
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.CancelSale(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_saleStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
}
[Test]
public void CancelSale_IdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.CancelSale(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _saleBusinessLogicContract.CancelSale(string.Empty), Throws.TypeOf<ArgumentNullException>());
_saleStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Never);
}
[Test]
public void CancelSale_IdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.CancelSale("id"), Throws.TypeOf<ValidationException>());
_saleStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Never);
}
[Test]
public void CancelSale_StorageThrowError_ThrowException_Test()
{
//Arrange
_saleStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.CancelSale(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_saleStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
}
}

View File

@@ -0,0 +1,562 @@
using AndDietCokeContracts.DataModels;
using AndDietCokeContracts.Exceptions;
using AndDietCokeContracts.StoragesContracts;
using AndDietCokeBuisnessLogic.Implementations;
using Moq;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using Microsoft.Extensions.Logging;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AndDietCokeTests.BuisnessLogicsContractsTests;
internal class WorkerBusinessLogicContractTests
{
private WorkerBusinessLogicContract _workerBusinessLogicContract;
private Mock<IWorkerStorageContract> _workerStorageContract;
[OneTimeSetUp]
public void OneTimeSetUp()
{
_workerStorageContract = new Mock<IWorkerStorageContract>();
_workerBusinessLogicContract = new WorkerBusinessLogicContract(_workerStorageContract.Object, new Mock<ILogger>().Object);
}
[SetUp]
public void SetUp()
{
_workerStorageContract.Reset();
}
[Test]
public void GetAllWorkers_ReturnListOfRecords_Test()
{
//Arrange
var listOriginal = new List<WorkerDataModel>()
{
new(Guid.NewGuid().ToString(), "fio 1", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false),
new(Guid.NewGuid().ToString(), "fio 2", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, true),
new(Guid.NewGuid().ToString(), "fio 3", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false),
};
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Returns(listOriginal);
//Act
var listOnlyActive = _workerBusinessLogicContract.GetAllWorkers(true);
var list = _workerBusinessLogicContract.GetAllWorkers(false);
//Assert
Assert.Multiple(() =>
{
Assert.That(listOnlyActive, Is.Not.Null);
Assert.That(list, Is.Not.Null);
Assert.That(listOnlyActive, Is.EquivalentTo(listOriginal));
Assert.That(list, Is.EquivalentTo(listOriginal));
});
_workerStorageContract.Verify(x => x.GetList(true, null, null, null, null, null), Times.Once);
_workerStorageContract.Verify(x => x.GetList(false, null, null, null, null, null), Times.Once);
}
[Test]
public void GetAllWorkers_ReturnEmptyList_Test()
{
//Arrange
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Returns([]);
//Act
var listOnlyActive = _workerBusinessLogicContract.GetAllWorkers(true);
var list = _workerBusinessLogicContract.GetAllWorkers(false);
//Assert
Assert.Multiple(() =>
{
Assert.That(listOnlyActive, Is.Not.Null);
Assert.That(list, Is.Not.Null);
Assert.That(listOnlyActive, Has.Count.EqualTo(0));
Assert.That(list, Has.Count.EqualTo(0));
});
_workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), null, null, null, null, null), Times.Exactly(2));
}
[Test]
public void GetAllWorkers_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.GetAllWorkers(It.IsAny<bool>()), Throws.TypeOf<NullListException>());
_workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Once);
}
[Test]
public void GetAllWorkers_StorageThrowError_ThrowException_Test()
{
//Arrange
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.GetAllWorkers(It.IsAny<bool>()), Throws.TypeOf<StorageException>());
_workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), null, null, null, null, null), Times.Once);
}
[Test]
public void GetAllWorkersByPost_ReturnListOfRecords_Test()
{
//Arrange
var postId = Guid.NewGuid().ToString();
var listOriginal = new List<WorkerDataModel>()
{
new(Guid.NewGuid().ToString(), "fio 1", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false),
new(Guid.NewGuid().ToString(), "fio 2", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, true),
new(Guid.NewGuid().ToString(), "fio 3", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false),
};
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Returns(listOriginal);
//Act
var listOnlyActive = _workerBusinessLogicContract.GetAllWorkersByPost(postId, true);
var list = _workerBusinessLogicContract.GetAllWorkersByPost(postId, false);
//Assert
Assert.Multiple(() =>
{
Assert.That(listOnlyActive, Is.Not.Null);
Assert.That(list, Is.Not.Null);
Assert.That(listOnlyActive, Is.EquivalentTo(listOriginal));
Assert.That(list, Is.EquivalentTo(listOriginal));
});
_workerStorageContract.Verify(x => x.GetList(true, postId, null, null, null, null), Times.Once);
_workerStorageContract.Verify(x => x.GetList(false, postId, null, null, null, null), Times.Once);
}
[Test]
public void GetAllWorkersByPost_ReturnEmptyList_Test()
{
//Arrange
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Returns([]);
//Act
var listOnlyActive = _workerBusinessLogicContract.GetAllWorkersByPost(Guid.NewGuid().ToString(), true);
var list = _workerBusinessLogicContract.GetAllWorkersByPost(Guid.NewGuid().ToString(), false);
//Assert
Assert.Multiple(() =>
{
Assert.That(listOnlyActive, Is.Not.Null);
Assert.That(list, Is.Not.Null);
Assert.That(listOnlyActive, Has.Count.EqualTo(0));
Assert.That(list, Has.Count.EqualTo(0));
});
_workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Exactly(2));
}
[Test]
public void GetAllWorkersByPost_PostIdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.GetAllWorkersByPost(null, It.IsAny<bool>()), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _workerBusinessLogicContract.GetAllWorkersByPost(string.Empty, It.IsAny<bool>()), Throws.TypeOf<ArgumentNullException>());
_workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Never);
}
[Test]
public void GetAllWorkersByPost_PostIdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.GetAllWorkersByPost("postId", It.IsAny<bool>()), Throws.TypeOf<ValidationException>());
_workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Never);
}
[Test]
public void GetAllWorkersByPost_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.GetAllWorkersByPost(Guid.NewGuid().ToString(), It.IsAny<bool>()), Throws.TypeOf<NullListException>());
_workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Once);
}
[Test]
public void GetAllWorkersByPost_StorageThrowError_ThrowException_Test()
{
//Arrange
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.GetAllWorkersByPost(Guid.NewGuid().ToString(), It.IsAny<bool>()), Throws.TypeOf<StorageException>());
_workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Once);
}
[Test]
public void GetAllWorkersByBirthDate_ReturnListOfRecords_Test()
{
//Arrange
var date = DateTime.UtcNow;
var listOriginal = new List<WorkerDataModel>()
{
new(Guid.NewGuid().ToString(), "fio 1", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false),
new(Guid.NewGuid().ToString(), "fio 2", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, true),
new(Guid.NewGuid().ToString(), "fio 3", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false),
};
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Returns(listOriginal);
//Act
var listOnlyActive = _workerBusinessLogicContract.GetAllWorkersByBirthDate(date, date.AddDays(1), true);
var list = _workerBusinessLogicContract.GetAllWorkersByBirthDate(date, date.AddDays(1), false);
//Assert
Assert.Multiple(() =>
{
Assert.That(listOnlyActive, Is.Not.Null);
Assert.That(list, Is.Not.Null);
Assert.That(listOnlyActive, Is.EquivalentTo(listOriginal));
Assert.That(list, Is.EquivalentTo(listOriginal));
});
_workerStorageContract.Verify(x => x.GetList(true, null, date, date.AddDays(1), null, null), Times.Once);
_workerStorageContract.Verify(x => x.GetList(false, null, date, date.AddDays(1), null, null), Times.Once);
}
[Test]
public void GetAllWorkersByBirthDate_ReturnEmptyList_Test()
{
//Arrange
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Returns([]);
//Act
var listOnlyActive = _workerBusinessLogicContract.GetAllWorkersByBirthDate(DateTime.UtcNow, DateTime.UtcNow.AddDays(1), true);
var list = _workerBusinessLogicContract.GetAllWorkers(false);
//Assert
Assert.Multiple(() =>
{
Assert.That(listOnlyActive, Is.Not.Null);
Assert.That(list, Is.Not.Null);
Assert.That(listOnlyActive, Has.Count.EqualTo(0));
Assert.That(list, Has.Count.EqualTo(0));
});
_workerStorageContract.Verify(x => x.GetList(true, null, It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), null, null), Times.Once);
_workerStorageContract.Verify(x => x.GetList(false, null, It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), null, null), Times.Once);
}
[Test]
public void GetAllWorkersByBirthDate_IncorrectDates_ThrowException_Test()
{
//Arrange
var date = DateTime.UtcNow;
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.GetAllWorkersByBirthDate(date, date, It.IsAny<bool>()), Throws.TypeOf<IncorrectDatesException>());
Assert.That(() => _workerBusinessLogicContract.GetAllWorkersByBirthDate(date, date.AddSeconds(-1), It.IsAny<bool>()), Throws.TypeOf<IncorrectDatesException>());
_workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Never);
}
[Test]
public void GetAllWorkersByBirthDate_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.GetAllWorkersByBirthDate(DateTime.UtcNow, DateTime.UtcNow.AddDays(1), It.IsAny<bool>()), Throws.TypeOf<NullListException>());
_workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Once);
}
[Test]
public void GetAllWorkersByBirthDate_StorageThrowError_ThrowException_Test()
{
//Arrange
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.GetAllWorkersByBirthDate(DateTime.UtcNow, DateTime.UtcNow.AddDays(1), It.IsAny<bool>()), Throws.TypeOf<StorageException>());
_workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Once);
}
[Test]
public void GetAllWorkersByEmploymentDate_ReturnListOfRecords_Test()
{
//Arrange
var date = DateTime.UtcNow;
var listOriginal = new List<WorkerDataModel>()
{
new(Guid.NewGuid().ToString(), "fio 1", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false),
new(Guid.NewGuid().ToString(), "fio 2", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, true),
new(Guid.NewGuid().ToString(), "fio 3", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false),
};
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Returns(listOriginal);
//Act
var listOnlyActive = _workerBusinessLogicContract.GetAllWorkersByEmploymentDate(date, date.AddDays(1), true);
var list = _workerBusinessLogicContract.GetAllWorkersByEmploymentDate(date, date.AddDays(1), false);
//Assert
Assert.Multiple(() =>
{
Assert.That(listOnlyActive, Is.Not.Null);
Assert.That(list, Is.Not.Null);
Assert.That(listOnlyActive, Is.EquivalentTo(listOriginal));
Assert.That(list, Is.EquivalentTo(listOriginal));
});
_workerStorageContract.Verify(x => x.GetList(true, null, null, null, date, date.AddDays(1)), Times.Once);
_workerStorageContract.Verify(x => x.GetList(false, null, null, null, date, date.AddDays(1)), Times.Once);
}
[Test]
public void GetAllWorkersByEmploymentDate_ReturnEmptyList_Test()
{
//Arrange
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Returns([]);
//Act
var listOnlyActive = _workerBusinessLogicContract.GetAllWorkersByEmploymentDate(DateTime.UtcNow, DateTime.UtcNow.AddDays(1), true);
var list = _workerBusinessLogicContract.GetAllWorkersByEmploymentDate(DateTime.UtcNow, DateTime.UtcNow.AddDays(1), false);
//Assert
Assert.Multiple(() =>
{
Assert.That(listOnlyActive, Is.Not.Null);
Assert.That(list, Is.Not.Null);
Assert.That(listOnlyActive, Has.Count.EqualTo(0));
Assert.That(list, Has.Count.EqualTo(0));
});
_workerStorageContract.Verify(x => x.GetList(true, null, null, null, It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Once);
_workerStorageContract.Verify(x => x.GetList(false, null, null, null, It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Once);
}
[Test]
public void GetAllWorkersByEmploymentDate_IncorrectDates_ThrowException_Test()
{
//Arrange
var date = DateTime.UtcNow;
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.GetAllWorkersByEmploymentDate(date, date, It.IsAny<bool>()), Throws.TypeOf<IncorrectDatesException>());
Assert.That(() => _workerBusinessLogicContract.GetAllWorkersByEmploymentDate(date, date.AddSeconds(-1), It.IsAny<bool>()), Throws.TypeOf<IncorrectDatesException>());
_workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Never);
}
[Test]
public void GetAllWorkersByEmploymentDate_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.GetAllWorkersByEmploymentDate(DateTime.UtcNow, DateTime.UtcNow.AddDays(1), It.IsAny<bool>()), Throws.TypeOf<NullListException>());
_workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Once);
}
[Test]
public void GetAllWorkersByEmploymentDate_StorageThrowError_ThrowException_Test()
{
//Arrange
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.GetAllWorkersByEmploymentDate(DateTime.UtcNow, DateTime.UtcNow.AddDays(1), It.IsAny<bool>()), Throws.TypeOf<StorageException>());
_workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Once);
}
[Test]
public void GetWorkerByData_GetById_ReturnRecord_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
var record = new WorkerDataModel(id, "fio", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false);
_workerStorageContract.Setup(x => x.GetElementById(id)).Returns(record);
//Act
var element = _workerBusinessLogicContract.GetWorkerByData(id);
//Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.Id, Is.EqualTo(id));
_workerStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetWorkerByData_GetByFio_ReturnRecord_Test()
{
//Arrange
var fio = "fio";
var record = new WorkerDataModel(Guid.NewGuid().ToString(), fio, Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false);
_workerStorageContract.Setup(x => x.GetElementByFIO(fio)).Returns(record);
//Act
var element = _workerBusinessLogicContract.GetWorkerByData(fio);
//Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.FIO, Is.EqualTo(fio));
_workerStorageContract.Verify(x => x.GetElementByFIO(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetWorkerByData_EmptyData_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.GetWorkerByData(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _workerBusinessLogicContract.GetWorkerByData(string.Empty), Throws.TypeOf<ArgumentNullException>());
_workerStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Never);
_workerStorageContract.Verify(x => x.GetElementByFIO(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetWorkerByData_GetById_NotFoundRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.GetWorkerByData(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_workerStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
_workerStorageContract.Verify(x => x.GetElementByFIO(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetWorkerByData_GetByFio_NotFoundRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.GetWorkerByData("fio"), Throws.TypeOf<ElementNotFoundException>());
_workerStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Never);
_workerStorageContract.Verify(x => x.GetElementByFIO(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetWorkerByData_StorageThrowError_ThrowException_Test()
{
//Arrange
_workerStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
_workerStorageContract.Setup(x => x.GetElementByFIO(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.GetWorkerByData(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
Assert.That(() => _workerBusinessLogicContract.GetWorkerByData("fio"), Throws.TypeOf<StorageException>());
_workerStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
_workerStorageContract.Verify(x => x.GetElementByFIO(It.IsAny<string>()), Times.Once);
}
[Test]
public void InsertWorker_CorrectRecord_Test()
{
//Arrange
var flag = false;
var record = new WorkerDataModel(Guid.NewGuid().ToString(), "fio", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false);
_workerStorageContract.Setup(x => x.AddElement(It.IsAny<WorkerDataModel>()))
.Callback((WorkerDataModel x) =>
{
flag = x.Id == record.Id && x.FIO == record.FIO && x.PostId == record.PostId && x.BirthDate == record.BirthDate &&
x.EmploymentDate == record.EmploymentDate && x.IsDeleted == record.IsDeleted;
});
//Act
_workerBusinessLogicContract.InsertWorker(record);
//Assert
_workerStorageContract.Verify(x => x.AddElement(It.IsAny<WorkerDataModel>()), Times.Once);
Assert.That(flag);
}
[Test]
public void InsertWorker_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_workerStorageContract.Setup(x => x.AddElement(It.IsAny<WorkerDataModel>())).Throws(new ElementExistsException("Data", "Data"));
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.InsertWorker(new(Guid.NewGuid().ToString(), "fio", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false)), Throws.TypeOf<ElementExistsException>());
_workerStorageContract.Verify(x => x.AddElement(It.IsAny<WorkerDataModel>()), Times.Once);
}
[Test]
public void InsertWorker_NullRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.InsertWorker(null), Throws.TypeOf<ArgumentNullException>());
_workerStorageContract.Verify(x => x.AddElement(It.IsAny<WorkerDataModel>()), Times.Never);
}
[Test]
public void InsertWorker_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.InsertWorker(new WorkerDataModel("id", "fio", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false)), Throws.TypeOf<ValidationException>());
_workerStorageContract.Verify(x => x.AddElement(It.IsAny<WorkerDataModel>()), Times.Never);
}
[Test]
public void InsertWorker_StorageThrowError_ThrowException_Test()
{
//Arrange
_workerStorageContract.Setup(x => x.AddElement(It.IsAny<WorkerDataModel>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.InsertWorker(new(Guid.NewGuid().ToString(), "fio", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false)), Throws.TypeOf<StorageException>());
_workerStorageContract.Verify(x => x.AddElement(It.IsAny<WorkerDataModel>()), Times.Once);
}
[Test]
public void UpdateWorker_CorrectRecord_Test()
{
//Arrange
var flag = false;
var record = new WorkerDataModel(Guid.NewGuid().ToString(), "fio", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false);
_workerStorageContract.Setup(x => x.UpdElement(It.IsAny<WorkerDataModel>()))
.Callback((WorkerDataModel x) =>
{
flag = x.Id == record.Id && x.FIO == record.FIO && x.PostId == record.PostId && x.BirthDate == record.BirthDate &&
x.EmploymentDate == record.EmploymentDate && x.IsDeleted == record.IsDeleted;
});
//Act
_workerBusinessLogicContract.UpdateWorker(record);
//Assert
_workerStorageContract.Verify(x => x.UpdElement(It.IsAny<WorkerDataModel>()), Times.Once);
Assert.That(flag);
}
[Test]
public void UpdateWorker_RecordWithIncorrectData_ThrowException_Test()
{
//Arrange
_workerStorageContract.Setup(x => x.UpdElement(It.IsAny<WorkerDataModel>())).Throws(new ElementNotFoundException(""));
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.UpdateWorker(new(Guid.NewGuid().ToString(), "fio", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false)), Throws.TypeOf<ElementNotFoundException>());
_workerStorageContract.Verify(x => x.UpdElement(It.IsAny<WorkerDataModel>()), Times.Once);
}
[Test]
public void UpdateWorker_NullRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.UpdateWorker(null), Throws.TypeOf<ArgumentNullException>());
_workerStorageContract.Verify(x => x.UpdElement(It.IsAny<WorkerDataModel>()), Times.Never);
}
[Test]
public void UpdateWorker_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.UpdateWorker(new WorkerDataModel("id", "fio", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false)), Throws.TypeOf<ValidationException>());
_workerStorageContract.Verify(x => x.UpdElement(It.IsAny<WorkerDataModel>()), Times.Never);
}
[Test]
public void UpdateWorker_StorageThrowError_ThrowException_Test()
{
//Arrange
_workerStorageContract.Setup(x => x.UpdElement(It.IsAny<WorkerDataModel>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.UpdateWorker(new(Guid.NewGuid().ToString(), "fio", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false)), Throws.TypeOf<StorageException>());
_workerStorageContract.Verify(x => x.UpdElement(It.IsAny<WorkerDataModel>()), Times.Once);
}
[Test]
public void DeleteWorker_CorrectRecord_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
var flag = false;
_workerStorageContract.Setup(x => x.DelElement(It.Is((string x) => x == id))).Callback(() => { flag = true; });
//Act
_workerBusinessLogicContract.DeleteWorker(id);
//Assert
_workerStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
Assert.That(flag);
}
[Test]
public void DeleteWorker_RecordWithIncorrectId_ThrowException_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
_workerStorageContract.Setup(x => x.DelElement(It.Is((string x) => x != id))).Throws(new ElementNotFoundException(id));
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.DeleteWorker(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_workerStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
}
[Test]
public void DeleteWorker_IdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.DeleteWorker(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _workerBusinessLogicContract.DeleteWorker(string.Empty), Throws.TypeOf<ArgumentNullException>());
_workerStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Never);
}
[Test]
public void DeleteWorker_IdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.DeleteWorker("id"), Throws.TypeOf<ValidationException>());
_workerStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Never);
}
[Test]
public void DeleteWorker_StorageThrowError_ThrowException_Test()
{
//Arrange
_workerStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.DeleteWorker(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_workerStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
}
}

View File

@@ -16,51 +16,51 @@ internal class PostDataModelTests
[Test]
public void IdIsNullOrEmptyTest()
{
var post = CreateDataModel(null, Guid.NewGuid().ToString(), "name", PostType.Waiter, 10, true, DateTime.UtcNow);
var post = CreateDataModel("0", "name", PostType.Waiter, 10, true, DateTime.UtcNow);
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
post = CreateDataModel(string.Empty, Guid.NewGuid().ToString(), "name", PostType.Waiter, 10, true, DateTime.UtcNow);
post = CreateDataModel(string.Empty, "name", PostType.Waiter, 10, true, DateTime.UtcNow);
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void IdIsNotGuidTest()
{
var post = CreateDataModel("id", Guid.NewGuid().ToString(), "name", PostType.Waiter, 10, true, DateTime.UtcNow);
var post = CreateDataModel("id", "name", PostType.Waiter, 10, true, DateTime.UtcNow);
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void PostIdIsNullEmptyTest()
{
var post = CreateDataModel(Guid.NewGuid().ToString(), null, "name", PostType.Waiter, 10, true, DateTime.UtcNow);
var post = CreateDataModel("0", "name", PostType.Waiter, 10, true, DateTime.UtcNow);
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
post = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, "name", PostType.Waiter, 10, true, DateTime.UtcNow);
post = CreateDataModel("0", "name", PostType.Waiter, 10, true, DateTime.UtcNow);
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void PostIdIsNotGuidTest()
{
var post = CreateDataModel(Guid.NewGuid().ToString(), "postId", "name", PostType.Waiter, 10, true, DateTime.UtcNow);
var post = CreateDataModel("0", "name", PostType.Waiter, 10, true, DateTime.UtcNow);
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void PostNameIsEmptyTest()
{
var manufacturer = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, PostType.Waiter, 10, true, DateTime.UtcNow);
var manufacturer = CreateDataModel(Guid.NewGuid().ToString(), null, PostType.Waiter, 10, true, DateTime.UtcNow);
Assert.That(() => manufacturer.Validate(), Throws.TypeOf<ValidationException>());
manufacturer = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), string.Empty, PostType.Waiter, 10, true, DateTime.UtcNow);
manufacturer = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, PostType.Waiter, 10, true, DateTime.UtcNow);
Assert.That(() => manufacturer.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void PostTypeIsNoneTest()
{
var post = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), "name", PostType.None, 10, true, DateTime.UtcNow);
var post = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.None, 10, true, DateTime.UtcNow);
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void SalaryIsLessOrZeroTest()
{
var post = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), "name", PostType.Waiter, 0, true, DateTime.UtcNow);
var post = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.Waiter, 0, true, DateTime.UtcNow);
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
post = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), "name", PostType.Waiter, -10, true, DateTime.UtcNow);
post = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.Waiter, -10, true, DateTime.UtcNow);
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
@@ -73,20 +73,17 @@ internal class PostDataModelTests
var salary = 10;
var isActual = false;
var changeDate = DateTime.UtcNow.AddDays(-1);
var post = CreateDataModel(postId, postPostId, postName, postType, salary, isActual, changeDate);
var post = CreateDataModel(postId, postName, postType, salary, isActual, changeDate);
Assert.That(() => post.Validate(), Throws.Nothing);
Assert.Multiple(() =>
{
Assert.That(post.Id, Is.EqualTo(postId));
Assert.That(post.PostId, Is.EqualTo(postPostId));
Assert.That(post.PostName, Is.EqualTo(postName));
Assert.That(post.PostType, Is.EqualTo(postType));
Assert.That(post.Salary, Is.EqualTo(salary));
Assert.That(post.IsActual, Is.EqualTo(isActual));
Assert.That(post.ChangeDate, Is.EqualTo(changeDate));
});
}
private static PostDataModel CreateDataModel(string? id, string? postId, string? postName, PostType postType, double salary, bool isActual, DateTime changeDate) => new(id, postId, postName, postType, salary, isActual, changeDate);
private static PostDataModel CreateDataModel(string? id, string? postName, PostType postType, double salary, bool isActual, DateTime changeDate) => new(id, postName, postType, salary, isActual, changeDate);
}

View File

@@ -0,0 +1,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));
});
}
}