PIbd-22 Pyzhov E.A. LabWork 4 #6
@@ -9,7 +9,7 @@ using SquirrelContract.DataModels;
|
||||
|
||||
namespace SquirrelBusinessLogic.Implementations;
|
||||
|
||||
internal class ClientBusinessLogicContract(IClientStorageContract clientStorageContract, ILogger logger) : IClientBusinessLogicContract
|
||||
public class ClientBusinessLogicContract(IClientStorageContract clientStorageContract, ILogger logger) : IClientBusinessLogicContract
|
||||
{
|
||||
private readonly ILogger _logger = logger;
|
||||
private readonly IClientStorageContract _clientStorageContract = clientStorageContract;
|
||||
|
||||
@@ -9,7 +9,7 @@ using System.Text.RegularExpressions;
|
||||
|
||||
namespace SquirrelBusinessLogic.Implementations;
|
||||
|
||||
internal class CocktailBusinessLogicContract(ICocktailStorageContract cocktailStorageContract, ILogger logger) : ICocktailBusinessLogicContract
|
||||
public class CocktailBusinessLogicContract(ICocktailStorageContract cocktailStorageContract, ILogger logger) : ICocktailBusinessLogicContract
|
||||
{
|
||||
private readonly ILogger _logger = logger;
|
||||
private readonly ICocktailStorageContract _cocktailStorageContract = cocktailStorageContract;
|
||||
|
||||
@@ -9,7 +9,7 @@ using System.Text.RegularExpressions;
|
||||
|
||||
namespace SquirrelBusinessLogic.Implementations;
|
||||
|
||||
internal class EmployeeBusinessLogicContract(IEmployeeStorageContract employeeStorageContract, ILogger logger) : IEmployeeBusinessLogicContract
|
||||
public class EmployeeBusinessLogicContract(IEmployeeStorageContract employeeStorageContract, ILogger logger) : IEmployeeBusinessLogicContract
|
||||
{
|
||||
private readonly ILogger _logger = logger;
|
||||
private readonly IEmployeeStorageContract _employeeStorageContract = employeeStorageContract;
|
||||
|
||||
@@ -8,14 +8,14 @@ using System.Text.Json;
|
||||
|
||||
namespace SquirrelBusinessLogic.Implementations;
|
||||
|
||||
internal class PostBusinessLogicContract(IPostStorageContract postStorageContract, ILogger logger) : IPostBusinessLogicContract
|
||||
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)
|
||||
public List<PostDataModel> GetAllPosts()
|
||||
{
|
||||
_logger.LogInformation("GetAllPosts params: {onlyActive}", onlyActive);
|
||||
return _postStorageContract.GetList(onlyActive) ?? throw new NullListException();
|
||||
_logger.LogInformation("GetAllPosts");
|
||||
return _postStorageContract.GetList() ?? throw new NullListException();
|
||||
}
|
||||
|
||||
public List<PostDataModel> GetAllDataOfPost(string postId)
|
||||
|
||||
@@ -7,7 +7,7 @@ using SquirrelContract.StoragesContracts;
|
||||
|
||||
namespace SquirrelBusinessLogic.Implementations;
|
||||
|
||||
internal class SalaryBusinessLogicContract(ISalaryStorageContract salaryStorageContract,
|
||||
public class SalaryBusinessLogicContract(ISalaryStorageContract salaryStorageContract,
|
||||
ISaleStorageContract saleStorageContract, IPostStorageContract postStorageContract, IEmployeeStorageContract employeeStorageContract, ILogger logger) : ISalaryBusinessLogicContract
|
||||
{
|
||||
private readonly ILogger _logger = logger;
|
||||
@@ -57,7 +57,7 @@ internal class SalaryBusinessLogicContract(ISalaryStorageContract salaryStorageC
|
||||
throw new NullListException();
|
||||
var salary = post.Salary + sales * 0.1;
|
||||
_logger.LogDebug("The employee {employeeId} was paid a salary of {salary}", employee.Id, salary);
|
||||
_salaryStorageContract.AddElement(new SalaryDataModel(employee.Id, finishDate, salary));
|
||||
_salaryStorageContract.AddElement(new SalaryDataModel(employee.Id, DateTime.SpecifyKind(finishDate, DateTimeKind.Utc), salary));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ using System.Text.Json;
|
||||
|
||||
namespace SquirrelBusinessLogic.Implementations;
|
||||
|
||||
internal class SaleBusinessLogicContract(ISaleStorageContract
|
||||
public class SaleBusinessLogicContract(ISaleStorageContract
|
||||
saleStorageContract, ILogger logger) : ISaleBusinessLogicContract
|
||||
{
|
||||
private readonly ILogger _logger = logger;
|
||||
|
||||
@@ -11,6 +11,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SquirrelBusinessLogic", "Sq
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SquirrelDatabase", "SquirrelDatabase\SquirrelDatabase.csproj", "{A8A7A434-A278-4362-8D34-C2E3CAA938C1}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SquirrelWebApi", "SquirrelWebApi\SquirrelWebApi.csproj", "{45D1F24F-AFCD-4259-88C2-3076E38254A9}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
@@ -33,8 +35,15 @@ Global
|
||||
{A8A7A434-A278-4362-8D34-C2E3CAA938C1}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{A8A7A434-A278-4362-8D34-C2E3CAA938C1}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{A8A7A434-A278-4362-8D34-C2E3CAA938C1}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{45D1F24F-AFCD-4259-88C2-3076E38254A9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{45D1F24F-AFCD-4259-88C2-3076E38254A9}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{45D1F24F-AFCD-4259-88C2-3076E38254A9}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{45D1F24F-AFCD-4259-88C2-3076E38254A9}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
EndGlobalSection
|
||||
GlobalSection(ExtensibilityGlobals) = postSolution
|
||||
SolutionGuid = {E3B65E92-8603-4ED7-8214-9DA9A305DAFF}
|
||||
EndGlobalSection
|
||||
EndGlobal
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
namespace SquirrelContract.AdapterContracts;
|
||||
using SquirrelContract.AdapterContracts.OperationResponses;
|
||||
using SquirrelContract.BindingModels;
|
||||
|
||||
public interface IClientAdapter
|
||||
{
|
||||
ClientOperationResponse GetList();
|
||||
|
||||
ClientOperationResponse GetElement(string data);
|
||||
|
||||
ClientOperationResponse RegisterClient(ClientBindingModel clientModel);
|
||||
|
||||
ClientOperationResponse ChangeClientInfo(ClientBindingModel clientModel);
|
||||
|
||||
ClientOperationResponse RemoveClient(string id);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
using SquirrelContract.BindingModels;
|
||||
using SquirrelContract.AdapterContracts.OperationResponses;
|
||||
|
||||
namespace SquirrelContract.AdapterContracts;
|
||||
|
||||
public interface ICocktailAdapter
|
||||
{
|
||||
CocktailOperationResponse GetList(bool includeDeleted);
|
||||
|
||||
CocktailOperationResponse GetHistory(string id);
|
||||
|
||||
CocktailOperationResponse GetElement(string data);
|
||||
|
||||
CocktailOperationResponse RegisterCocktail(CocktailBindingModel cocktailModel);
|
||||
|
||||
CocktailOperationResponse ChangeCocktailInfo(CocktailBindingModel cocktailModel);
|
||||
|
||||
CocktailOperationResponse RemoveCocktail(string id);
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
using SquirrelContract.AdapterContracts.OperationResponses;
|
||||
using SquirrelContract.BindingModels;
|
||||
|
||||
namespace SquirrelContract.AdapterContracts;
|
||||
|
||||
public interface IEmployeeAdapter
|
||||
{
|
||||
EmployeeOperationResponse GetList(bool includeDeleted);
|
||||
|
||||
EmployeeOperationResponse GetPostList(string id, bool includeDeleted);
|
||||
|
||||
EmployeeOperationResponse GetListByBirthDate(DateTime fromDate, DateTime toDate, bool includeDeleted);
|
||||
|
||||
EmployeeOperationResponse GetListByEmploymentDate(DateTime fromDate, DateTime toDate, bool includeDeleted);
|
||||
|
||||
EmployeeOperationResponse GetElement(string data);
|
||||
|
||||
EmployeeOperationResponse RegisterEmployee(EmployeeBindingModel employeeModel);
|
||||
|
||||
EmployeeOperationResponse ChangeEmployeeInfo(EmployeeBindingModel employeeModel);
|
||||
|
||||
EmployeeOperationResponse RemoveEmployee(string id);
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
using SquirrelContract.AdapterContracts.OperationResponses;
|
||||
using SquirrelContract.BindingModels;
|
||||
|
||||
namespace SquirrelContract.AdapterContracts;
|
||||
|
||||
public interface IPostAdapter
|
||||
{
|
||||
PostOperationResponse GetList();
|
||||
|
||||
PostOperationResponse GetHistory(string id);
|
||||
|
||||
PostOperationResponse GetElement(string data);
|
||||
|
||||
PostOperationResponse RegisterPost(PostBindingModel postModel);
|
||||
|
||||
PostOperationResponse ChangePostInfo(PostBindingModel postModel);
|
||||
|
||||
PostOperationResponse RemovePost(string id);
|
||||
|
||||
PostOperationResponse RestorePost(string id);
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
using SquirrelContract.AdapterContracts.OperationResponses;
|
||||
|
||||
namespace SquirrelContract.AdapterContracts;
|
||||
|
||||
public interface ISalaryAdapter
|
||||
{
|
||||
SalaryOperationResponse GetListByPeriod(DateTime fromDate, DateTime toDate);
|
||||
SalaryOperationResponse GetListByPeriodByEmployee(DateTime fromDate, DateTime toDate, string employeeId);
|
||||
SalaryOperationResponse CalculateSalary(DateTime date);
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
using SquirrelContract.AdapterContracts.OperationResponses;
|
||||
using SquirrelContract.BindingModels;
|
||||
|
||||
namespace SquirrelContract.AdapterContracts;
|
||||
|
||||
public interface ISaleAdapter
|
||||
{
|
||||
SaleOperationResponse GetList(DateTime fromDate, DateTime toDate);
|
||||
|
||||
SaleOperationResponse GetEmployeeList(string id, DateTime fromDate, DateTime toDate);
|
||||
|
||||
SaleOperationResponse GetClientList(string id, DateTime fromDate, DateTime toDate);
|
||||
|
||||
SaleOperationResponse GetCocktailList(string id, DateTime fromDate, DateTime toDate);
|
||||
|
||||
SaleOperationResponse GetElement(string id);
|
||||
|
||||
SaleOperationResponse MakeSale(SaleBindingModel saleModel);
|
||||
|
||||
SaleOperationResponse CancelSale(string id);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
using SquirrelContract.ViewModels;
|
||||
using SquirrelContract.Infrastructure;
|
||||
|
||||
namespace SquirrelContract.AdapterContracts.OperationResponses;
|
||||
|
||||
public class ClientOperationResponse : OperationResponse
|
||||
{
|
||||
public static ClientOperationResponse OK(List<ClientViewModel> data) => OK<ClientOperationResponse, List<ClientViewModel>>(data);
|
||||
|
||||
public static ClientOperationResponse OK(ClientViewModel data) => OK<ClientOperationResponse, ClientViewModel>(data);
|
||||
|
||||
public static ClientOperationResponse NoContent() => NoContent<ClientOperationResponse>();
|
||||
|
||||
public static ClientOperationResponse BadRequest(string message) => BadRequest<ClientOperationResponse>(message);
|
||||
|
||||
public static ClientOperationResponse NotFound(string message) => NotFound<ClientOperationResponse>(message);
|
||||
|
||||
public static ClientOperationResponse InternalServerError(string message) => InternalServerError<ClientOperationResponse>(message);
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
using SquirrelContract.ViewModels;
|
||||
using SquirrelContract.Infrastructure;
|
||||
|
||||
namespace SquirrelContract.AdapterContracts.OperationResponses;
|
||||
|
||||
public class CocktailOperationResponse : OperationResponse
|
||||
{
|
||||
public static CocktailOperationResponse OK(List<CocktailViewModel> data) => OK<CocktailOperationResponse, List<CocktailViewModel>>(data);
|
||||
|
||||
public static CocktailOperationResponse OK(List<CocktailHistoryViewModel> data) => OK<CocktailOperationResponse, List<CocktailHistoryViewModel>>(data);
|
||||
|
||||
public static CocktailOperationResponse OK(CocktailViewModel data) => OK<CocktailOperationResponse, CocktailViewModel>(data);
|
||||
|
||||
public static CocktailOperationResponse NoContent() => NoContent<CocktailOperationResponse>();
|
||||
|
||||
public static CocktailOperationResponse NotFound(string message) => NotFound<CocktailOperationResponse>(message);
|
||||
|
||||
public static CocktailOperationResponse BadRequest(string message) => BadRequest<CocktailOperationResponse>(message);
|
||||
|
||||
public static CocktailOperationResponse InternalServerError(string message) => InternalServerError<CocktailOperationResponse>(message);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
using SquirrelContract.ViewModels;
|
||||
using SquirrelContract.Infrastructure;
|
||||
|
||||
namespace SquirrelContract.AdapterContracts.OperationResponses;
|
||||
|
||||
public class EmployeeOperationResponse : OperationResponse
|
||||
{
|
||||
public static EmployeeOperationResponse OK(List<EmployeeViewModel> data) => OK<EmployeeOperationResponse, List<EmployeeViewModel>>(data);
|
||||
|
||||
public static EmployeeOperationResponse OK(EmployeeViewModel data) => OK<EmployeeOperationResponse, EmployeeViewModel>(data);
|
||||
|
||||
public static EmployeeOperationResponse NoContent() => NoContent<EmployeeOperationResponse>();
|
||||
|
||||
public static EmployeeOperationResponse NotFound(string message) => NotFound<EmployeeOperationResponse>(message);
|
||||
|
||||
public static EmployeeOperationResponse BadRequest(string message) => BadRequest<EmployeeOperationResponse>(message);
|
||||
|
||||
public static EmployeeOperationResponse InternalServerError(string message) => InternalServerError<EmployeeOperationResponse>(message);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
using SquirrelContract.Infrastructure;
|
||||
using SquirrelContract.ViewModels;
|
||||
|
||||
namespace SquirrelContract.AdapterContracts.OperationResponses;
|
||||
|
||||
public class PostOperationResponse : OperationResponse
|
||||
{
|
||||
public static PostOperationResponse OK(List<PostViewModel> data) => OK<PostOperationResponse, List<PostViewModel>>(data);
|
||||
|
||||
public static PostOperationResponse OK(PostViewModel data) => OK<PostOperationResponse, PostViewModel>(data);
|
||||
|
||||
public static PostOperationResponse NoContent() => NoContent<PostOperationResponse>();
|
||||
|
||||
public static PostOperationResponse NotFound(string message) => NotFound<PostOperationResponse>(message);
|
||||
|
||||
public static PostOperationResponse BadRequest(string message) => BadRequest<PostOperationResponse>(message);
|
||||
|
||||
public static PostOperationResponse InternalServerError(string message) => InternalServerError<PostOperationResponse>(message);
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
using SquirrelContract.Infrastructure;
|
||||
using SquirrelContract.ViewModels;
|
||||
|
||||
namespace SquirrelContract.AdapterContracts.OperationResponses;
|
||||
|
||||
public class SalaryOperationResponse : OperationResponse
|
||||
{
|
||||
public static SalaryOperationResponse OK(List<SalaryViewModel> data) => OK<SalaryOperationResponse, List<SalaryViewModel>>(data);
|
||||
public static SalaryOperationResponse NoContent() => NoContent<SalaryOperationResponse>();
|
||||
public static SalaryOperationResponse NotFound(string message) => NotFound<SalaryOperationResponse>(message);
|
||||
public static SalaryOperationResponse BadRequest(string message) => BadRequest<SalaryOperationResponse>(message);
|
||||
public static SalaryOperationResponse InternalServerError(string message) => InternalServerError<SalaryOperationResponse>(message);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
using SquirrelContract.ViewModels;
|
||||
using SquirrelContract.Infrastructure;
|
||||
|
||||
namespace SquirrelContract.AdapterContracts.OperationResponses;
|
||||
|
||||
public class SaleOperationResponse : OperationResponse
|
||||
{
|
||||
public static SaleOperationResponse OK(List<SaleViewModel> data) => OK<SaleOperationResponse, List<SaleViewModel>>(data);
|
||||
|
||||
public static SaleOperationResponse OK(SaleViewModel data) => OK<SaleOperationResponse, SaleViewModel>(data);
|
||||
|
||||
public static SaleOperationResponse NoContent() => NoContent<SaleOperationResponse>();
|
||||
|
||||
public static SaleOperationResponse NotFound(string message) => NotFound<SaleOperationResponse>(message);
|
||||
|
||||
public static SaleOperationResponse BadRequest(string message) => BadRequest<SaleOperationResponse>(message);
|
||||
|
||||
public static SaleOperationResponse InternalServerError(string message) => InternalServerError<SaleOperationResponse>(message);
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
namespace SquirrelContract.BindingModels;
|
||||
|
||||
public class ClientBindingModel
|
||||
{
|
||||
public string? Id { get; set; }
|
||||
|
||||
public string? FIO { get; set; }
|
||||
|
||||
public string? PhoneNumber { get; set; }
|
||||
|
||||
public double DiscountSize { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
namespace SquirrelContract.BindingModels;
|
||||
|
||||
public class CocktailBindingModel
|
||||
{
|
||||
public string? Id { get; set; }
|
||||
public string? CocktailName { get; set; }
|
||||
public double Price { get; set; }
|
||||
public string? BaseAlcohol { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
namespace SquirrelContract.BindingModels;
|
||||
|
||||
public class EmployeeBindingModel
|
||||
{
|
||||
public string? Id { get; set; }
|
||||
|
||||
public string? FIO { get; set; }
|
||||
|
||||
public string? Email { get; set; }
|
||||
|
||||
public string? PostId { get; set; }
|
||||
|
||||
public DateTime BirthDate { get; set; }
|
||||
|
||||
public DateTime EmploymentDate { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
namespace SquirrelContract.BindingModels;
|
||||
|
||||
public class PostBindingModel
|
||||
{
|
||||
public string? Id { get; set; }
|
||||
|
||||
public string? PostId => Id;
|
||||
|
||||
public string? PostName { get; set; }
|
||||
|
||||
public string? PostType { get; set; }
|
||||
|
||||
public double Salary { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
namespace SquirrelContract.BindingModels;
|
||||
|
||||
public class SaleBindingModel
|
||||
{
|
||||
public string? Id { get; set; }
|
||||
|
||||
public string? EmployeeId { get; set; }
|
||||
|
||||
public string? ClientId { get; set; }
|
||||
|
||||
public int DiscountType { get; set; }
|
||||
|
||||
public List<SaleCocktailBindingModel>? Cocktails { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
namespace SquirrelContract.BindingModels;
|
||||
|
||||
public class SaleCocktailBindingModel
|
||||
{
|
||||
public string? SaleId { get; set; }
|
||||
|
||||
public string? CocktailId { get; set; }
|
||||
|
||||
public int Count { get; set; }
|
||||
|
||||
public double Price { get; set; }
|
||||
}
|
||||
@@ -4,7 +4,7 @@ namespace SquirrelContract.BusinessLogicContracts;
|
||||
|
||||
public interface IPostBusinessLogicContract
|
||||
{
|
||||
List<PostDataModel> GetAllPosts(bool onlyActive);
|
||||
List<PostDataModel> GetAllPosts();
|
||||
|
||||
List<PostDataModel> GetAllDataOfPost(string postId);
|
||||
|
||||
|
||||
@@ -6,12 +6,22 @@ namespace SquirrelContract.DataModels;
|
||||
|
||||
public class CocktailHistoryDataModel(string cocktailId, double oldPrice) : IValidation
|
||||
{
|
||||
private readonly CocktailDataModel? _cocktail;
|
||||
|
||||
public string CocktailId { get; private set; } = cocktailId;
|
||||
|
||||
public double OldPrice { get; private set; } = oldPrice;
|
||||
|
||||
public DateTime ChangeDate { get; private set; } = DateTime.UtcNow;
|
||||
|
||||
public string CocktailName => _cocktail?.CocktailName ?? string.Empty;
|
||||
|
||||
public CocktailHistoryDataModel(string cocktailId, double oldPrice, DateTime changeDate, CocktailDataModel cocktail) : this(cocktailId, oldPrice)
|
||||
{
|
||||
ChangeDate = changeDate;
|
||||
_cocktail = cocktail;
|
||||
}
|
||||
|
||||
public void Validate()
|
||||
{
|
||||
if (CocktailId.IsEmpty())
|
||||
|
||||
@@ -7,6 +7,8 @@ namespace SquirrelContract.DataModels;
|
||||
|
||||
public class EmployeeDataModel(string id, string fio, string email, string postId, DateTime birthDate, DateTime employmentDate, bool isDeleted) : IValidation
|
||||
{
|
||||
private readonly PostDataModel? _post;
|
||||
|
||||
public string Id { get; private set; } = id;
|
||||
|
||||
public string FIO { get; private set; } = fio;
|
||||
@@ -21,6 +23,15 @@ public class EmployeeDataModel(string id, string fio, string email, string postI
|
||||
|
||||
public bool IsDeleted { get; private set; } = isDeleted;
|
||||
|
||||
public string PostName => _post?.PostName ?? string.Empty;
|
||||
|
||||
public EmployeeDataModel(string id, string fio, string email, string postId, DateTime birthDate, DateTime employmentDate, bool isDeleted, PostDataModel post) : this(id, fio, email, postId, birthDate, employmentDate, isDeleted)
|
||||
{
|
||||
_post = post;
|
||||
}
|
||||
|
||||
public EmployeeDataModel(string id, string fio, string email, string postId, DateTime birthDate, DateTime employmentDate) : this(id, fio, email, postId, birthDate, employmentDate, false) { }
|
||||
|
||||
public void Validate()
|
||||
{
|
||||
if (Id.IsEmpty())
|
||||
|
||||
@@ -5,7 +5,7 @@ using SquirrelContract.Infastructure;
|
||||
|
||||
namespace SquirrelContract.DataModels;
|
||||
|
||||
public class PostDataModel(string postId, string postName, PostType postType, double salary, bool isActual, DateTime changeDate) : IValidation
|
||||
public class PostDataModel(string postId, string postName, PostType postType, double salary) : IValidation
|
||||
{
|
||||
public string Id { get; private set; } = postId;
|
||||
|
||||
@@ -15,10 +15,6 @@ public class PostDataModel(string postId, string postName, PostType postType, do
|
||||
|
||||
public double Salary { get; private set; } = salary;
|
||||
|
||||
public bool IsActual { get; private set; } = isActual;
|
||||
|
||||
public DateTime ChangeDate { get; private set; } = changeDate;
|
||||
|
||||
public void Validate()
|
||||
{
|
||||
if (Id.IsEmpty())
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using SquirrelContract.Exceptions;
|
||||
using SquirrelContract.DataModels;
|
||||
using SquirrelContract.Exceptions;
|
||||
using SquirrelContract.Extensions;
|
||||
using SquirrelContract.Infastructure;
|
||||
|
||||
@@ -6,12 +7,21 @@ namespace BarBelochkaContract.DataModels;
|
||||
|
||||
public class SalaryDataModel(string employeeId, DateTime salaryDate, double employeeSalary) : IValidation
|
||||
{
|
||||
private readonly EmployeeDataModel? _employee;
|
||||
|
||||
public string EmployeeId { get; private set; } = employeeId;
|
||||
|
||||
public DateTime SalaryDate { get; private set; } = salaryDate;
|
||||
|
||||
public double Salary { get; private set; } = employeeSalary;
|
||||
|
||||
public string EmployeeFIO => _employee?.FIO ?? string.Empty;
|
||||
|
||||
public SalaryDataModel(string employeeId, DateTime salaryDate, double employeeSalary, EmployeeDataModel employee) : this(employeeId, salaryDate, employeeSalary)
|
||||
{
|
||||
_employee = employee;
|
||||
}
|
||||
|
||||
public void Validate()
|
||||
{
|
||||
if (EmployeeId.IsEmpty())
|
||||
|
||||
@@ -4,14 +4,25 @@ using SquirrelContract.Infastructure;
|
||||
|
||||
namespace SquirrelContract.DataModels;
|
||||
|
||||
public class SaleCocktailDataModel(string saleId, string cocktailId, int count) : IValidation
|
||||
public class SaleCocktailDataModel(string saleId, string cocktailId, int count, double price) : IValidation
|
||||
{
|
||||
private readonly CocktailDataModel? _cocktail;
|
||||
|
||||
public string SaleId { get; private set; } = saleId;
|
||||
|
||||
public string CocktailId { get; private set; } = cocktailId;
|
||||
|
||||
public int Count { get; private set; } = count;
|
||||
|
||||
public double Price { get; private set; } = price;
|
||||
|
||||
public string CocktailName => _cocktail?.CocktailName ?? string.Empty;
|
||||
|
||||
public SaleCocktailDataModel(string saleId, string cocktailId, int count, double price, CocktailDataModel cocktail) : this(saleId, cocktailId, count, price)
|
||||
{
|
||||
_cocktail = cocktail;
|
||||
}
|
||||
|
||||
public void Validate()
|
||||
{
|
||||
if (SaleId.IsEmpty())
|
||||
@@ -21,12 +32,15 @@ public class SaleCocktailDataModel(string saleId, string cocktailId, int count)
|
||||
throw new ValidationException("The value in the field SaleId is not a unique identifier");
|
||||
|
||||
if (CocktailId.IsEmpty())
|
||||
throw new ValidationException("Field ProductId is empty");
|
||||
throw new ValidationException("Field CocktailId is empty");
|
||||
|
||||
if (!CocktailId.IsGuid())
|
||||
throw new ValidationException("The value in the field ProductId is not a unique identifier");
|
||||
throw new ValidationException("The value in the field CocktailId is not a unique identifier");
|
||||
|
||||
if (Count <= 0)
|
||||
throw new ValidationException("Field Count is less than or equal to 0");
|
||||
|
||||
if (Price <= 0)
|
||||
throw new ValidationException("Field Price is less than or equal to 0");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,25 +5,76 @@ using SquirrelContract.Infastructure;
|
||||
|
||||
namespace SquirrelContract.DataModels;
|
||||
|
||||
public class SaleDataModel(string id, string employeeId, string? clientId, double sum, DiscountType discountType, double discount, bool isCancel, List<SaleCocktailDataModel> saleCocktails) : IValidation
|
||||
public class SaleDataModel : IValidation
|
||||
{
|
||||
public string Id { get; private set; } = id;
|
||||
private readonly ClientDataModel? _client;
|
||||
|
||||
public string EmployeeId { get; private set; } = employeeId;
|
||||
private readonly EmployeeDataModel? _employee;
|
||||
|
||||
public string? ClientId { get; private set; } = clientId;
|
||||
public string Id { get; private set; }
|
||||
|
||||
public string EmployeeId { get; private set; }
|
||||
|
||||
public string? ClientId { get; private set; }
|
||||
|
||||
public DateTime SaleDate { get; private set; } = DateTime.UtcNow;
|
||||
|
||||
public double Sum { get; private set; } = sum;
|
||||
public double Sum { get; private set; }
|
||||
|
||||
public DiscountType DiscountType { get; private set; } = discountType;
|
||||
public DiscountType DiscountType { get; private set; }
|
||||
|
||||
public double Discount { get; private set; } = discount;
|
||||
|
||||
public bool IsCancel { get; private set; } = isCancel;
|
||||
public double Discount { get; private set; }
|
||||
|
||||
public List<SaleCocktailDataModel> Cocktails { get; private set; } = saleCocktails;
|
||||
public bool IsCancel { get; private set; }
|
||||
|
||||
public List<SaleCocktailDataModel>? Cocktails { get; private set; }
|
||||
|
||||
public string ClientFIO => _client?.FIO ?? string.Empty;
|
||||
|
||||
public string EmployeeFIO => _employee?.FIO ?? string.Empty;
|
||||
|
||||
public SaleDataModel(string id, string employeeId, string? clientId, DiscountType discountType, bool isCancel, List<SaleCocktailDataModel> saleCocktails)
|
||||
{
|
||||
Id = id;
|
||||
EmployeeId = employeeId;
|
||||
ClientId = clientId;
|
||||
DiscountType = discountType;
|
||||
IsCancel = isCancel;
|
||||
Cocktails = saleCocktails;
|
||||
var percent = 0.0;
|
||||
foreach (DiscountType elem in Enum.GetValues<DiscountType>())
|
||||
{
|
||||
if ((elem & discountType) != 0)
|
||||
{
|
||||
switch (elem)
|
||||
{
|
||||
case DiscountType.None:
|
||||
break;
|
||||
case DiscountType.OnSale:
|
||||
percent += 0.1;
|
||||
break;
|
||||
case DiscountType.RegularCustomer:
|
||||
percent += 0.5;
|
||||
break;
|
||||
case DiscountType.Certificate:
|
||||
percent += 0.3;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
Sum = Cocktails?.Sum(x => x.Price * x.Count) ?? 0;
|
||||
Discount = Sum * percent;
|
||||
}
|
||||
|
||||
public SaleDataModel(string id, string employeeId, string? clientId, double sum, DiscountType discountType, double discount, bool isCancel, List<SaleCocktailDataModel> saleCocktails, EmployeeDataModel employee, ClientDataModel? client) : this(id, employeeId, clientId, discountType, isCancel, saleCocktails)
|
||||
{
|
||||
Sum = sum;
|
||||
Discount = discount;
|
||||
_employee = employee;
|
||||
_client = client;
|
||||
}
|
||||
|
||||
public SaleDataModel(string id, string employeeId, string? clientId, int discountType, List<SaleCocktailDataModel> cocktails) : this(id, employeeId, clientId, (DiscountType)discountType, false, cocktails) { }
|
||||
|
||||
public void Validate()
|
||||
{
|
||||
@@ -40,7 +91,7 @@ public class SaleDataModel(string id, string employeeId, string? clientId, doubl
|
||||
throw new ValidationException("The value in the field EmployeeId is not a unique identifier");
|
||||
|
||||
if (!ClientId?.IsGuid() ?? !ClientId?.IsEmpty() ?? false)
|
||||
throw new ValidationException("The value in the field BuyerId is not a unique identifier");
|
||||
throw new ValidationException("The value in the field ClientId is not a unique identifier");
|
||||
|
||||
if (Sum <= 0)
|
||||
throw new ValidationException("Field Sum is less than or equal to 0");
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using System.Net;
|
||||
|
||||
namespace SquirrelContract.Infrastructure;
|
||||
|
||||
public class OperationResponse
|
||||
{
|
||||
protected HttpStatusCode StatusCode { get; set; }
|
||||
|
||||
protected object? Result { get; set; }
|
||||
|
||||
public IActionResult GetResponse(HttpRequest request, HttpResponse response)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(request);
|
||||
ArgumentNullException.ThrowIfNull(response);
|
||||
|
||||
response.StatusCode = (int)StatusCode;
|
||||
|
||||
if (Result is null)
|
||||
{
|
||||
return new StatusCodeResult((int)StatusCode);
|
||||
}
|
||||
|
||||
return new ObjectResult(Result);
|
||||
}
|
||||
|
||||
protected static TResult OK<TResult, TData>(TData data) where TResult : OperationResponse, new() => new() { StatusCode = HttpStatusCode.OK, Result = data };
|
||||
|
||||
protected static TResult NoContent<TResult>() where TResult : OperationResponse, new() => new() { StatusCode = HttpStatusCode.NoContent };
|
||||
|
||||
protected static TResult BadRequest<TResult>(string? errorMessage = null) where TResult : OperationResponse, new() => new() { StatusCode = HttpStatusCode.BadRequest, Result = errorMessage };
|
||||
|
||||
protected static TResult NotFound<TResult>(string? errorMessage = null) where TResult : OperationResponse, new() => new() { StatusCode = HttpStatusCode.NotFound, Result = errorMessage };
|
||||
|
||||
protected static TResult InternalServerError<TResult>(string? errorMessage = null) where TResult : OperationResponse, new() => new() { StatusCode = HttpStatusCode.InternalServerError, Result = errorMessage };
|
||||
}
|
||||
@@ -6,4 +6,9 @@
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.AspNetCore.Mvc.Abstractions" Version="2.3.0" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Mvc.Core" Version="2.3.0" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
||||
@@ -4,7 +4,7 @@ namespace SquirrelContract.StoragesContracts;
|
||||
|
||||
public interface IPostStorageContract
|
||||
{
|
||||
List<PostDataModel> GetList(bool onlyActual = true);
|
||||
List<PostDataModel> GetList();
|
||||
List<PostDataModel> GetPostWithHistory(string postId);
|
||||
PostDataModel? GetElementById(string id);
|
||||
PostDataModel? GetElementByName(string name);
|
||||
|
||||
@@ -4,7 +4,7 @@ namespace SquirrelContract.StoragesContracts;
|
||||
|
||||
public interface ISalaryStorageContract
|
||||
{
|
||||
List<SalaryDataModel> GetList(DateTime startDate, DateTime endDate, string? employeeId = null);
|
||||
List<SalaryDataModel> GetList(DateTime? startDate, DateTime? endDate, string? employeeId = null);
|
||||
|
||||
void AddElement(SalaryDataModel salaryDataModel);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
namespace SquirrelContract.ViewModels;
|
||||
|
||||
public class ClientViewModel
|
||||
{
|
||||
public required string Id { get; set; }
|
||||
|
||||
public required string FIO { get; set; }
|
||||
|
||||
public required string PhoneNumber { get; set; }
|
||||
|
||||
public double DiscountSize { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
namespace SquirrelContract.ViewModels;
|
||||
|
||||
public class CocktailHistoryViewModel
|
||||
{
|
||||
public required string CocktailName { get; set; }
|
||||
|
||||
public double OldPrice { get; set; }
|
||||
|
||||
public DateTime ChangeDate { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
namespace SquirrelContract.ViewModels;
|
||||
|
||||
public class CocktailViewModel
|
||||
{
|
||||
public required string Id { get; set; }
|
||||
|
||||
public required string CocktailName { get; set; }
|
||||
|
||||
public required string BaseAlcohol { get; set; }
|
||||
|
||||
public double Price { get; set; }
|
||||
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
namespace SquirrelContract.ViewModels;
|
||||
|
||||
public class EmployeeViewModel
|
||||
{
|
||||
public required string Id { get; set; }
|
||||
|
||||
public required string FIO { get; set; }
|
||||
|
||||
public string Email { get; set; }
|
||||
|
||||
public required string PostId { get; set; }
|
||||
|
||||
public required string PostName { get; set; }
|
||||
|
||||
public bool IsDeleted { get; set; }
|
||||
|
||||
public DateTime BirthDate { get; set; }
|
||||
|
||||
public DateTime EmploymentDate { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
namespace SquirrelContract.ViewModels;
|
||||
|
||||
public class PostViewModel
|
||||
{
|
||||
public required string Id { get; set; }
|
||||
|
||||
public required string PostName { get; set; }
|
||||
|
||||
public required string PostType { get; set; }
|
||||
|
||||
public double Salary { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
namespace SquirrelContract.ViewModels;
|
||||
|
||||
public class SalaryViewModel
|
||||
{
|
||||
public required string EmployeeId { get; set; }
|
||||
public required string EmployeeFIO { get; set; }
|
||||
public DateTime SalaryDate { get; set; }
|
||||
public double Salary { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
namespace SquirrelContract.ViewModels;
|
||||
|
||||
public class SaleCocktailViewModel
|
||||
{
|
||||
public required string CocktailId { get; set; }
|
||||
|
||||
public required string CocktailName { get; set; }
|
||||
|
||||
public int Count { get; set; }
|
||||
|
||||
public double Price { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
namespace SquirrelContract.ViewModels;
|
||||
|
||||
public class SaleViewModel
|
||||
{
|
||||
public required string Id { get; set; }
|
||||
|
||||
public required string EmployeeId { get; set; }
|
||||
|
||||
public required string EmployeeFIO { get; set; }
|
||||
|
||||
public string? ClientId { get; set; }
|
||||
|
||||
public string? ClientFIO { get; set; }
|
||||
|
||||
public DateTime SaleDate { get; set; }
|
||||
|
||||
public double Sum { get; set; }
|
||||
|
||||
public required string DiscountType { get; set; }
|
||||
|
||||
public double Discount { get; set; }
|
||||
|
||||
public bool IsCancel { get; set; }
|
||||
|
||||
public required List<SaleCocktailViewModel> Cocktails { get; set; }
|
||||
}
|
||||
@@ -42,7 +42,7 @@ public class CocktailStorageContract : ICocktailStorageContract
|
||||
{
|
||||
try
|
||||
{
|
||||
return [.. _dbContext.CocktailHistories.Where(x => x.CocktailId == cocktailId).OrderByDescending(x => x.ChangeDate).Select(x => _mapper.Map<CocktailHistoryDataModel>(x))];
|
||||
return [.. _dbContext.CocktailHistories.Include(x => x.Cocktail).Where(x => x.CocktailId == cocktailId).OrderByDescending(x => x.ChangeDate).Select(x => _mapper.Map<CocktailHistoryDataModel>(x))];
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -105,20 +105,35 @@ public class CocktailStorageContract : ICocktailStorageContract
|
||||
{
|
||||
try
|
||||
{
|
||||
var element = GetCocktailById(cocktailDataModel.Id) ?? throw new ElementNotFoundException(cocktailDataModel.Id);
|
||||
_dbContext.Cocktails.Update(_mapper.Map(cocktailDataModel, element));
|
||||
_dbContext.SaveChanges();
|
||||
}
|
||||
catch (ElementNotFoundException)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw;
|
||||
var transaction = _dbContext.Database.BeginTransaction();
|
||||
try
|
||||
{
|
||||
var element = GetCocktailById(cocktailDataModel.Id) ?? throw new ElementNotFoundException(cocktailDataModel.Id);
|
||||
if (element.Price != cocktailDataModel.Price)
|
||||
{
|
||||
_dbContext.CocktailHistories.Add(new CocktailHistory() { CocktailId = element.Id, OldPrice = element.Price });
|
||||
_dbContext.SaveChanges();
|
||||
}
|
||||
_dbContext.Cocktails.Update(_mapper.Map(cocktailDataModel, element));
|
||||
_dbContext.SaveChanges();
|
||||
transaction.Commit();
|
||||
}
|
||||
catch
|
||||
{
|
||||
transaction.Rollback();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Cocktails_CocktailName" })
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new ElementExistsException("CocktailName", cocktailDataModel.CocktailName);
|
||||
}
|
||||
catch (Exception ex) when (ex is ElementDeletedException || ex is ElementNotFoundException)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
|
||||
@@ -16,7 +16,10 @@ public class EmployeeStorageContract : IEmployeeStorageContract
|
||||
_dbContext = dbContext;
|
||||
var config = new MapperConfiguration(cfg =>
|
||||
{
|
||||
cfg.AddMaps(typeof(SquirrelDbContext).Assembly);
|
||||
cfg.CreateMap<Post, PostDataModel>()
|
||||
.ForMember(x => x.Id, x => x.MapFrom(src => src.PostId));
|
||||
cfg.CreateMap<Employee, EmployeeDataModel>();
|
||||
cfg.CreateMap<EmployeeDataModel, Employee>();
|
||||
});
|
||||
_mapper = new Mapper(config);
|
||||
}
|
||||
@@ -36,13 +39,13 @@ public class EmployeeStorageContract : IEmployeeStorageContract
|
||||
}
|
||||
if (fromBirthDate is not null && toBirthDate is not null)
|
||||
{
|
||||
query = query.Where(x => x.BirthDate >= fromBirthDate && x.BirthDate <= toBirthDate);
|
||||
query = query.Where(x => x.BirthDate >= DateTime.SpecifyKind(fromBirthDate ?? DateTime.UtcNow, DateTimeKind.Utc) && x.BirthDate <= DateTime.SpecifyKind(toBirthDate ?? DateTime.UtcNow, DateTimeKind.Utc));
|
||||
}
|
||||
if (fromEmploymentDate is not null && toEmploymentDate is not null)
|
||||
{
|
||||
query = query.Where(x => x.EmploymentDate >= fromEmploymentDate && x.EmploymentDate <= toEmploymentDate);
|
||||
query = query.Where(x => x.EmploymentDate >= DateTime.SpecifyKind(fromEmploymentDate ?? DateTime.UtcNow, DateTimeKind.Utc) && x.EmploymentDate <= DateTime.SpecifyKind(toEmploymentDate ?? DateTime.UtcNow, DateTimeKind.Utc));
|
||||
}
|
||||
return [.. query.Select(x => _mapper.Map<EmployeeDataModel>(x))];
|
||||
return [.. JoinPost(query).Select(x => _mapper.Map<EmployeeDataModel>(x))];
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -68,7 +71,7 @@ public class EmployeeStorageContract : IEmployeeStorageContract
|
||||
{
|
||||
try
|
||||
{
|
||||
return _mapper.Map<EmployeeDataModel>(_dbContext.Employees.FirstOrDefault(x => x.FIO == fio));
|
||||
return _mapper.Map<EmployeeDataModel>(AddPost(_dbContext.Employees.FirstOrDefault(x => x.FIO == fio && !x.IsDeleted)));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -81,7 +84,7 @@ public class EmployeeStorageContract : IEmployeeStorageContract
|
||||
{
|
||||
try
|
||||
{
|
||||
return _mapper.Map<EmployeeDataModel>(_dbContext.Employees.FirstOrDefault(x => x.Email == email));
|
||||
return _mapper.Map<EmployeeDataModel>(AddPost(_dbContext.Employees.FirstOrDefault(x => x.Email == email && !x.IsDeleted)));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -149,5 +152,12 @@ public class EmployeeStorageContract : IEmployeeStorageContract
|
||||
}
|
||||
}
|
||||
|
||||
private Employee? GetEmployeeById(string id) => _dbContext.Employees.FirstOrDefault(x => x.Id == id && !x.IsDeleted);
|
||||
private Employee? GetEmployeeById(string id) => AddPost(_dbContext.Employees.FirstOrDefault(x => x.Id == id && !x.IsDeleted));
|
||||
|
||||
private IQueryable<Employee> JoinPost(IQueryable<Employee> query)
|
||||
=> query.GroupJoin(_dbContext.Posts.Where(x => x.IsActual), x => x.PostId, y => y.PostId, (x, y) => new { Employee = x, Post = y })
|
||||
.SelectMany(xy => xy.Post.DefaultIfEmpty(), (x, y) => x.Employee.AddPost(y));
|
||||
|
||||
private Employee? AddPost(Employee? employee)
|
||||
=> employee?.AddPost(_dbContext.Posts.FirstOrDefault(x => x.PostId == employee.PostId && x.IsActual));
|
||||
}
|
||||
|
||||
@@ -29,16 +29,11 @@ public class PostStorageContract : IPostStorageContract
|
||||
_mapper = new Mapper(config);
|
||||
}
|
||||
|
||||
public List<PostDataModel> GetList(bool onlyActual = true)
|
||||
public List<PostDataModel> GetList()
|
||||
{
|
||||
try
|
||||
{
|
||||
var query = _dbContext.Posts.AsQueryable();
|
||||
if (onlyActual)
|
||||
{
|
||||
query = query.Where(x => x.IsActual);
|
||||
}
|
||||
return [.. query.Select(x => _mapper.Map<PostDataModel>(x))];
|
||||
return [.. _dbContext.Posts.Select(x => _mapper.Map<PostDataModel>(x))];
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
using AutoMapper;
|
||||
using BarBelochkaContract.DataModels;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using SquirrelContract.DataModels;
|
||||
using SquirrelContract.Exceptions;
|
||||
using SquirrelContract.StoragesContracts;
|
||||
using SquirrelDatabase.Models;
|
||||
@@ -16,6 +18,7 @@ public class SalaryStorageContract : ISalaryStorageContract
|
||||
_dbContext = dbContext;
|
||||
var config = new MapperConfiguration(cfg =>
|
||||
{
|
||||
cfg.CreateMap<Employee, EmployeeDataModel>();
|
||||
cfg.CreateMap<Salary, SalaryDataModel>();
|
||||
cfg.CreateMap<SalaryDataModel, Salary>()
|
||||
.ForMember(dest => dest.EmployeeSalary, opt => opt.MapFrom(src => src.Salary));
|
||||
@@ -23,15 +26,17 @@ public class SalaryStorageContract : ISalaryStorageContract
|
||||
_mapper = new Mapper(config);
|
||||
}
|
||||
|
||||
public List<SalaryDataModel> GetList(DateTime startDate, DateTime endDate, string? employeeId = null)
|
||||
public List<SalaryDataModel> GetList(DateTime? startDate, DateTime? endDate, string? employeeId = null)
|
||||
{
|
||||
try
|
||||
{
|
||||
var query = _dbContext.Salaries.Where(x => x.SalaryDate >= startDate && x.SalaryDate <= endDate);
|
||||
if (employeeId is not null)
|
||||
{
|
||||
var query = _dbContext.Salaries.Include(d => d.Employee).AsQueryable();
|
||||
if (startDate.HasValue)
|
||||
query = query.Where(x => x.SalaryDate >= DateTime.SpecifyKind(startDate ?? DateTime.UtcNow, DateTimeKind.Utc));
|
||||
if (endDate.HasValue)
|
||||
query = query.Where(x => x.SalaryDate <= DateTime.SpecifyKind(endDate ?? DateTime.UtcNow, DateTimeKind.Utc));
|
||||
if (employeeId != null)
|
||||
query = query.Where(x => x.EmployeeId == employeeId);
|
||||
}
|
||||
return [.. query.Select(x => _mapper.Map<SalaryDataModel>(x))];
|
||||
}
|
||||
catch (Exception ex)
|
||||
|
||||
@@ -2,11 +2,14 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using SquirrelContract.DataModels;
|
||||
using SquirrelContract.Exceptions;
|
||||
using SquirrelContract.StoragesContracts;
|
||||
using SquirrelDatabase.Models;
|
||||
using System;
|
||||
using static System.Runtime.InteropServices.JavaScript.JSType;
|
||||
|
||||
namespace SquirrelDatabase.Implementations;
|
||||
|
||||
public class SaleStorageContract
|
||||
public class SaleStorageContract : ISaleStorageContract
|
||||
{
|
||||
private readonly SquirrelDbContext _dbContext;
|
||||
private readonly Mapper _mapper;
|
||||
@@ -15,13 +18,19 @@ public class SaleStorageContract
|
||||
{
|
||||
_dbContext = dbContext;
|
||||
var config = new MapperConfiguration(cfg =>
|
||||
{
|
||||
{
|
||||
cfg.CreateMap<Client, ClientDataModel>();
|
||||
cfg.CreateMap<Cocktail, CocktailDataModel>();
|
||||
cfg.CreateMap<Employee, EmployeeDataModel>();
|
||||
cfg.CreateMap<SaleCocktail, SaleCocktailDataModel>();
|
||||
cfg.CreateMap<SaleCocktailDataModel, SaleCocktail>();
|
||||
cfg.CreateMap<SaleCocktailDataModel, SaleCocktail>()
|
||||
.ForMember(x => x.Cocktail, x => x.Ignore());
|
||||
cfg.CreateMap<Sale, SaleDataModel>();
|
||||
cfg.CreateMap<SaleDataModel, Sale>()
|
||||
.ForMember(x => x.IsCancel, x => x.MapFrom(src => false))
|
||||
.ForMember(x => x.SaleCocktails, x => x.MapFrom(src => src.Cocktails));
|
||||
.ForMember(x => x.SaleCocktails, x => x.MapFrom(src => src.Cocktails))
|
||||
.ForMember(x => x.Employee, x => x.Ignore())
|
||||
.ForMember(x => x.Client, x => x.Ignore());
|
||||
});
|
||||
_mapper = new Mapper(config);
|
||||
}
|
||||
@@ -30,23 +39,23 @@ public class SaleStorageContract
|
||||
{
|
||||
try
|
||||
{
|
||||
var query = _dbContext.Sales.Include(x => x.SaleCocktails).AsQueryable();
|
||||
if (startDate is not null && endDate is not null)
|
||||
{
|
||||
query = query.Where(x => x.SaleDate >= startDate && x.SaleDate < endDate);
|
||||
}
|
||||
if (employeeId is not null)
|
||||
{
|
||||
var query = _dbContext.Sales
|
||||
.Include(r => r.Employee)
|
||||
.Include(r => r.Client)
|
||||
.Include(r => r.SaleCocktails)!
|
||||
.ThenInclude(d => d.Cocktail)
|
||||
.AsQueryable();
|
||||
if (startDate.HasValue)
|
||||
query = query.Where(x => x.SaleDate >= DateTime.SpecifyKind(startDate ?? DateTime.UtcNow, DateTimeKind.Utc));
|
||||
if (endDate.HasValue)
|
||||
query = query.Where(x => x.SaleDate <= DateTime.SpecifyKind(endDate ?? DateTime.UtcNow, DateTimeKind.Utc));
|
||||
if (employeeId != null)
|
||||
query = query.Where(x => x.EmployeeId == employeeId);
|
||||
}
|
||||
if (clientId is not null)
|
||||
{
|
||||
if (clientId != null)
|
||||
query = query.Where(x => x.ClientId == clientId);
|
||||
}
|
||||
if (cocktailId is not null)
|
||||
{
|
||||
if (cocktailId != null)
|
||||
query = query.Where(x => x.SaleCocktails!.Any(y => y.CocktailId == cocktailId));
|
||||
}
|
||||
var s = query.ToList();
|
||||
return [.. query.Select(x => _mapper.Map<SaleDataModel>(x))];
|
||||
}
|
||||
catch (Exception ex)
|
||||
@@ -107,5 +116,5 @@ public class SaleStorageContract
|
||||
}
|
||||
}
|
||||
|
||||
private Sale? GetSaleById(string id) => _dbContext.Sales.FirstOrDefault(x => x.Id == id);
|
||||
private Sale? GetSaleById(string id) => _dbContext.Sales.Include(x => x.Client).Include(x => x.Employee).Include(x => x.SaleCocktails)!.ThenInclude(x => x.Cocktail).FirstOrDefault(x => x.Id == id);
|
||||
}
|
||||
|
||||
@@ -13,7 +13,7 @@ public class Employee
|
||||
|
||||
public string Email { get; set; }
|
||||
|
||||
public string PostId { get; set; }
|
||||
public required string PostId { get; set; }
|
||||
|
||||
public DateTime BirthDate { get; set; }
|
||||
|
||||
@@ -21,9 +21,18 @@ public class Employee
|
||||
|
||||
public bool IsDeleted { get; set; }
|
||||
|
||||
[NotMapped]
|
||||
public Post? Post { get; set; }
|
||||
|
||||
[ForeignKey("EmployeeId")]
|
||||
public List<Salary>? Salaries { get; set; }
|
||||
|
||||
[ForeignKey("EmployeeId")]
|
||||
public List<Sale>? Sales { get; set; }
|
||||
|
||||
public Employee AddPost(Post? post)
|
||||
{
|
||||
Post = post;
|
||||
return this;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,4 +7,10 @@ public class SaleCocktail
|
||||
public required string CocktailId { get; set; }
|
||||
|
||||
public int Count { get; set; }
|
||||
|
||||
public double Price { get; set; }
|
||||
|
||||
public Sale? Sale { get; set; }
|
||||
|
||||
public Cocktail? Cocktail { get; set; }
|
||||
}
|
||||
|
||||
@@ -20,6 +20,11 @@ public class SquirrelDbContext(IConfigurationDatabase configurationDatabase) : D
|
||||
|
||||
modelBuilder.Entity<Client>().HasIndex(x => x.PhoneNumber).IsUnique();
|
||||
|
||||
modelBuilder.Entity<Sale>()
|
||||
.HasOne(e => e.Client)
|
||||
.WithMany(e => e.Sales)
|
||||
.OnDelete(DeleteBehavior.SetNull);
|
||||
|
||||
modelBuilder.Entity<Cocktail>().HasIndex(x => x.CocktailName).IsUnique();
|
||||
|
||||
modelBuilder.Entity<Post>()
|
||||
|
||||
@@ -33,61 +33,53 @@ internal class PostBusinessLogicContractTests
|
||||
//Arrange
|
||||
var listOriginal = new List<PostDataModel>()
|
||||
{
|
||||
new(Guid.NewGuid().ToString(),"name 1", PostType.Manager, 10, true, DateTime.UtcNow),
|
||||
new(Guid.NewGuid().ToString(), "name 2", PostType.Manager, 10, false, DateTime.UtcNow),
|
||||
new(Guid.NewGuid().ToString(), "name 3", PostType.Manager, 10, true, DateTime.UtcNow),
|
||||
new(Guid.NewGuid().ToString(),"name 1", PostType.Manager, 10),
|
||||
new(Guid.NewGuid().ToString(), "name 2", PostType.Manager, 10),
|
||||
new(Guid.NewGuid().ToString(), "name 3", PostType.Manager, 10),
|
||||
};
|
||||
_postStorageContract.Setup(x => x.GetList(It.IsAny<bool>())).Returns(listOriginal);
|
||||
_postStorageContract.Setup(x => x.GetList()).Returns(listOriginal);
|
||||
//Act
|
||||
var listOnlyActive = _postBusinessLogicContract.GetAllPosts(true);
|
||||
var listAll = _postBusinessLogicContract.GetAllPosts(false);
|
||||
var list = _postBusinessLogicContract.GetAllPosts();
|
||||
//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));
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Is.EquivalentTo(listOriginal));
|
||||
});
|
||||
_postStorageContract.Verify(x => x.GetList(true), Times.Once);
|
||||
_postStorageContract.Verify(x => x.GetList(false), Times.Once);
|
||||
_postStorageContract.Verify(x => x.GetList(), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetAllPosts_ReturnEmptyList_Test()
|
||||
{
|
||||
//Arrange
|
||||
_postStorageContract.Setup(x => x.GetList(It.IsAny<bool>())).Returns([]);
|
||||
_postStorageContract.Setup(x => x.GetList()).Returns([]);
|
||||
//Act
|
||||
var listOnlyActive = _postBusinessLogicContract.GetAllPosts(true);
|
||||
var listAll = _postBusinessLogicContract.GetAllPosts(false);
|
||||
var list = _postBusinessLogicContract.GetAllPosts();
|
||||
//Assert
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(listOnlyActive, Is.Not.Null);
|
||||
Assert.That(listAll, Is.Not.Null);
|
||||
Assert.That(listOnlyActive, Has.Count.EqualTo(0));
|
||||
Assert.That(listAll, Has.Count.EqualTo(0));
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(0));
|
||||
});
|
||||
_postStorageContract.Verify(x => x.GetList(It.IsAny<bool>()), Times.Exactly(2));
|
||||
}
|
||||
|
||||
[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);
|
||||
Assert.That(() => _postBusinessLogicContract.GetAllPosts(), Throws.TypeOf<NullListException>());
|
||||
_postStorageContract.Verify(x => x.GetList(), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetAllPosts_StorageThrowError_ThrowException_Test()
|
||||
{
|
||||
//Arrange
|
||||
_postStorageContract.Setup(x => x.GetList(It.IsAny<bool>())).Throws(new StorageException(new InvalidOperationException()));
|
||||
_postStorageContract.Setup(x => x.GetList()).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);
|
||||
Assert.That(() => _postBusinessLogicContract.GetAllPosts(), Throws.TypeOf<StorageException>());
|
||||
_postStorageContract.Verify(x => x.GetList(), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
@@ -97,8 +89,8 @@ internal class PostBusinessLogicContractTests
|
||||
var postId = Guid.NewGuid().ToString();
|
||||
var listOriginal = new List<PostDataModel>()
|
||||
{
|
||||
new(postId, "name 1", PostType.Manager, 10, true, DateTime.UtcNow),
|
||||
new(postId, "name 2", PostType.Manager, 10, false, DateTime.UtcNow)
|
||||
new(postId, "name 1", PostType.Manager, 10),
|
||||
new(postId, "name 2", PostType.Manager, 10)
|
||||
};
|
||||
_postStorageContract.Setup(x => x.GetPostWithHistory(It.IsAny<string>())).Returns(listOriginal);
|
||||
//Act
|
||||
@@ -162,7 +154,7 @@ internal class PostBusinessLogicContractTests
|
||||
{
|
||||
//Arrange
|
||||
var id = Guid.NewGuid().ToString();
|
||||
var record = new PostDataModel(id, "name", PostType.Manager, 10, true, DateTime.UtcNow);
|
||||
var record = new PostDataModel(id, "name", PostType.Manager, 10);
|
||||
_postStorageContract.Setup(x => x.GetElementById(id)).Returns(record);
|
||||
//Act
|
||||
var element = _postBusinessLogicContract.GetPostByData(id);
|
||||
@@ -177,7 +169,7 @@ internal class PostBusinessLogicContractTests
|
||||
{
|
||||
//Arrange
|
||||
var postName = "name";
|
||||
var record = new PostDataModel(Guid.NewGuid().ToString(), postName, PostType.Manager, 10, true, DateTime.UtcNow);
|
||||
var record = new PostDataModel(Guid.NewGuid().ToString(), postName, PostType.Manager, 10);
|
||||
_postStorageContract.Setup(x => x.GetElementByName(postName)).Returns(record);
|
||||
//Act
|
||||
var element = _postBusinessLogicContract.GetPostByData(postName);
|
||||
@@ -233,12 +225,11 @@ internal class PostBusinessLogicContractTests
|
||||
{
|
||||
//Arrange
|
||||
var flag = false;
|
||||
var record = new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Bartender, 10, true, DateTime.UtcNow.AddDays(-1));
|
||||
var record = new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Manager, 10);
|
||||
_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 &&
|
||||
x.ChangeDate == record.ChangeDate;
|
||||
flag = x.Id == record.Id && x.PostName == record.PostName && x.PostType == record.PostType && x.Salary == record.Salary;
|
||||
});
|
||||
//Act
|
||||
_postBusinessLogicContract.InsertPost(record);
|
||||
@@ -253,7 +244,7 @@ internal class PostBusinessLogicContractTests
|
||||
//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.Bartender, 10, true, DateTime.UtcNow)), Throws.TypeOf<ElementExistsException>());
|
||||
Assert.That(() => _postBusinessLogicContract.InsertPost(new(Guid.NewGuid().ToString(), "name", PostType.Manager, 10)), Throws.TypeOf<ElementExistsException>());
|
||||
_postStorageContract.Verify(x => x.AddElement(It.IsAny<PostDataModel>()), Times.Once);
|
||||
}
|
||||
|
||||
@@ -269,7 +260,7 @@ internal class PostBusinessLogicContractTests
|
||||
public void InsertPost_InvalidRecord_ThrowException_Test()
|
||||
{
|
||||
//Act&Assert
|
||||
Assert.That(() => _postBusinessLogicContract.InsertPost(new PostDataModel("id", "name", PostType.Bartender, 10, true, DateTime.UtcNow)), Throws.TypeOf<ValidationException>());
|
||||
Assert.That(() => _postBusinessLogicContract.InsertPost(new PostDataModel("id", "name", PostType.Manager, 10)), Throws.TypeOf<ValidationException>());
|
||||
_postStorageContract.Verify(x => x.AddElement(It.IsAny<PostDataModel>()), Times.Never);
|
||||
}
|
||||
|
||||
@@ -279,7 +270,7 @@ internal class PostBusinessLogicContractTests
|
||||
//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.Bartender, 10, true, DateTime.UtcNow)), Throws.TypeOf<StorageException>());
|
||||
Assert.That(() => _postBusinessLogicContract.InsertPost(new(Guid.NewGuid().ToString(), "name", PostType.Manager, 10)), Throws.TypeOf<StorageException>());
|
||||
_postStorageContract.Verify(x => x.AddElement(It.IsAny<PostDataModel>()), Times.Once);
|
||||
}
|
||||
|
||||
@@ -288,12 +279,11 @@ internal class PostBusinessLogicContractTests
|
||||
{
|
||||
//Arrange
|
||||
var flag = false;
|
||||
var record = new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Bartender, 10, true, DateTime.UtcNow.AddDays(-1));
|
||||
var record = new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Manager, 10);
|
||||
_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 &&
|
||||
x.ChangeDate == record.ChangeDate;
|
||||
flag = x.Id == record.Id && x.PostName == record.PostName && x.PostType == record.PostType && x.Salary == record.Salary;
|
||||
});
|
||||
//Act
|
||||
_postBusinessLogicContract.UpdatePost(record);
|
||||
@@ -308,7 +298,7 @@ internal class PostBusinessLogicContractTests
|
||||
//Arrange
|
||||
_postStorageContract.Setup(x => x.UpdElement(It.IsAny<PostDataModel>())).Throws(new ElementNotFoundException(""));
|
||||
//Act&Assert
|
||||
Assert.That(() => _postBusinessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "name", PostType.Bartender, 10, true, DateTime.UtcNow)), Throws.TypeOf<ElementNotFoundException>());
|
||||
Assert.That(() => _postBusinessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "name", PostType.Manager, 10)), Throws.TypeOf<ElementNotFoundException>());
|
||||
_postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Once);
|
||||
}
|
||||
|
||||
@@ -318,7 +308,7 @@ internal class PostBusinessLogicContractTests
|
||||
//Arrange
|
||||
_postStorageContract.Setup(x => x.UpdElement(It.IsAny<PostDataModel>())).Throws(new ElementExistsException("Data", "Data"));
|
||||
//Act&Assert
|
||||
Assert.That(() => _postBusinessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "anme", PostType.Bartender, 10, true, DateTime.UtcNow)), Throws.TypeOf<ElementExistsException>());
|
||||
Assert.That(() => _postBusinessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "anme", PostType.Manager, 10)), Throws.TypeOf<ElementExistsException>());
|
||||
_postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Once);
|
||||
}
|
||||
|
||||
@@ -334,7 +324,7 @@ internal class PostBusinessLogicContractTests
|
||||
public void UpdatePost_InvalidRecord_ThrowException_Test()
|
||||
{
|
||||
//Act&Assert
|
||||
Assert.That(() => _postBusinessLogicContract.UpdatePost(new PostDataModel("id", "name", PostType.Bartender, 10, true, DateTime.UtcNow)), Throws.TypeOf<ValidationException>());
|
||||
Assert.That(() => _postBusinessLogicContract.UpdatePost(new PostDataModel("id", "name", PostType.Manager, 10)), Throws.TypeOf<ValidationException>());
|
||||
_postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Never);
|
||||
}
|
||||
|
||||
@@ -344,7 +334,7 @@ internal class PostBusinessLogicContractTests
|
||||
//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.Bartender, 10, true, DateTime.UtcNow)), Throws.TypeOf<StorageException>());
|
||||
Assert.That(() => _postBusinessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "name", PostType.Manager, 10)), Throws.TypeOf<StorageException>());
|
||||
_postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Once);
|
||||
}
|
||||
|
||||
|
||||
@@ -160,7 +160,7 @@ internal class SalaryBusinessLogicContractTests
|
||||
public void GetAllSalariesByEmployee_EmployeeIdIsNotGuid_ThrowException_Test()
|
||||
{
|
||||
//Act&Assert
|
||||
Assert.That(() => _salaryBusinessLogicContract.GetAllSalariesByPeriodByEmployee(DateTime.UtcNow, DateTime.UtcNow.AddDays(1), "workerId"), Throws.TypeOf<ValidationException>());
|
||||
Assert.That(() => _salaryBusinessLogicContract.GetAllSalariesByPeriodByEmployee(DateTime.UtcNow, DateTime.UtcNow.AddDays(1), "employeeId"), Throws.TypeOf<ValidationException>());
|
||||
_salaryStorageContract.Verify(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>()), Times.Never);
|
||||
}
|
||||
|
||||
@@ -187,12 +187,12 @@ internal class SalaryBusinessLogicContractTests
|
||||
{
|
||||
//Arrange
|
||||
var employeeId = Guid.NewGuid().ToString();
|
||||
var saleSum = 200.0;
|
||||
var saleSum = 1.2 * 5;
|
||||
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(), employeeId, null, saleSum, DiscountType.None, 0, false, [])]);
|
||||
.Returns([new SaleDataModel(Guid.NewGuid().ToString(), employeeId, null, DiscountType.None, false, [new SaleCocktailDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5, 1.2)])]);
|
||||
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
|
||||
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Manager, postSalary, true, DateTime.UtcNow));
|
||||
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Manager, postSalary));
|
||||
_employeeStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
|
||||
.Returns([new EmployeeDataModel(employeeId, "Test", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)]);
|
||||
var sum = 0.0;
|
||||
@@ -209,7 +209,7 @@ internal class SalaryBusinessLogicContractTests
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void CalculateSalaryByMounth_WithSeveralWorkers_Test()
|
||||
public void CalculateSalaryByMounth_WithSeveralEmployees_Test()
|
||||
{
|
||||
//Arrange
|
||||
var employee1Id = Guid.NewGuid().ToString();
|
||||
@@ -221,13 +221,13 @@ internal class SalaryBusinessLogicContractTests
|
||||
new(employee3Id, "Test", "123@gmail.com", 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(), employee1Id, null, 1, DiscountType.None, 0, false, []),
|
||||
new SaleDataModel(Guid.NewGuid().ToString(), employee1Id, null, 1, DiscountType.None, 0, false, []),
|
||||
new SaleDataModel(Guid.NewGuid().ToString(), employee2Id, null, 1, DiscountType.None, 0, false, []),
|
||||
new SaleDataModel(Guid.NewGuid().ToString(), employee3Id, null, 1, DiscountType.None, 0, false, []),
|
||||
new SaleDataModel(Guid.NewGuid().ToString(), employee3Id, null, 1, DiscountType.None, 0, false, [])]);
|
||||
.Returns([new SaleDataModel(Guid.NewGuid().ToString(), employee1Id, null, DiscountType.None, false, []),
|
||||
new SaleDataModel(Guid.NewGuid().ToString(), employee1Id, null, DiscountType.None, false, []),
|
||||
new SaleDataModel(Guid.NewGuid().ToString(), employee2Id, null, DiscountType.None, false, []),
|
||||
new SaleDataModel(Guid.NewGuid().ToString(), employee3Id, null, DiscountType.None, false, []),
|
||||
new SaleDataModel(Guid.NewGuid().ToString(), employee3Id, null, DiscountType.None, false, [])]);
|
||||
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
|
||||
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Manager, 2000, true, DateTime.UtcNow));
|
||||
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Manager, 2000));
|
||||
_employeeStorageContract.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
|
||||
@@ -237,7 +237,7 @@ internal class SalaryBusinessLogicContractTests
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void CalculateSalaryByMounth_WithoutSalesByWorker_Test()
|
||||
public void CalculateSalaryByMounth_WithoutSalesByEmployee_Test()
|
||||
{
|
||||
//Arrange
|
||||
var postSalary = 2000.0;
|
||||
@@ -245,7 +245,7 @@ internal class SalaryBusinessLogicContractTests
|
||||
_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.Manager, postSalary, true, DateTime.UtcNow));
|
||||
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Manager, postSalary));
|
||||
_employeeStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
|
||||
.Returns([new EmployeeDataModel(employeeId, "Test", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)]);
|
||||
var sum = 0.0;
|
||||
@@ -267,7 +267,7 @@ internal class SalaryBusinessLogicContractTests
|
||||
//Arrange
|
||||
var employeeId = Guid.NewGuid().ToString();
|
||||
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
|
||||
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Manager, 2000, true, DateTime.UtcNow));
|
||||
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Manager, 2000));
|
||||
_employeeStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
|
||||
.Returns([new EmployeeDataModel(employeeId, "Test", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)]);
|
||||
//Act&Assert
|
||||
@@ -280,22 +280,22 @@ internal class SalaryBusinessLogicContractTests
|
||||
//Arrange
|
||||
var employeeId = 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(), employeeId, null, 200, DiscountType.None, 0, false, [])]);
|
||||
.Returns([new SaleDataModel(Guid.NewGuid().ToString(), employeeId, null, DiscountType.None, false, [])]);
|
||||
_employeeStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
|
||||
.Returns([new EmployeeDataModel(employeeId, "Test", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)]);
|
||||
.Returns([new EmployeeDataModel(employeeId, "Test", "abc@gmail.com", 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()
|
||||
public void CalculateSalaryByMounth_EmployeeStorageReturnNull_ThrowException_Test()
|
||||
{
|
||||
//Arrange
|
||||
var employeeId = 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(), employeeId, null, 200, DiscountType.None, 0, false, [])]);
|
||||
.Returns([new SaleDataModel(Guid.NewGuid().ToString(), employeeId, null, DiscountType.None, false, [])]);
|
||||
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
|
||||
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Manager, 2000, true, DateTime.UtcNow));
|
||||
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Manager, 2000));
|
||||
//Act&Assert
|
||||
Assert.That(() => _salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow), Throws.TypeOf<NullListException>());
|
||||
}
|
||||
@@ -308,7 +308,7 @@ internal class SalaryBusinessLogicContractTests
|
||||
_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.Manager, 2000, true, DateTime.UtcNow));
|
||||
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Manager, 2000));
|
||||
_employeeStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
|
||||
.Returns([new EmployeeDataModel(employeeId, "Test", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)]);
|
||||
//Act&Assert
|
||||
@@ -321,7 +321,7 @@ internal class SalaryBusinessLogicContractTests
|
||||
//Arrange
|
||||
var employeeId = 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(), employeeId, null, 200, DiscountType.None, 0, false, [])]);
|
||||
.Returns([new SaleDataModel(Guid.NewGuid().ToString(), employeeId, null, DiscountType.None, false, [])]);
|
||||
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
|
||||
.Throws(new StorageException(new InvalidOperationException()));
|
||||
_employeeStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
|
||||
@@ -331,14 +331,14 @@ internal class SalaryBusinessLogicContractTests
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void CalculateSalaryByMounth_WorkerStorageThrowException_ThrowException_Test()
|
||||
public void CalculateSalaryByMounth_EmployeeStorageThrowException_ThrowException_Test()
|
||||
{
|
||||
//Arrange
|
||||
var employeeId = 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(), employeeId, null, 200, DiscountType.None, 0, false, [])]);
|
||||
.Returns([new SaleDataModel(Guid.NewGuid().ToString(), employeeId, null, DiscountType.None, false, [])]);
|
||||
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
|
||||
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Manager, 2000, true, DateTime.UtcNow));
|
||||
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Manager, 2000));
|
||||
_employeeStorageContract.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
|
||||
|
||||
@@ -34,10 +34,10 @@ internal class SaleBusinessLogicContractTests
|
||||
var date = DateTime.UtcNow;
|
||||
var listOriginal = new List<SaleDataModel>()
|
||||
{
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, DiscountType.None, 0, false,
|
||||
[new SaleCocktailDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]),
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, DiscountType.None, 0, false, []),
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, DiscountType.None, 0, false, []),
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, DiscountType.None, false,
|
||||
[new SaleCocktailDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5, 1.2)]),
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, DiscountType.None, false, []),
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, DiscountType.None, false, []),
|
||||
};
|
||||
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Returns(listOriginal);
|
||||
//Act
|
||||
@@ -98,10 +98,10 @@ internal class SaleBusinessLogicContractTests
|
||||
var employeeId = Guid.NewGuid().ToString();
|
||||
var listOriginal = new List<SaleDataModel>()
|
||||
{
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, DiscountType.None, 0, false,
|
||||
[new SaleCocktailDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]),
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, DiscountType.None, 0, false, []),
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, DiscountType.None, 0, false, []),
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, DiscountType.None, false,
|
||||
[new SaleCocktailDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5, 1.2)]),
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, DiscountType.None, false, []),
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, DiscountType.None, false, []),
|
||||
};
|
||||
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Returns(listOriginal);
|
||||
//Act
|
||||
@@ -179,10 +179,10 @@ internal class SaleBusinessLogicContractTests
|
||||
var clientId = Guid.NewGuid().ToString();
|
||||
var listOriginal = new List<SaleDataModel>()
|
||||
{
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, DiscountType.None, 0, false,
|
||||
[new SaleCocktailDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]),
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, DiscountType.None, 0, false, []),
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, DiscountType.None, 0, false, []),
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, DiscountType.None, false,
|
||||
[new SaleCocktailDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5, 1.2)]),
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, DiscountType.None, false, []),
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, DiscountType.None, false, []),
|
||||
};
|
||||
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Returns(listOriginal);
|
||||
//Act
|
||||
@@ -260,10 +260,10 @@ internal class SaleBusinessLogicContractTests
|
||||
var cocktailId = Guid.NewGuid().ToString();
|
||||
var listOriginal = new List<SaleDataModel>()
|
||||
{
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, DiscountType.None, 0, false,
|
||||
[new SaleCocktailDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]),
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, DiscountType.None, 0, false, []),
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, DiscountType.None, 0, false, []),
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, DiscountType.None, false,
|
||||
[new SaleCocktailDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5, 1.2)]),
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, DiscountType.None, false, []),
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, DiscountType.None, false, []),
|
||||
};
|
||||
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Returns(listOriginal);
|
||||
//Act
|
||||
@@ -338,8 +338,8 @@ internal class SaleBusinessLogicContractTests
|
||||
{
|
||||
//Arrange
|
||||
var id = Guid.NewGuid().ToString();
|
||||
var record = new SaleDataModel(id, Guid.NewGuid().ToString(), null, 10, DiscountType.None, 0, false,
|
||||
[new SaleCocktailDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]);
|
||||
var record = new SaleDataModel(id, Guid.NewGuid().ToString(), null, DiscountType.None, false,
|
||||
[new SaleCocktailDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5, 1.2)]);
|
||||
_saleStorageContract.Setup(x => x.GetElementById(id)).Returns(record);
|
||||
//Act
|
||||
var element = _saleBusinessLogicContract.GetSaleByData(id);
|
||||
@@ -389,8 +389,8 @@ internal class SaleBusinessLogicContractTests
|
||||
{
|
||||
//Arrange
|
||||
var flag = false;
|
||||
var record = new SaleDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 10, DiscountType.None, 10,
|
||||
false, [new SaleCocktailDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]);
|
||||
var record = new SaleDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), DiscountType.None,
|
||||
false, [new SaleCocktailDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5, 1.2)]);
|
||||
_saleStorageContract.Setup(x => x.AddElement(It.IsAny<SaleDataModel>()))
|
||||
.Callback((SaleDataModel x) =>
|
||||
{
|
||||
@@ -415,7 +415,7 @@ internal class SaleBusinessLogicContractTests
|
||||
_saleStorageContract.Setup(x => x.AddElement(It.IsAny<SaleDataModel>())).Throws(new ElementExistsException("Data", "Data"));
|
||||
//Act&Assert
|
||||
Assert.That(() => _saleBusinessLogicContract.InsertSale(new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(),
|
||||
Guid.NewGuid().ToString(), 10, DiscountType.None, 10, false, [new SaleCocktailDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<ElementExistsException>());
|
||||
Guid.NewGuid().ToString(), DiscountType.None, false, [new SaleCocktailDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5, 1.2)])), Throws.TypeOf<ElementExistsException>());
|
||||
_saleStorageContract.Verify(x => x.AddElement(It.IsAny<SaleDataModel>()), Times.Once);
|
||||
}
|
||||
|
||||
@@ -431,7 +431,7 @@ internal class SaleBusinessLogicContractTests
|
||||
public void InsertSale_InvalidRecord_ThrowException_Test()
|
||||
{
|
||||
//Act&Assert
|
||||
Assert.That(() => _saleBusinessLogicContract.InsertSale(new SaleDataModel("id", Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 10, DiscountType.None, 10, false, [])), Throws.TypeOf<ValidationException>());
|
||||
Assert.That(() => _saleBusinessLogicContract.InsertSale(new SaleDataModel("id", Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), DiscountType.None, false, [])), Throws.TypeOf<ValidationException>());
|
||||
_saleStorageContract.Verify(x => x.AddElement(It.IsAny<SaleDataModel>()), Times.Never);
|
||||
}
|
||||
|
||||
@@ -442,7 +442,7 @@ internal class SaleBusinessLogicContractTests
|
||||
_saleStorageContract.Setup(x => x.AddElement(It.IsAny<SaleDataModel>())).Throws(new StorageException(new InvalidOperationException()));
|
||||
//Act&Assert
|
||||
Assert.That(() => _saleBusinessLogicContract.InsertSale(new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(),
|
||||
Guid.NewGuid().ToString(), 10, DiscountType.None, 10, false, [new SaleCocktailDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<StorageException>());
|
||||
Guid.NewGuid().ToString(), DiscountType.None, false, [new SaleCocktailDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5, 1.2)])), Throws.TypeOf<StorageException>());
|
||||
_saleStorageContract.Verify(x => x.AddElement(It.IsAny<SaleDataModel>()), Times.Once);
|
||||
}
|
||||
|
||||
|
||||
@@ -10,41 +10,41 @@ internal class PostDataModelTests
|
||||
[Test]
|
||||
public void IdIsNullOrEmptyTest()
|
||||
{
|
||||
var post = CreateDataModel(null, "name", PostType.Manager, 10, true, DateTime.UtcNow);
|
||||
var post = CreateDataModel(null, "name", PostType.Manager, 10);
|
||||
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
|
||||
post = CreateDataModel(string.Empty, "name", PostType.Manager, 10, true, DateTime.UtcNow);
|
||||
post = CreateDataModel(string.Empty, "name", PostType.Manager, 10);
|
||||
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void IdIsNotGuidTest()
|
||||
{
|
||||
var post = CreateDataModel("id", "name", PostType.Manager, 10, true, DateTime.UtcNow);
|
||||
var post = CreateDataModel("id", "name", PostType.Manager, 10);
|
||||
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void PostNameIsEmptyTest()
|
||||
{
|
||||
var manufacturer = CreateDataModel(Guid.NewGuid().ToString(), null, PostType.Manager, 10, true, DateTime.UtcNow);
|
||||
var manufacturer = CreateDataModel(Guid.NewGuid().ToString(), null, PostType.Manager, 10);
|
||||
Assert.That(() => manufacturer.Validate(), Throws.TypeOf<ValidationException>());
|
||||
manufacturer = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, PostType.Manager, 10, true, DateTime.UtcNow);
|
||||
manufacturer = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, PostType.Manager, 10);
|
||||
Assert.That(() => manufacturer.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void PostTypeIsNoneTest()
|
||||
{
|
||||
var post = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.None, 10, true, DateTime.UtcNow);
|
||||
var post = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.None, 10);
|
||||
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void SalaryIsLessOrZeroTest()
|
||||
{
|
||||
var post = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.Manager, 0, true, DateTime.UtcNow);
|
||||
var post = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.Manager, 0);
|
||||
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
|
||||
post = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.Manager, -10, true, DateTime.UtcNow);
|
||||
post = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.Manager, -10);
|
||||
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
@@ -55,9 +55,7 @@ internal class PostDataModelTests
|
||||
var postName = "name";
|
||||
var postType = PostType.Manager;
|
||||
var salary = 10;
|
||||
var isActual = false;
|
||||
var changeDate = DateTime.UtcNow.AddDays(-1);
|
||||
var post = CreateDataModel(postId, postName, postType, salary, isActual, changeDate);
|
||||
var post = CreateDataModel(postId, postName, postType, salary);
|
||||
Assert.That(() => post.Validate(), Throws.Nothing);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
@@ -65,11 +63,9 @@ internal class PostDataModelTests
|
||||
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? postName, PostType postType, double salary, bool isActual, DateTime changeDate) =>
|
||||
new(id, postName, postType, salary, isActual, changeDate);
|
||||
private static PostDataModel CreateDataModel(string? id, string? postName, PostType postType, double salary) =>
|
||||
new(id, postName, postType, salary);
|
||||
}
|
||||
|
||||
@@ -9,41 +9,50 @@ internal class SaleCocktailDataModelTests
|
||||
[Test]
|
||||
public void SaleIdIsNullOrEmptyTest()
|
||||
{
|
||||
var saleCocktail = CreateDataModel(null, Guid.NewGuid().ToString(), 10);
|
||||
var saleCocktail = CreateDataModel(null, Guid.NewGuid().ToString(), 10, 1.1);
|
||||
Assert.That(() => saleCocktail.Validate(), Throws.TypeOf<ValidationException>());
|
||||
saleCocktail = CreateDataModel(string.Empty, Guid.NewGuid().ToString(), 10);
|
||||
saleCocktail = CreateDataModel(string.Empty, Guid.NewGuid().ToString(), 10, 1.1);
|
||||
Assert.That(() => saleCocktail.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void SaleIdIsNotGuidTest()
|
||||
{
|
||||
var saleProduct = CreateDataModel("saleId", Guid.NewGuid().ToString(), 10);
|
||||
Assert.That(() => saleProduct.Validate(), Throws.TypeOf<ValidationException>());
|
||||
var saleCocktail = CreateDataModel("saleId", Guid.NewGuid().ToString(), 10, 1.1);
|
||||
Assert.That(() => saleCocktail.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void CocktailIdIsNullOrEmptyTest()
|
||||
{
|
||||
var saleCocktail = CreateDataModel(Guid.NewGuid().ToString(), null, 10);
|
||||
var saleCocktail = CreateDataModel(Guid.NewGuid().ToString(), null, 10, 1.1);
|
||||
Assert.That(() => saleCocktail.Validate(), Throws.TypeOf<ValidationException>());
|
||||
saleCocktail = CreateDataModel(string.Empty, Guid.NewGuid().ToString(), 10);
|
||||
saleCocktail = CreateDataModel(string.Empty, Guid.NewGuid().ToString(), 10, 1.1);
|
||||
Assert.That(() => saleCocktail.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ProductIdIsNotGuidTest()
|
||||
public void CocktailIdIsNotGuidTest()
|
||||
{
|
||||
var saleCocktail = CreateDataModel(Guid.NewGuid().ToString(), "productId", 10);
|
||||
var saleCocktail = CreateDataModel(Guid.NewGuid().ToString(), "cocktailId", 10, 1.1);
|
||||
Assert.That(() => saleCocktail.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void CountIsLessOrZeroTest()
|
||||
{
|
||||
var saleCocktail = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 0);
|
||||
var saleCocktail = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 0, 1.1);
|
||||
Assert.That(() => saleCocktail.Validate(), Throws.TypeOf<ValidationException>());
|
||||
saleCocktail = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), -10);
|
||||
saleCocktail = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), -10, 1.1);
|
||||
Assert.That(() => saleCocktail.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void PriceIsLessOrZeroTest()
|
||||
{
|
||||
var saleCocktail = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 1, 0);
|
||||
Assert.That(() => saleCocktail.Validate(), Throws.TypeOf<ValidationException>());
|
||||
saleCocktail = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 1, -10);
|
||||
Assert.That(() => saleCocktail.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
@@ -53,16 +62,18 @@ internal class SaleCocktailDataModelTests
|
||||
var saleId = Guid.NewGuid().ToString();
|
||||
var cocktailId = Guid.NewGuid().ToString();
|
||||
var count = 10;
|
||||
var saleCocktail = CreateDataModel(saleId, cocktailId, count);
|
||||
var price = 1.2;
|
||||
var saleCocktail = CreateDataModel(saleId, cocktailId, count, price);
|
||||
Assert.That(() => saleCocktail.Validate(), Throws.Nothing);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(saleCocktail.SaleId, Is.EqualTo(saleId));
|
||||
Assert.That(saleCocktail.CocktailId, Is.EqualTo(cocktailId));
|
||||
Assert.That(saleCocktail.Count, Is.EqualTo(count));
|
||||
Assert.That(saleCocktail.Price, Is.EqualTo(price));
|
||||
});
|
||||
}
|
||||
|
||||
private static SaleCocktailDataModel CreateDataModel(string? saleId, string? cocktailId, int count) =>
|
||||
new(saleId, cocktailId, count);
|
||||
private static SaleCocktailDataModel CreateDataModel(string? saleId, string? cocktailId, int count, double price) =>
|
||||
new(saleId, cocktailId, count, price);
|
||||
}
|
||||
|
||||
@@ -10,88 +10,120 @@ internal class SaleDataModelTests
|
||||
[Test]
|
||||
public void IdIsNullOrEmptyTest()
|
||||
{
|
||||
var sale = CreateDataModel(null, Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 10, DiscountType.OnSale, 10, false, CreateSubDataModel());
|
||||
var sale = CreateDataModel(null, Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), DiscountType.OnSale, false, CreateSubDataModel());
|
||||
Assert.That(() => sale.Validate(), Throws.TypeOf<ValidationException>());
|
||||
sale = CreateDataModel(string.Empty, Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 10, DiscountType.OnSale, 10, false, CreateSubDataModel());
|
||||
sale = CreateDataModel(string.Empty, Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), DiscountType.OnSale, false, CreateSubDataModel());
|
||||
Assert.That(() => sale.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void IdIsNotGuidTest()
|
||||
{
|
||||
var sale = CreateDataModel("id", Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 10, DiscountType.OnSale, 10, false, CreateSubDataModel());
|
||||
var sale = CreateDataModel("id", Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), DiscountType.OnSale, false, CreateSubDataModel());
|
||||
Assert.That(() => sale.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
[Test]
|
||||
public void EmployeeIdIsNullOrEmptyTest()
|
||||
{
|
||||
var sale = CreateDataModel(Guid.NewGuid().ToString(), null, Guid.NewGuid().ToString(), 10, DiscountType.OnSale, 10, false, CreateSubDataModel());
|
||||
var sale = CreateDataModel(Guid.NewGuid().ToString(), null, Guid.NewGuid().ToString(), DiscountType.OnSale, false, CreateSubDataModel());
|
||||
Assert.That(() => sale.Validate(), Throws.TypeOf<ValidationException>());
|
||||
sale = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, Guid.NewGuid().ToString(), 10, DiscountType.OnSale, 10, false, CreateSubDataModel());
|
||||
sale = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, Guid.NewGuid().ToString(), DiscountType.OnSale, false, CreateSubDataModel());
|
||||
Assert.That(() => sale.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void EmployeeIdIsNotGuidTest()
|
||||
{
|
||||
var sale = CreateDataModel(Guid.NewGuid().ToString(), "employeeId", Guid.NewGuid().ToString(), 10, DiscountType.OnSale, 10, false, CreateSubDataModel());
|
||||
var sale = CreateDataModel(Guid.NewGuid().ToString(), "employeeId", Guid.NewGuid().ToString(), DiscountType.OnSale, false, CreateSubDataModel());
|
||||
Assert.That(() => sale.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ClientIdIsNotGuidTest()
|
||||
{
|
||||
var sale = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), "clientId", 10, DiscountType.OnSale, 10, false, CreateSubDataModel());
|
||||
Assert.That(() => sale.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void SumIsLessOrZeroTest()
|
||||
{
|
||||
var sale = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 0, DiscountType.OnSale, 10, false, CreateSubDataModel());
|
||||
Assert.That(() => sale.Validate(), Throws.TypeOf<ValidationException>());
|
||||
sale = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), -10, DiscountType.OnSale, 10, false, CreateSubDataModel());
|
||||
var sale = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), "clientId", DiscountType.OnSale, false, CreateSubDataModel());
|
||||
Assert.That(() => sale.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void CocktailsIsNullOrEmptyTest()
|
||||
{
|
||||
var sale = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 10, DiscountType.OnSale, 10, false, null);
|
||||
var sale = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), DiscountType.OnSale, false, null);
|
||||
Assert.That(() => sale.Validate(), Throws.TypeOf<ValidationException>());
|
||||
sale = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 10, DiscountType.OnSale, 10, false, []);
|
||||
sale = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), DiscountType.OnSale, false, []);
|
||||
Assert.That(() => sale.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void CalcSumAndDiscountTest()
|
||||
{
|
||||
var saleId = Guid.NewGuid().ToString();
|
||||
var employeeId = Guid.NewGuid().ToString();
|
||||
var clientId = Guid.NewGuid().ToString();
|
||||
var cocktails = new List<SaleCocktailDataModel>()
|
||||
{
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 2, 1.1),
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 1, 1.3)
|
||||
};
|
||||
var isCancel = false;
|
||||
var totalSum = cocktails.Sum(x => x.Price * x.Count);
|
||||
var saleNone = CreateDataModel(saleId, employeeId, clientId, DiscountType.None, isCancel, cocktails);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(saleNone.Sum, Is.EqualTo(totalSum));
|
||||
Assert.That(saleNone.Discount, Is.EqualTo(0));
|
||||
});
|
||||
var saleOnSale = CreateDataModel(saleId, employeeId, clientId, DiscountType.OnSale, isCancel, cocktails);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(saleOnSale.Sum, Is.EqualTo(totalSum));
|
||||
Assert.That(saleOnSale.Discount, Is.EqualTo(totalSum * 0.1));
|
||||
});
|
||||
var saleRegularCustomer = CreateDataModel(saleId, employeeId, clientId, DiscountType.RegularCustomer, isCancel, cocktails);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(saleRegularCustomer.Sum, Is.EqualTo(totalSum));
|
||||
Assert.That(saleRegularCustomer.Discount, Is.EqualTo(totalSum * 0.5));
|
||||
});
|
||||
var saleCertificate = CreateDataModel(saleId, employeeId, clientId, DiscountType.Certificate, isCancel, cocktails);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(saleCertificate.Sum, Is.EqualTo(totalSum));
|
||||
Assert.That(saleCertificate.Discount, Is.EqualTo(totalSum * 0.3));
|
||||
});
|
||||
var saleMulty = CreateDataModel(saleId, employeeId, clientId, DiscountType.Certificate | DiscountType.RegularCustomer, isCancel, cocktails);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(saleMulty.Sum, Is.EqualTo(totalSum));
|
||||
Assert.That(saleMulty.Discount, Is.EqualTo(totalSum * 0.8));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AllFieldsIsCorrectTest()
|
||||
{
|
||||
var saleId = Guid.NewGuid().ToString();
|
||||
var employeeId = Guid.NewGuid().ToString();
|
||||
var clientId = Guid.NewGuid().ToString();
|
||||
var sum = 10;
|
||||
var discountType = DiscountType.Certificate;
|
||||
var discount = 1;
|
||||
var isCancel = true;
|
||||
var cocktails = CreateSubDataModel();
|
||||
var sale = CreateDataModel(saleId, employeeId, clientId, sum, discountType, discount, isCancel, cocktails);
|
||||
var sale = CreateDataModel(saleId, employeeId, clientId, discountType, isCancel, cocktails);
|
||||
Assert.That(() => sale.Validate(), Throws.Nothing);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(sale.Id, Is.EqualTo(saleId));
|
||||
Assert.That(sale.EmployeeId, Is.EqualTo(employeeId));
|
||||
Assert.That(sale.ClientId, Is.EqualTo(clientId));
|
||||
Assert.That(sale.Sum, Is.EqualTo(sum));
|
||||
Assert.That(sale.DiscountType, Is.EqualTo(discountType));
|
||||
Assert.That(sale.Discount, Is.EqualTo(discount));
|
||||
Assert.That(sale.IsCancel, Is.EqualTo(isCancel));
|
||||
Assert.That(sale.Cocktails, Is.EquivalentTo(cocktails));
|
||||
});
|
||||
}
|
||||
|
||||
private static SaleDataModel CreateDataModel(string? id, string? employeeId, string? clientId, double sum, DiscountType discountType, double discount, bool isCancel, List<SaleCocktailDataModel>? cocktails) =>
|
||||
new(id, employeeId, clientId, sum, discountType, discount, isCancel, cocktails);
|
||||
private static SaleDataModel CreateDataModel(string? id, string? employeeId, string? clientId, DiscountType discountType, bool isCancel, List<SaleCocktailDataModel>? cocktails) =>
|
||||
new(id, employeeId, clientId, discountType, isCancel, cocktails);
|
||||
|
||||
private static List<SaleCocktailDataModel> CreateSubDataModel()
|
||||
=> [new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 1)];
|
||||
=> [new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 1, 1.1)];
|
||||
}
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.AspNetCore.Mvc.Testing;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using SquirrelContract.Infastructure;
|
||||
|
||||
namespace SquirrelTests.Infrastructure;
|
||||
|
||||
internal class CustomWebApplicationFactory<TProgram> : WebApplicationFactory<TProgram>
|
||||
where TProgram : class
|
||||
{
|
||||
protected override void ConfigureWebHost(IWebHostBuilder builder)
|
||||
{
|
||||
builder.ConfigureServices(services =>
|
||||
{
|
||||
var databaseConfig = services.SingleOrDefault(x => x.ServiceType == typeof(IConfigurationDatabase));
|
||||
if (databaseConfig is not null)
|
||||
services.Remove(databaseConfig);
|
||||
|
||||
var loggerFactory = services.SingleOrDefault(x => x.ServiceType == typeof(LoggerFactory));
|
||||
if (loggerFactory is not null)
|
||||
services.Remove(loggerFactory);
|
||||
|
||||
services.AddSingleton<IConfigurationDatabase, ConfigurationDatabaseTest>();
|
||||
});
|
||||
|
||||
builder.UseEnvironment("Development");
|
||||
|
||||
base.ConfigureWebHost(builder);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
using SquirrelContract.Enums;
|
||||
using SquirrelDatabase;
|
||||
using SquirrelDatabase.Models;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace SquirrelTests.Infrastructure;
|
||||
|
||||
internal static class SquirrelDbContextExtensions
|
||||
{
|
||||
public static Client InsertClientToDatabaseAndReturn(this SquirrelDbContext dbContext, string? id = null, string fio = "test", string phoneNumber = "+7-777-777-77-77", double discountSize = 10)
|
||||
{
|
||||
var client = new Client() { Id = id ?? Guid.NewGuid().ToString(), FIO = fio, PhoneNumber = phoneNumber, DiscountSize = discountSize };
|
||||
dbContext.Clients.Add(client);
|
||||
dbContext.SaveChanges();
|
||||
return client;
|
||||
}
|
||||
|
||||
public static Post InsertPostToDatabaseAndReturn(this SquirrelDbContext dbContext, string? id = null, string postName = "test", PostType postType = PostType.Manager, double salary = 10, bool isActual = true, DateTime? changeDate = null)
|
||||
{
|
||||
var post = new Post() { Id = Guid.NewGuid().ToString(), PostId = id ?? Guid.NewGuid().ToString(), PostName = postName, PostType = postType, Salary = salary, IsActual = isActual, ChangeDate = changeDate ?? DateTime.UtcNow };
|
||||
dbContext.Posts.Add(post);
|
||||
dbContext.SaveChanges();
|
||||
return post;
|
||||
}
|
||||
|
||||
public static Cocktail InsertCocktailToDatabaseAndReturn(this SquirrelDbContext dbContext, string? id = null, string cocktailName = "test", AlcoholType baseAlcohol = AlcoholType.Vodka, double price = 1)
|
||||
{
|
||||
var cocktail = new Cocktail() { Id = id ?? Guid.NewGuid().ToString(), CocktailName = cocktailName, BaseAlcohol = baseAlcohol, Price = price };
|
||||
dbContext.Cocktails.Add(cocktail);
|
||||
dbContext.SaveChanges();
|
||||
return cocktail;
|
||||
}
|
||||
|
||||
public static CocktailHistory InsertCocktailHistoryToDatabaseAndReturn(this SquirrelDbContext dbContext, string cocktailId, double price = 10, DateTime? changeDate = null)
|
||||
{
|
||||
var cocktailHistory = new CocktailHistory() { Id = Guid.NewGuid().ToString(), CocktailId = cocktailId, OldPrice = price, ChangeDate = changeDate ?? DateTime.UtcNow };
|
||||
dbContext.CocktailHistories.Add(cocktailHistory);
|
||||
dbContext.SaveChanges();
|
||||
return cocktailHistory;
|
||||
}
|
||||
|
||||
public static Salary InsertSalaryToDatabaseAndReturn(this SquirrelDbContext dbContext, string employeeId, double employeeSalary = 1, DateTime? salaryDate = null)
|
||||
{
|
||||
var salary = new Salary() { EmployeeId = employeeId, EmployeeSalary = employeeSalary, SalaryDate = salaryDate ?? DateTime.UtcNow };
|
||||
dbContext.Salaries.Add(salary);
|
||||
dbContext.SaveChanges();
|
||||
return salary;
|
||||
}
|
||||
|
||||
public static Sale InsertSaleToDatabaseAndReturn(this SquirrelDbContext dbContext, string employeeId, string? clientId = null, DateTime? saleDate = null, double sum = 1, DiscountType discountType = DiscountType.None, double discount = 0, bool isCancel = false, List<(string, int, double)>? cocktails = null)
|
||||
{
|
||||
var sale = new Sale() { EmployeeId = employeeId, ClientId = clientId, SaleDate = saleDate ?? DateTime.UtcNow, Sum = sum, DiscountType = discountType, Discount = discount, IsCancel = isCancel, SaleCocktails = [] };
|
||||
if (cocktails is not null)
|
||||
{
|
||||
foreach (var elem in cocktails)
|
||||
{
|
||||
sale.SaleCocktails.Add(new SaleCocktail { CocktailId = elem.Item1, SaleId = sale.Id, Count = elem.Item2, Price = elem.Item3 });
|
||||
}
|
||||
}
|
||||
dbContext.Sales.Add(sale);
|
||||
dbContext.SaveChanges();
|
||||
return sale;
|
||||
}
|
||||
|
||||
public static Employee InsertEmployeeToDatabaseAndReturn(this SquirrelDbContext dbContext, string? id = null, string fio = "test", string email = "abc@gmail.com", string? postId = null, DateTime? birthDate = null, DateTime? employmentDate = null, bool isDeleted = false)
|
||||
{
|
||||
var employee = new Employee() { Id = id ?? Guid.NewGuid().ToString(), FIO = fio, Email = email, PostId = postId ?? Guid.NewGuid().ToString(), BirthDate = birthDate ?? DateTime.UtcNow.AddYears(-20), EmploymentDate = employmentDate ?? DateTime.UtcNow, IsDeleted = isDeleted };
|
||||
dbContext.Employees.Add(employee);
|
||||
dbContext.SaveChanges();
|
||||
return employee;
|
||||
}
|
||||
|
||||
public static Client? GetClientFromDatabase(this SquirrelDbContext dbContext, string id) => dbContext.Clients.FirstOrDefault(x => x.Id == id);
|
||||
|
||||
public static Post? GetPostFromDatabaseByPostId(this SquirrelDbContext dbContext, string id) => dbContext.Posts.FirstOrDefault(x => x.PostId == id && x.IsActual);
|
||||
|
||||
public static Post[] GetPostsFromDatabaseByPostId(this SquirrelDbContext dbContext, string id) => [.. dbContext.Posts.Where(x => x.PostId == id).OrderByDescending(x => x.ChangeDate)];
|
||||
|
||||
public static Cocktail? GetCocktailFromDatabaseById(this SquirrelDbContext dbContext, string id) => dbContext.Cocktails.FirstOrDefault(x => x.Id == id);
|
||||
|
||||
public static Salary[] GetSalariesFromDatabaseByEmployeeId(this SquirrelDbContext dbContext, string id) => [.. dbContext.Salaries.Where(x => x.EmployeeId == id)];
|
||||
|
||||
public static Sale? GetSaleFromDatabaseById(this SquirrelDbContext dbContext, string id) => dbContext.Sales.Include(x => x.SaleCocktails).FirstOrDefault(x => x.Id == id);
|
||||
|
||||
public static Sale[] GetSalesByClientId(this SquirrelDbContext dbContext, string? clientId) => [.. dbContext.Sales.Include(x => x.SaleCocktails).Where(x => x.ClientId == clientId)];
|
||||
|
||||
public static Employee? GetEmployeeFromDatabaseById(this SquirrelDbContext dbContext, string id) => dbContext.Employees.FirstOrDefault(x => x.Id == id);
|
||||
|
||||
public static void RemoveClientsFromDatabase(this SquirrelDbContext dbContext) => dbContext.ExecuteSqlRaw("TRUNCATE \"Clients\" CASCADE;");
|
||||
|
||||
public static void RemovePostsFromDatabase(this SquirrelDbContext dbContext) => dbContext.ExecuteSqlRaw("TRUNCATE \"Posts\" CASCADE;");
|
||||
|
||||
public static void RemoveCocktailsFromDatabase(this SquirrelDbContext dbContext) => dbContext.ExecuteSqlRaw("TRUNCATE \"Cocktails\" CASCADE;");
|
||||
|
||||
public static void RemoveSalariesFromDatabase(this SquirrelDbContext dbContext) => dbContext.ExecuteSqlRaw("TRUNCATE \"Salaries\" CASCADE;");
|
||||
|
||||
public static void RemoveSalesFromDatabase(this SquirrelDbContext dbContext) => dbContext.ExecuteSqlRaw("TRUNCATE \"Sales\" CASCADE;");
|
||||
|
||||
public static void RemoveEmployeesFromDatabase(this SquirrelDbContext dbContext) => dbContext.ExecuteSqlRaw("TRUNCATE \"Employees\" CASCADE;");
|
||||
|
||||
private static void ExecuteSqlRaw(this SquirrelDbContext dbContext, string command) => dbContext.Database.ExecuteSqlRaw(command);
|
||||
}
|
||||
@@ -10,17 +10,20 @@
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="coverlet.collector" Version="6.0.2" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="9.0.3" />
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.12.0" />
|
||||
<PackageReference Include="Moq" Version="4.20.72" />
|
||||
<PackageReference Include="NUnit" Version="4.2.2" />
|
||||
<PackageReference Include="NUnit.Analyzers" Version="4.4.0" />
|
||||
<PackageReference Include="NUnit3TestAdapter" Version="4.6.0" />
|
||||
<PackageReference Include="Serilog" Version="4.2.0" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\SquirrelBusinessLogic\SquirrelBusinessLogic.csproj" />
|
||||
<ProjectReference Include="..\SquirrelContract\SquirrelContract.csproj" />
|
||||
<ProjectReference Include="..\SquirrelDatabase\SquirrelDatabase.csproj" />
|
||||
<ProjectReference Include="..\SquirrelWebApi\SquirrelWebApi.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
||||
@@ -6,6 +6,7 @@ using SquirrelDatabase.Models;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using SquirrelContract.StoragesContracts;
|
||||
using SquirrelTests.StoragesContracts;
|
||||
using SquirrelTests.Infrastructure;
|
||||
|
||||
namespace SquirrelTests.StorageContracts;
|
||||
|
||||
@@ -23,17 +24,17 @@ internal class ClientStorageContractTests : BaseStorageContractTest
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
SquirrelDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Sales\" CASCADE;");
|
||||
SquirrelDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Employees\" CASCADE;");
|
||||
SquirrelDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Clients\" CASCADE;");
|
||||
}
|
||||
SquirrelDbContext.RemoveSalesFromDatabase();
|
||||
SquirrelDbContext.RemoveEmployeesFromDatabase();
|
||||
SquirrelDbContext.RemoveClientsFromDatabase();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_WhenHaveRecords_Test()
|
||||
{
|
||||
var client = InsertClientToDatabaseAndReturn(Guid.NewGuid().ToString(), phoneNumber: "+5-555-555-55-55");
|
||||
InsertClientToDatabaseAndReturn(Guid.NewGuid().ToString(), phoneNumber: "+6-666-666-66-66");
|
||||
InsertClientToDatabaseAndReturn(Guid.NewGuid().ToString(), phoneNumber: "+7-777-777-77-77");
|
||||
var client = SquirrelDbContext.InsertClientToDatabaseAndReturn(Guid.NewGuid().ToString(), phoneNumber: "+5-555-555-55-55");
|
||||
SquirrelDbContext.InsertClientToDatabaseAndReturn(Guid.NewGuid().ToString(), phoneNumber: "+6-666-666-66-66");
|
||||
SquirrelDbContext.InsertClientToDatabaseAndReturn(Guid.NewGuid().ToString(), phoneNumber: "+7-777-777-77-77");
|
||||
var list = _clientStorageContract.GetList();
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(3));
|
||||
@@ -51,42 +52,42 @@ internal class ClientStorageContractTests : BaseStorageContractTest
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenHaveRecord_Test()
|
||||
{
|
||||
var client = InsertClientToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
var client = SquirrelDbContext.InsertClientToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
AssertElement(_clientStorageContract.GetElementById(client.Id), client);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenNoRecord_Test()
|
||||
{
|
||||
InsertClientToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
SquirrelDbContext.InsertClientToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
Assert.That(() => _clientStorageContract.GetElementById(Guid.NewGuid().ToString()), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementByFIO_WhenHaveRecord_Test()
|
||||
{
|
||||
var client = InsertClientToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
var client = SquirrelDbContext.InsertClientToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
AssertElement(_clientStorageContract.GetElementByFIO(client.FIO), client);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementByFIO_WhenNoRecord_Test()
|
||||
{
|
||||
InsertClientToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
SquirrelDbContext.InsertClientToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
Assert.That(() => _clientStorageContract.GetElementByFIO("New Fio"), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementByPhoneNumber_WhenHaveRecord_Test()
|
||||
{
|
||||
var client = InsertClientToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
var client = SquirrelDbContext.InsertClientToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
AssertElement(_clientStorageContract.GetElementByPhoneNumber(client.PhoneNumber), client);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementByPhoneNumber_WhenNoRecord_Test()
|
||||
{
|
||||
InsertClientToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
SquirrelDbContext.InsertClientToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
Assert.That(() => _clientStorageContract.GetElementByPhoneNumber("+8-888-888-88-88"), Is.Null);
|
||||
}
|
||||
|
||||
@@ -95,14 +96,14 @@ internal class ClientStorageContractTests : BaseStorageContractTest
|
||||
{
|
||||
var client = CreateModel(Guid.NewGuid().ToString());
|
||||
_clientStorageContract.AddElement(client);
|
||||
AssertElement(GetClientFromDatabase(client.Id), client);
|
||||
AssertElement(SquirrelDbContext.GetClientFromDatabase(client.Id), client);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_WhenHaveRecordWithSameId_Test()
|
||||
{
|
||||
var client = CreateModel(Guid.NewGuid().ToString(), "New Fio", "+5-555-555-55-55", 500);
|
||||
InsertClientToDatabaseAndReturn(client.Id);
|
||||
SquirrelDbContext.InsertClientToDatabaseAndReturn(client.Id);
|
||||
Assert.That(() => _clientStorageContract.AddElement(client), Throws.TypeOf<ElementExistsException>());
|
||||
}
|
||||
|
||||
@@ -110,7 +111,7 @@ internal class ClientStorageContractTests : BaseStorageContractTest
|
||||
public void Try_AddElement_WhenHaveRecordWithSamePhoneNumber_Test()
|
||||
{
|
||||
var client = CreateModel(Guid.NewGuid().ToString(), "New Fio", "+5-555-555-55-55", 500);
|
||||
InsertClientToDatabaseAndReturn(Guid.NewGuid().ToString(), phoneNumber: client.PhoneNumber);
|
||||
SquirrelDbContext.InsertClientToDatabaseAndReturn(Guid.NewGuid().ToString(), phoneNumber: client.PhoneNumber);
|
||||
Assert.That(() => _clientStorageContract.AddElement(client), Throws.TypeOf<ElementExistsException>());
|
||||
}
|
||||
|
||||
@@ -118,9 +119,9 @@ internal class ClientStorageContractTests : BaseStorageContractTest
|
||||
public void Try_UpdElement_Test()
|
||||
{
|
||||
var client = CreateModel(Guid.NewGuid().ToString(), "New Fio", "+5-555-555-55-55", 500);
|
||||
InsertClientToDatabaseAndReturn(client.Id);
|
||||
SquirrelDbContext.InsertClientToDatabaseAndReturn(client.Id);
|
||||
_clientStorageContract.UpdElement(client);
|
||||
AssertElement(GetClientFromDatabase(client.Id), client);
|
||||
AssertElement(SquirrelDbContext.GetClientFromDatabase(client.Id), client);
|
||||
}
|
||||
|
||||
[Test]
|
||||
@@ -133,24 +134,24 @@ internal class ClientStorageContractTests : BaseStorageContractTest
|
||||
public void Try_UpdElement_WhenHaveRecordWithSamePhoneNumber_Test()
|
||||
{
|
||||
var client = CreateModel(Guid.NewGuid().ToString(), "New Fio", "+5-555-555-55-55", 500);
|
||||
InsertClientToDatabaseAndReturn(client.Id, phoneNumber: "+7-777-777-77-77");
|
||||
InsertClientToDatabaseAndReturn(Guid.NewGuid().ToString(), phoneNumber: client.PhoneNumber);
|
||||
SquirrelDbContext.InsertClientToDatabaseAndReturn(client.Id, phoneNumber: "+7-777-777-77-77");
|
||||
SquirrelDbContext.InsertClientToDatabaseAndReturn(Guid.NewGuid().ToString(), phoneNumber: client.PhoneNumber);
|
||||
Assert.That(() => _clientStorageContract.UpdElement(client), Throws.TypeOf<ElementExistsException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_DelElement_Test()
|
||||
{
|
||||
var client = InsertClientToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
var client = SquirrelDbContext.InsertClientToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
_clientStorageContract.DelElement(client.Id);
|
||||
var element = GetClientFromDatabase(client.Id);
|
||||
var element = SquirrelDbContext.GetClientFromDatabase(client.Id);
|
||||
Assert.That(element, Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_DelElement_WhenHaveSalesByThisClient_Test()
|
||||
{
|
||||
var client = InsertClientToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
var client = SquirrelDbContext.InsertClientToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
var employeeId = Guid.NewGuid().ToString();
|
||||
SquirrelDbContext.Employees.Add(new Employee() { Id = employeeId, FIO = "test", PostId = Guid.NewGuid().ToString(), Email = "abc@gmail.com" });
|
||||
SquirrelDbContext.Sales.Add(new Sale() { Id = Guid.NewGuid().ToString(), EmployeeId = employeeId, ClientId = client.Id, Sum = 10, DiscountType = DiscountType.None, Discount = 0 });
|
||||
@@ -158,7 +159,7 @@ internal class ClientStorageContractTests : BaseStorageContractTest
|
||||
SquirrelDbContext.SaveChanges();
|
||||
var salesBeforeDelete = SquirrelDbContext.Sales.Where(x => x.ClientId == client.Id).ToArray();
|
||||
_clientStorageContract.DelElement(client.Id);
|
||||
var element = GetClientFromDatabase(client.Id);
|
||||
var element = SquirrelDbContext.GetClientFromDatabase(client.Id);
|
||||
var salesAfterDelete = SquirrelDbContext.Sales.Where(x => x.ClientId == client.Id).ToArray();
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
@@ -175,14 +176,6 @@ internal class ClientStorageContractTests : BaseStorageContractTest
|
||||
Assert.That(() => _clientStorageContract.DelElement(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
|
||||
}
|
||||
|
||||
private Client InsertClientToDatabaseAndReturn(string id, string fio = "test", string phoneNumber = "+7-777-777-77-77", double discountSize = 10)
|
||||
{
|
||||
var client = new Client() { Id = id, FIO = fio, PhoneNumber = phoneNumber, DiscountSize = discountSize };
|
||||
SquirrelDbContext.Clients.Add(client);
|
||||
SquirrelDbContext.SaveChanges();
|
||||
return client;
|
||||
}
|
||||
|
||||
private static void AssertElement(ClientDataModel? actual, Client expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
@@ -198,8 +191,6 @@ internal class ClientStorageContractTests : BaseStorageContractTest
|
||||
private static ClientDataModel CreateModel(string id, string fio = "test", string phoneNumber = "+7-777-777-77-77", double discountSize = 10)
|
||||
=> new(id, fio, phoneNumber, discountSize);
|
||||
|
||||
private Client? GetClientFromDatabase(string id) => SquirrelDbContext.Clients.FirstOrDefault(x => x.Id == id);
|
||||
|
||||
private static void AssertElement(Client? actual, ClientDataModel expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
|
||||
@@ -4,6 +4,7 @@ using SquirrelContract.Enums;
|
||||
using SquirrelContract.Exceptions;
|
||||
using SquirrelDatabase.Implementations;
|
||||
using SquirrelDatabase.Models;
|
||||
using SquirrelTests.Infrastructure;
|
||||
using SquirrelTests.StoragesContracts;
|
||||
using static NUnit.Framework.Internal.OSPlatform;
|
||||
|
||||
@@ -23,15 +24,15 @@ internal class CocktailStorageContractTests : BaseStorageContractTest
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
SquirrelDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Cocktails\" CASCADE;");
|
||||
SquirrelDbContext.RemoveCocktailsFromDatabase();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_WhenHaveRecords_Test()
|
||||
{
|
||||
var cocktail = InsertCocktailToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 1");
|
||||
InsertCocktailToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 2");
|
||||
InsertCocktailToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 3");
|
||||
var cocktail = SquirrelDbContext.InsertCocktailToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 1");
|
||||
SquirrelDbContext.InsertCocktailToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 2");
|
||||
SquirrelDbContext.InsertCocktailToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 3");
|
||||
var list = _cocktailStorageContract.GetList();
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(3));
|
||||
@@ -49,10 +50,10 @@ internal class CocktailStorageContractTests : BaseStorageContractTest
|
||||
[Test]
|
||||
public void Try_GetHistoryByCocktailId_WhenHaveRecords_Test()
|
||||
{
|
||||
var cocktail = InsertCocktailToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 1");
|
||||
InsertCocktailHistoryToDatabaseAndReturn(cocktail.Id, 20, DateTime.UtcNow.AddDays(-1));
|
||||
InsertCocktailHistoryToDatabaseAndReturn(cocktail.Id, 30, DateTime.UtcNow.AddMinutes(-10));
|
||||
InsertCocktailHistoryToDatabaseAndReturn(cocktail.Id, 40, DateTime.UtcNow.AddDays(1));
|
||||
var cocktail = SquirrelDbContext.InsertCocktailToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 1");
|
||||
SquirrelDbContext.InsertCocktailHistoryToDatabaseAndReturn(cocktail.Id, 20, DateTime.UtcNow.AddDays(-1));
|
||||
SquirrelDbContext.InsertCocktailHistoryToDatabaseAndReturn(cocktail.Id, 30, DateTime.UtcNow.AddMinutes(-10));
|
||||
SquirrelDbContext.InsertCocktailHistoryToDatabaseAndReturn(cocktail.Id, 40, DateTime.UtcNow.AddDays(1));
|
||||
var list = _cocktailStorageContract.GetHistoryByCocktailId(cocktail.Id);
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(3));
|
||||
@@ -61,10 +62,10 @@ internal class CocktailStorageContractTests : BaseStorageContractTest
|
||||
[Test]
|
||||
public void Try_GetHistoryByCocktailId_WhenNoRecords_Test()
|
||||
{
|
||||
var cocktail = InsertCocktailToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 1");
|
||||
InsertCocktailHistoryToDatabaseAndReturn(cocktail.Id, 20, DateTime.UtcNow.AddDays(-1));
|
||||
InsertCocktailHistoryToDatabaseAndReturn(cocktail.Id, 30, DateTime.UtcNow.AddMinutes(-10));
|
||||
InsertCocktailHistoryToDatabaseAndReturn(cocktail.Id, 40, DateTime.UtcNow.AddDays(1));
|
||||
var cocktail = SquirrelDbContext.InsertCocktailToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 1");
|
||||
SquirrelDbContext.InsertCocktailHistoryToDatabaseAndReturn(cocktail.Id, 20, DateTime.UtcNow.AddDays(-1));
|
||||
SquirrelDbContext.InsertCocktailHistoryToDatabaseAndReturn(cocktail.Id, 30, DateTime.UtcNow.AddMinutes(-10));
|
||||
SquirrelDbContext.InsertCocktailHistoryToDatabaseAndReturn(cocktail.Id, 40, DateTime.UtcNow.AddDays(1));
|
||||
var list = _cocktailStorageContract.GetHistoryByCocktailId(Guid.NewGuid().ToString());
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(0));
|
||||
@@ -73,28 +74,28 @@ internal class CocktailStorageContractTests : BaseStorageContractTest
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenHaveRecord_Test()
|
||||
{
|
||||
var cocktail = InsertCocktailToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
var cocktail = SquirrelDbContext.InsertCocktailToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
AssertElement(_cocktailStorageContract.GetElementById(cocktail.Id), cocktail);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenNoRecord_Test()
|
||||
{
|
||||
InsertCocktailToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
SquirrelDbContext.InsertCocktailToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
Assert.That(() => _cocktailStorageContract.GetElementById(Guid.NewGuid().ToString()), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementByName_WhenHaveRecord_Test()
|
||||
{
|
||||
var cocktail = InsertCocktailToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
var cocktail = SquirrelDbContext.InsertCocktailToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
AssertElement(_cocktailStorageContract.GetElementByName(cocktail.CocktailName), cocktail);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementByName_WhenNoRecord_Test()
|
||||
{
|
||||
InsertCocktailToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
SquirrelDbContext.InsertCocktailToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
Assert.That(() => _cocktailStorageContract.GetElementByName("name"), Is.Null);
|
||||
}
|
||||
|
||||
@@ -103,14 +104,14 @@ internal class CocktailStorageContractTests : BaseStorageContractTest
|
||||
{
|
||||
var cocktail = CreateModel(Guid.NewGuid().ToString());
|
||||
_cocktailStorageContract.AddElement(cocktail);
|
||||
AssertElement(GetCocktailFromDatabaseById(cocktail.Id), cocktail);
|
||||
AssertElement(SquirrelDbContext.GetCocktailFromDatabaseById(cocktail.Id), cocktail);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_WhenHaveRecordWithSameId_Test()
|
||||
{
|
||||
var cocktail = CreateModel(Guid.NewGuid().ToString());
|
||||
InsertCocktailToDatabaseAndReturn(cocktail.Id, cocktailName: "name unique");
|
||||
SquirrelDbContext.InsertCocktailToDatabaseAndReturn(cocktail.Id, cocktailName: "name unique");
|
||||
Assert.That(() => _cocktailStorageContract.AddElement(cocktail), Throws.TypeOf<ElementExistsException>());
|
||||
}
|
||||
|
||||
@@ -118,7 +119,7 @@ internal class CocktailStorageContractTests : BaseStorageContractTest
|
||||
public void Try_AddElement_WhenHaveRecordWithSameName_Test()
|
||||
{
|
||||
var cocktail = CreateModel(Guid.NewGuid().ToString(), "name unique");
|
||||
InsertCocktailToDatabaseAndReturn(Guid.NewGuid().ToString(), cocktailName: cocktail.CocktailName);
|
||||
SquirrelDbContext.InsertCocktailToDatabaseAndReturn(Guid.NewGuid().ToString(), cocktailName: cocktail.CocktailName);
|
||||
Assert.That(() => _cocktailStorageContract.AddElement(cocktail), Throws.TypeOf<ElementExistsException>());
|
||||
}
|
||||
|
||||
@@ -126,9 +127,9 @@ internal class CocktailStorageContractTests : BaseStorageContractTest
|
||||
public void Try_UpdElement_Test()
|
||||
{
|
||||
var cocktail = CreateModel(Guid.NewGuid().ToString(), "new name", AlcoholType.Vodka);
|
||||
InsertCocktailToDatabaseAndReturn(cocktail.Id);
|
||||
SquirrelDbContext.InsertCocktailToDatabaseAndReturn(cocktail.Id);
|
||||
_cocktailStorageContract.UpdElement(cocktail);
|
||||
AssertElement(GetCocktailFromDatabaseById(cocktail.Id), cocktail);
|
||||
AssertElement(SquirrelDbContext.GetCocktailFromDatabaseById(cocktail.Id), cocktail);
|
||||
}
|
||||
|
||||
[Test]
|
||||
@@ -141,17 +142,17 @@ internal class CocktailStorageContractTests : BaseStorageContractTest
|
||||
public void Try_UpdElement_WhenHaveRecordWithSameName_Test()
|
||||
{
|
||||
var cocktail = CreateModel(Guid.NewGuid().ToString(), "name unique");
|
||||
InsertCocktailToDatabaseAndReturn(cocktail.Id, cocktailName: "name");
|
||||
InsertCocktailToDatabaseAndReturn(Guid.NewGuid().ToString(), cocktailName: cocktail.CocktailName);
|
||||
SquirrelDbContext.InsertCocktailToDatabaseAndReturn(cocktail.Id, cocktailName: "name");
|
||||
SquirrelDbContext.InsertCocktailToDatabaseAndReturn(cocktailName: cocktail.CocktailName);
|
||||
Assert.That(() => _cocktailStorageContract.UpdElement(cocktail), Throws.TypeOf<ElementExistsException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_DelElement_Test()
|
||||
{
|
||||
var cocktail = InsertCocktailToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
var cocktail = SquirrelDbContext.InsertCocktailToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
_cocktailStorageContract.DelElement(cocktail.Id);
|
||||
var element = GetCocktailFromDatabaseById(cocktail.Id);
|
||||
var element = SquirrelDbContext.GetCocktailFromDatabaseById(cocktail.Id);
|
||||
Assert.That(element, Is.Null);
|
||||
}
|
||||
|
||||
@@ -160,23 +161,6 @@ internal class CocktailStorageContractTests : BaseStorageContractTest
|
||||
{
|
||||
Assert.That(() => _cocktailStorageContract.DelElement(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
|
||||
}
|
||||
|
||||
private Cocktail InsertCocktailToDatabaseAndReturn(string id, string cocktailName = "test", AlcoholType baseAlcohol = AlcoholType.Vodka, double price = 1)
|
||||
{
|
||||
var cocktail = new Cocktail() { Id = id, CocktailName = cocktailName, BaseAlcohol = baseAlcohol, Price = price };
|
||||
SquirrelDbContext.Cocktails.Add(cocktail);
|
||||
SquirrelDbContext.SaveChanges();
|
||||
return cocktail;
|
||||
}
|
||||
|
||||
private CocktailHistory InsertCocktailHistoryToDatabaseAndReturn(string cocktailId, double price, DateTime changeDate)
|
||||
{
|
||||
var cocktailHistory = new CocktailHistory() { Id = Guid.NewGuid().ToString(), CocktailId = cocktailId, OldPrice = price, ChangeDate = changeDate };
|
||||
SquirrelDbContext.CocktailHistories.Add(cocktailHistory);
|
||||
SquirrelDbContext.SaveChanges();
|
||||
return cocktailHistory;
|
||||
}
|
||||
|
||||
private static void AssertElement(CocktailDataModel? actual, Cocktail expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
@@ -192,8 +176,6 @@ internal class CocktailStorageContractTests : BaseStorageContractTest
|
||||
private static CocktailDataModel CreateModel(string id, string cocktailName = "test", AlcoholType baseAlcohol = AlcoholType.Beer, double price = 1)
|
||||
=> new(id, cocktailName, price, baseAlcohol);
|
||||
|
||||
private Cocktail? GetCocktailFromDatabaseById(string id) => SquirrelDbContext.Cocktails.FirstOrDefault(x => x.Id == id);
|
||||
|
||||
private static void AssertElement(Cocktail? actual, CocktailDataModel expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
|
||||
@@ -6,6 +6,7 @@ using SquirrelDatabase.Models;
|
||||
using SquirrelContract.DataModels;
|
||||
using SquirrelTests.StoragesContracts;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using SquirrelTests.Infrastructure;
|
||||
|
||||
namespace SquirrelTests.StorageContracts;
|
||||
|
||||
@@ -23,19 +24,19 @@ internal class EmployeeStorageContractTests : BaseStorageContractTest
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
SquirrelDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Employees\" CASCADE;");
|
||||
SquirrelDbContext.RemoveEmployeesFromDatabase();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_WhenHaveRecords_Test()
|
||||
{
|
||||
var employee = InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 1", "abc@gmail.com");
|
||||
InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 2", "abc@gmail.com");
|
||||
InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 3", "abc@gmail.com");
|
||||
var employee = SquirrelDbContext.InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 1", "abc@gmail.com");
|
||||
SquirrelDbContext.InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 2", "abc@gmail.com");
|
||||
SquirrelDbContext.InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 3", "abc@gmail.com");
|
||||
var list = _employeeStorageContract.GetList();
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(3));
|
||||
AssertElement(list.First(), employee);
|
||||
AssertElement(list.First(x => x.Id == employee.Id), employee);
|
||||
}
|
||||
|
||||
[Test]
|
||||
@@ -50,9 +51,9 @@ internal class EmployeeStorageContractTests : BaseStorageContractTest
|
||||
public void Try_GetList_ByPostId_Test()
|
||||
{
|
||||
var postId = Guid.NewGuid().ToString();
|
||||
InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 1", "abc@gmail.com", postId);
|
||||
InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 2", "abc@gmail.com", postId);
|
||||
InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 3", "abc@gmail.com");
|
||||
SquirrelDbContext.InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 1", "abc@gmail.com", postId);
|
||||
SquirrelDbContext.InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 2", "abc@gmail.com", postId);
|
||||
SquirrelDbContext.InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 3", "abc@gmail.com");
|
||||
var list = _employeeStorageContract.GetList(postId: postId);
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(2));
|
||||
@@ -62,10 +63,10 @@ internal class EmployeeStorageContractTests : BaseStorageContractTest
|
||||
[Test]
|
||||
public void Try_GetList_ByBirthDate_Test()
|
||||
{
|
||||
InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 1", "abc@gmail.com", birthDate: DateTime.UtcNow.AddYears(-25));
|
||||
InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 2", "abc@gmail.com", birthDate: DateTime.UtcNow.AddYears(-21));
|
||||
InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 3", "abc@gmail.com", birthDate: DateTime.UtcNow.AddYears(-20));
|
||||
InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 4", "abc@gmail.com", birthDate: DateTime.UtcNow.AddYears(-19));
|
||||
SquirrelDbContext.InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 1", "abc@gmail.com", birthDate: DateTime.UtcNow.AddYears(-25));
|
||||
SquirrelDbContext.InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 2", "abc@gmail.com", birthDate: DateTime.UtcNow.AddYears(-21));
|
||||
SquirrelDbContext.InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 3", "abc@gmail.com", birthDate: DateTime.UtcNow.AddYears(-20));
|
||||
SquirrelDbContext.InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 4", "abc@gmail.com", birthDate: DateTime.UtcNow.AddYears(-19));
|
||||
var list = _employeeStorageContract.GetList(fromBirthDate: DateTime.UtcNow.AddYears(-21).AddMinutes(-1), toBirthDate: DateTime.UtcNow.AddYears(-20).AddMinutes(1));
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(2));
|
||||
@@ -74,10 +75,10 @@ internal class EmployeeStorageContractTests : BaseStorageContractTest
|
||||
[Test]
|
||||
public void Try_GetList_ByEmploymentDate_Test()
|
||||
{
|
||||
InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 1", "abc@gmail.com", employmentDate: DateTime.UtcNow.AddDays(-2));
|
||||
InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 2", "abc@gmail.com", employmentDate: DateTime.UtcNow.AddDays(-1));
|
||||
InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 3", "abc@gmail.com", employmentDate: DateTime.UtcNow.AddDays(1));
|
||||
InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 4", "abc@gmail.com", employmentDate: DateTime.UtcNow.AddDays(2));
|
||||
SquirrelDbContext.InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 1", "abc@gmail.com", employmentDate: DateTime.UtcNow.AddDays(-2));
|
||||
SquirrelDbContext.InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 2", "abc@gmail.com", employmentDate: DateTime.UtcNow.AddDays(-1));
|
||||
SquirrelDbContext.InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 3", "abc@gmail.com", employmentDate: DateTime.UtcNow.AddDays(1));
|
||||
SquirrelDbContext.InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 4", "abc@gmail.com", employmentDate: DateTime.UtcNow.AddDays(2));
|
||||
var list = _employeeStorageContract.GetList(fromEmploymentDate: DateTime.UtcNow.AddDays(-1).AddMinutes(-1), toEmploymentDate: DateTime.UtcNow.AddDays(1).AddMinutes(1));
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(2));
|
||||
@@ -87,10 +88,10 @@ internal class EmployeeStorageContractTests : BaseStorageContractTest
|
||||
public void Try_GetList_ByAllParameters_Test()
|
||||
{
|
||||
var postId = Guid.NewGuid().ToString();
|
||||
InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 1", "abc@gmail.com", postId, birthDate: DateTime.UtcNow.AddYears(-25), employmentDate: DateTime.UtcNow.AddDays(-2));
|
||||
InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 2", "abc@gmail.com", postId, birthDate: DateTime.UtcNow.AddYears(-22), employmentDate: DateTime.UtcNow.AddDays(-1));
|
||||
InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 3", "abc@gmail.com", postId, birthDate: DateTime.UtcNow.AddYears(-21), employmentDate: DateTime.UtcNow.AddDays(-1));
|
||||
InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 4", "abc@gmail.com", birthDate: DateTime.UtcNow.AddYears(-20), employmentDate: DateTime.UtcNow.AddDays(1));
|
||||
SquirrelDbContext.InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 1", "abc@gmail.com", postId, birthDate: DateTime.UtcNow.AddYears(-25), employmentDate: DateTime.UtcNow.AddDays(-2));
|
||||
SquirrelDbContext.InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 2", "abc@gmail.com", postId, birthDate: DateTime.UtcNow.AddYears(-22), employmentDate: DateTime.UtcNow.AddDays(-1));
|
||||
SquirrelDbContext.InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 3", "abc@gmail.com", postId, birthDate: DateTime.UtcNow.AddYears(-21), employmentDate: DateTime.UtcNow.AddDays(-1));
|
||||
SquirrelDbContext.InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 4", "abc@gmail.com", birthDate: DateTime.UtcNow.AddYears(-20), employmentDate: DateTime.UtcNow.AddDays(1));
|
||||
var list = _employeeStorageContract.GetList(postId: postId, fromBirthDate: DateTime.UtcNow.AddYears(-21).AddMinutes(-1), toBirthDate: DateTime.UtcNow.AddYears(-20).AddMinutes(1), fromEmploymentDate: DateTime.UtcNow.AddDays(-1).AddMinutes(-1), toEmploymentDate: DateTime.UtcNow.AddDays(1).AddMinutes(1));
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(1));
|
||||
@@ -99,7 +100,7 @@ internal class EmployeeStorageContractTests : BaseStorageContractTest
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenHaveRecord_Test()
|
||||
{
|
||||
var employee = InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
var employee = SquirrelDbContext.InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
AssertElement(_employeeStorageContract.GetElementById(employee.Id), employee);
|
||||
}
|
||||
|
||||
@@ -112,7 +113,7 @@ internal class EmployeeStorageContractTests : BaseStorageContractTest
|
||||
[Test]
|
||||
public void Try_GetElementByFIO_WhenHaveRecord_Test()
|
||||
{
|
||||
var employee = InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
var employee = SquirrelDbContext.InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
AssertElement(_employeeStorageContract.GetElementByFIO(employee.FIO), employee);
|
||||
}
|
||||
|
||||
@@ -127,14 +128,14 @@ internal class EmployeeStorageContractTests : BaseStorageContractTest
|
||||
{
|
||||
var employee = CreateModel(Guid.NewGuid().ToString());
|
||||
_employeeStorageContract.AddElement(employee);
|
||||
AssertElement(GetEmployeeFromDatabase(employee.Id), employee);
|
||||
AssertElement(SquirrelDbContext.GetEmployeeFromDatabaseById(employee.Id), employee);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_WhenHaveRecordWithSameId_Test()
|
||||
{
|
||||
var employee = CreateModel(Guid.NewGuid().ToString());
|
||||
InsertEmployeeToDatabaseAndReturn(employee.Id);
|
||||
SquirrelDbContext.InsertEmployeeToDatabaseAndReturn(employee.Id);
|
||||
Assert.That(() => _employeeStorageContract.AddElement(employee), Throws.TypeOf<ElementExistsException>());
|
||||
}
|
||||
|
||||
@@ -142,9 +143,9 @@ internal class EmployeeStorageContractTests : BaseStorageContractTest
|
||||
public void Try_UpdElement_Test()
|
||||
{
|
||||
var employee = CreateModel(Guid.NewGuid().ToString(), "New Fio");
|
||||
InsertEmployeeToDatabaseAndReturn(employee.Id);
|
||||
SquirrelDbContext.InsertEmployeeToDatabaseAndReturn(employee.Id);
|
||||
_employeeStorageContract.UpdElement(employee);
|
||||
AssertElement(GetEmployeeFromDatabase(employee.Id), employee);
|
||||
AssertElement(SquirrelDbContext.GetEmployeeFromDatabaseById(employee.Id), employee);
|
||||
}
|
||||
|
||||
[Test]
|
||||
@@ -157,16 +158,16 @@ internal class EmployeeStorageContractTests : BaseStorageContractTest
|
||||
public void Try_UpdElement_WhenNoRecordWasDeleted_Test()
|
||||
{
|
||||
var employee = CreateModel(Guid.NewGuid().ToString());
|
||||
InsertEmployeeToDatabaseAndReturn(employee.Id, isDeleted: true);
|
||||
SquirrelDbContext.InsertEmployeeToDatabaseAndReturn(employee.Id, isDeleted: true);
|
||||
Assert.That(() => _employeeStorageContract.UpdElement(employee), Throws.TypeOf<ElementNotFoundException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_DelElement_Test()
|
||||
{
|
||||
var employee = InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
var employee = SquirrelDbContext.InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
_employeeStorageContract.DelElement(employee.Id);
|
||||
var element = GetEmployeeFromDatabase(employee.Id);
|
||||
var element = SquirrelDbContext.GetEmployeeFromDatabaseById(employee.Id);
|
||||
Assert.That(element, Is.Not.Null);
|
||||
Assert.That(element.IsDeleted);
|
||||
}
|
||||
@@ -181,18 +182,10 @@ internal class EmployeeStorageContractTests : BaseStorageContractTest
|
||||
public void Try_DelElement_WhenNoRecordWasDeleted_Test()
|
||||
{
|
||||
var employee = CreateModel(Guid.NewGuid().ToString());
|
||||
InsertEmployeeToDatabaseAndReturn(employee.Id, isDeleted: true);
|
||||
SquirrelDbContext.InsertEmployeeToDatabaseAndReturn(employee.Id, isDeleted: true);
|
||||
Assert.That(() => _employeeStorageContract.DelElement(employee.Id), Throws.TypeOf<ElementNotFoundException>());
|
||||
}
|
||||
|
||||
private Employee InsertEmployeeToDatabaseAndReturn(string id, string fio = "test", string email = "abc@mail.ru", string? postId = null, DateTime? birthDate = null, DateTime? employmentDate = null, bool isDeleted = false)
|
||||
{
|
||||
var employee = new Employee() { Id = id, FIO = fio, Email = email, PostId = postId ?? Guid.NewGuid().ToString(), BirthDate = birthDate ?? DateTime.UtcNow.AddYears(-20), EmploymentDate = employmentDate ?? DateTime.UtcNow, IsDeleted = isDeleted };
|
||||
SquirrelDbContext.Employees.Add(employee);
|
||||
SquirrelDbContext.SaveChanges();
|
||||
return employee;
|
||||
}
|
||||
|
||||
private static void AssertElement(EmployeeDataModel? actual, Employee expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
@@ -211,8 +204,6 @@ internal class EmployeeStorageContractTests : BaseStorageContractTest
|
||||
private static EmployeeDataModel CreateModel(string id, string fio = "fio", string email = "abc@mail.ru", string? postId = null, DateTime? birthDate = null, DateTime? employmentDate = null, bool isDeleted = false) =>
|
||||
new(id, fio, email, postId ?? Guid.NewGuid().ToString(), birthDate ?? DateTime.UtcNow.AddYears(-20), employmentDate ?? DateTime.UtcNow, isDeleted);
|
||||
|
||||
private Employee? GetEmployeeFromDatabase(string id) => SquirrelDbContext.Employees.FirstOrDefault(x => x.Id == id);
|
||||
|
||||
private static void AssertElement(Employee? actual, EmployeeDataModel expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
|
||||
@@ -4,6 +4,7 @@ using SquirrelContract.Enums;
|
||||
using SquirrelContract.Exceptions;
|
||||
using SquirrelDatabase.Implementations;
|
||||
using SquirrelDatabase.Models;
|
||||
using SquirrelTests.Infrastructure;
|
||||
using SquirrelTests.StoragesContracts;
|
||||
|
||||
namespace SquirrelTests.StorageContracts;
|
||||
@@ -22,15 +23,15 @@ internal class PostStorageContractTests : BaseStorageContractTest
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
SquirrelDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Posts\" CASCADE;");
|
||||
SquirrelDbContext.RemovePostsFromDatabase();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_WhenHaveRecords_Test()
|
||||
{
|
||||
var post = InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 1");
|
||||
InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 2");
|
||||
InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 3");
|
||||
var post = SquirrelDbContext.InsertPostToDatabaseAndReturn(postName: "name 1");
|
||||
SquirrelDbContext.InsertPostToDatabaseAndReturn(postName: "name 2");
|
||||
SquirrelDbContext.InsertPostToDatabaseAndReturn(postName: "name 3");
|
||||
var list = _postStorageContract.GetList();
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(3));
|
||||
@@ -45,44 +46,13 @@ internal class PostStorageContractTests : BaseStorageContractTest
|
||||
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);
|
||||
SquirrelDbContext.InsertPostToDatabaseAndReturn(postName: "name 1", isActual: true);
|
||||
SquirrelDbContext.InsertPostToDatabaseAndReturn(postId, "name 2", isActual: true);
|
||||
SquirrelDbContext.InsertPostToDatabaseAndReturn(postId, "name 2", isActual: false);
|
||||
var list = _postStorageContract.GetPostWithHistory(postId);
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(2));
|
||||
@@ -92,9 +62,9 @@ internal class PostStorageContractTests : BaseStorageContractTest
|
||||
public void Try_GetPostWithHistory_WhenNoRecords_Test()
|
||||
{
|
||||
var postId = Guid.NewGuid().ToString();
|
||||
InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 1", isActual: true);
|
||||
InsertPostToDatabaseAndReturn(postId, "name 2", isActual: true);
|
||||
InsertPostToDatabaseAndReturn(postId, "name 2", isActual: false);
|
||||
SquirrelDbContext.InsertPostToDatabaseAndReturn(postName: "name 1", isActual: true);
|
||||
SquirrelDbContext.InsertPostToDatabaseAndReturn(postId, "name 2", isActual: true);
|
||||
SquirrelDbContext.InsertPostToDatabaseAndReturn(postId, "name 2", isActual: false);
|
||||
var list = _postStorageContract.GetPostWithHistory(Guid.NewGuid().ToString());
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(0));
|
||||
@@ -103,81 +73,73 @@ internal class PostStorageContractTests : BaseStorageContractTest
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenHaveRecord_Test()
|
||||
{
|
||||
var post = InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
var post = SquirrelDbContext.InsertPostToDatabaseAndReturn();
|
||||
AssertElement(_postStorageContract.GetElementById(post.PostId), post);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenNoRecord_Test()
|
||||
{
|
||||
InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
SquirrelDbContext.InsertPostToDatabaseAndReturn();
|
||||
Assert.That(() => _postStorageContract.GetElementById(Guid.NewGuid().ToString()), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenRecordHasDeleted_Test()
|
||||
public void Try_GetElementById_WhenRecordWasDeleted_Test()
|
||||
{
|
||||
var post = InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), isActual: false);
|
||||
var post = SquirrelDbContext.InsertPostToDatabaseAndReturn(isActual: false);
|
||||
Assert.That(() => _postStorageContract.GetElementById(post.PostId), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenTrySearchById_Test()
|
||||
{
|
||||
var post = InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
var post = SquirrelDbContext.InsertPostToDatabaseAndReturn();
|
||||
Assert.That(() => _postStorageContract.GetElementById(post.Id), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementByName_WhenHaveRecord_Test()
|
||||
{
|
||||
var post = InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
var post = SquirrelDbContext.InsertPostToDatabaseAndReturn();
|
||||
AssertElement(_postStorageContract.GetElementByName(post.PostName), post);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementByName_WhenNoRecord_Test()
|
||||
{
|
||||
InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
SquirrelDbContext.InsertPostToDatabaseAndReturn();
|
||||
Assert.That(() => _postStorageContract.GetElementByName("name"), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementByName_WhenRecordHasDeleted_Test()
|
||||
public void Try_GetElementByName_WhenRecordWasDeleted_Test()
|
||||
{
|
||||
var post = InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), isActual: false);
|
||||
var post = SquirrelDbContext.InsertPostToDatabaseAndReturn(isActual: false);
|
||||
Assert.That(() => _postStorageContract.GetElementById(post.PostName), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_Test()
|
||||
{
|
||||
var post = CreateModel(Guid.NewGuid().ToString(), isActual: true);
|
||||
var post = CreateModel(Guid.NewGuid().ToString());
|
||||
_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));
|
||||
AssertElement(SquirrelDbContext.GetPostFromDatabaseByPostId(post.Id), post);
|
||||
}
|
||||
|
||||
[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);
|
||||
var post = CreateModel(Guid.NewGuid().ToString(), "name unique");
|
||||
SquirrelDbContext.InsertPostToDatabaseAndReturn(postName: post.PostName, isActual: true);
|
||||
Assert.That(() => _postStorageContract.AddElement(post), Throws.TypeOf<ElementExistsException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_WhenHaveRecordWithSamePostIdAndActualIsTrue_Test()
|
||||
public void Try_AddElement_WhenHaveRecordWithSamePostId_Test()
|
||||
{
|
||||
var post = CreateModel(Guid.NewGuid().ToString(), isActual: true);
|
||||
InsertPostToDatabaseAndReturn(post.Id, isActual: true);
|
||||
var post = CreateModel(Guid.NewGuid().ToString());
|
||||
SquirrelDbContext.InsertPostToDatabaseAndReturn(post.Id, isActual: true);
|
||||
Assert.That(() => _postStorageContract.AddElement(post), Throws.TypeOf<ElementExistsException>());
|
||||
}
|
||||
|
||||
@@ -185,21 +147,13 @@ internal class PostStorageContractTests : BaseStorageContractTest
|
||||
public void Try_UpdElement_Test()
|
||||
{
|
||||
var post = CreateModel(Guid.NewGuid().ToString());
|
||||
InsertPostToDatabaseAndReturn(post.Id, isActual: true);
|
||||
SquirrelDbContext.InsertPostToDatabaseAndReturn(post.Id, isActual: true);
|
||||
_postStorageContract.UpdElement(post);
|
||||
var posts = SquirrelDbContext.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));
|
||||
var posts = SquirrelDbContext.GetPostsFromDatabaseByPostId(post.Id);
|
||||
Assert.That(posts, Is.Not.Null);
|
||||
Assert.That(posts, Has.Length.EqualTo(2));
|
||||
AssertElement(posts[0], CreateModel(post.Id));
|
||||
AssertElement(posts[^1], CreateModel(post.Id));
|
||||
}
|
||||
|
||||
[Test]
|
||||
@@ -212,8 +166,8 @@ internal class PostStorageContractTests : BaseStorageContractTest
|
||||
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);
|
||||
SquirrelDbContext.InsertPostToDatabaseAndReturn(post.Id, postName: "name");
|
||||
SquirrelDbContext.InsertPostToDatabaseAndReturn(postName: post.PostName);
|
||||
Assert.That(() => _postStorageContract.UpdElement(post), Throws.TypeOf<ElementExistsException>());
|
||||
}
|
||||
|
||||
@@ -221,21 +175,16 @@ internal class PostStorageContractTests : BaseStorageContractTest
|
||||
public void Try_UpdElement_WhenRecordWasDeleted_Test()
|
||||
{
|
||||
var post = CreateModel(Guid.NewGuid().ToString());
|
||||
InsertPostToDatabaseAndReturn(post.Id, isActual: false);
|
||||
SquirrelDbContext.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);
|
||||
var post = SquirrelDbContext.InsertPostToDatabaseAndReturn(isActual: true);
|
||||
_postStorageContract.DelElement(post.PostId);
|
||||
var element = GetPostFromDatabaseByPostId(post.PostId);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(element, Is.Not.Null);
|
||||
Assert.That(!element!.IsActual);
|
||||
});
|
||||
Assert.That(SquirrelDbContext.GetPostFromDatabaseByPostId(post.PostId), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
@@ -247,16 +196,16 @@ internal class PostStorageContractTests : BaseStorageContractTest
|
||||
[Test]
|
||||
public void Try_DelElement_WhenRecordWasDeleted_Test()
|
||||
{
|
||||
var post = InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), isActual: false);
|
||||
var post = SquirrelDbContext.InsertPostToDatabaseAndReturn(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);
|
||||
var post = SquirrelDbContext.InsertPostToDatabaseAndReturn(isActual: false);
|
||||
_postStorageContract.ResElement(post.PostId);
|
||||
var element = GetPostFromDatabaseByPostId(post.PostId);
|
||||
var element = SquirrelDbContext.GetPostFromDatabaseByPostId(post.PostId);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(element, Is.Not.Null);
|
||||
@@ -273,18 +222,10 @@ internal class PostStorageContractTests : BaseStorageContractTest
|
||||
[Test]
|
||||
public void Try_ResElement_WhenRecordNotWasDeleted_Test()
|
||||
{
|
||||
var post = InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), isActual: true);
|
||||
var post = SquirrelDbContext.InsertPostToDatabaseAndReturn(isActual: true);
|
||||
Assert.That(() => _postStorageContract.ResElement(post.PostId), Throws.Nothing);
|
||||
}
|
||||
|
||||
private Post InsertPostToDatabaseAndReturn(string id, string postName = "test", PostType postType = PostType.Manager, 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 };
|
||||
SquirrelDbContext.Posts.Add(post);
|
||||
SquirrelDbContext.SaveChanges();
|
||||
return post;
|
||||
}
|
||||
|
||||
private static void AssertElement(PostDataModel? actual, Post expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
@@ -294,14 +235,11 @@ internal class PostStorageContractTests : BaseStorageContractTest
|
||||
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.Manager, double salary = 10, bool isActual = false, DateTime? changeDate = null)
|
||||
=> new(postId, postName, postType, salary, isActual, changeDate ?? DateTime.UtcNow);
|
||||
|
||||
private Post? GetPostFromDatabaseByPostId(string id) => SquirrelDbContext.Posts.Where(x => x.PostId == id).OrderByDescending(x => x.ChangeDate).FirstOrDefault();
|
||||
private static PostDataModel CreateModel(string postId, string postName = "test", PostType postType = PostType.Manager, double salary = 10)
|
||||
=> new(postId, postName, postType, salary);
|
||||
|
||||
private static void AssertElement(Post? actual, PostDataModel expected)
|
||||
{
|
||||
@@ -312,7 +250,6 @@ internal class PostStorageContractTests : BaseStorageContractTest
|
||||
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));
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ using Microsoft.EntityFrameworkCore;
|
||||
using SquirrelContract.StoragesContracts;
|
||||
using SquirrelDatabase.Implementations;
|
||||
using SquirrelDatabase.Models;
|
||||
using SquirrelTests.Infrastructure;
|
||||
using SquirrelTests.StoragesContracts;
|
||||
|
||||
namespace SquirrelTests.StorageContracts;
|
||||
@@ -17,26 +18,26 @@ internal class SalaryStorageContractTests : BaseStorageContractTest
|
||||
public void SetUp()
|
||||
{
|
||||
_salaryStorageContract = new SalaryStorageContract(SquirrelDbContext);
|
||||
_employee = InsertEmployeeToDatabaseAndReturn();
|
||||
_employee = SquirrelDbContext.InsertEmployeeToDatabaseAndReturn();
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
SquirrelDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Salaries\" CASCADE;");
|
||||
SquirrelDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Employees\" CASCADE;");
|
||||
SquirrelDbContext.RemoveSalariesFromDatabase();
|
||||
SquirrelDbContext.RemoveEmployeesFromDatabase();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_WhenHaveRecords_Test()
|
||||
{
|
||||
var salary = InsertSalaryToDatabaseAndReturn(_employee.Id, employeeSalary: 100);
|
||||
InsertSalaryToDatabaseAndReturn(_employee.Id);
|
||||
InsertSalaryToDatabaseAndReturn(_employee.Id);
|
||||
var salary = SquirrelDbContext.InsertSalaryToDatabaseAndReturn(_employee.Id, employeeSalary: 100);
|
||||
SquirrelDbContext.InsertSalaryToDatabaseAndReturn(_employee.Id);
|
||||
SquirrelDbContext.InsertSalaryToDatabaseAndReturn(_employee.Id);
|
||||
var list = _salaryStorageContract.GetList(DateTime.UtcNow.AddDays(-10), DateTime.UtcNow.AddDays(10));
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(3));
|
||||
AssertElement(list.First(), salary);
|
||||
AssertElement(list.Single(x => x.Salary == salary.EmployeeSalary), salary);
|
||||
}
|
||||
|
||||
[Test]
|
||||
@@ -50,12 +51,12 @@ internal class SalaryStorageContractTests : BaseStorageContractTest
|
||||
[Test]
|
||||
public void Try_GetList_OnlyInDatePeriod_Test()
|
||||
{
|
||||
InsertSalaryToDatabaseAndReturn(_employee.Id, salaryDate: DateTime.UtcNow.AddDays(-2));
|
||||
InsertSalaryToDatabaseAndReturn(_employee.Id, salaryDate: DateTime.UtcNow.AddDays(-1).AddMinutes(-5));
|
||||
InsertSalaryToDatabaseAndReturn(_employee.Id, salaryDate: DateTime.UtcNow.AddDays(-1).AddMinutes(5));
|
||||
InsertSalaryToDatabaseAndReturn(_employee.Id, salaryDate: DateTime.UtcNow.AddDays(1).AddMinutes(-5));
|
||||
InsertSalaryToDatabaseAndReturn(_employee.Id, salaryDate: DateTime.UtcNow.AddDays(1).AddMinutes(5));
|
||||
InsertSalaryToDatabaseAndReturn(_employee.Id, salaryDate: DateTime.UtcNow.AddDays(-2));
|
||||
SquirrelDbContext.InsertSalaryToDatabaseAndReturn(_employee.Id, salaryDate: DateTime.UtcNow.AddDays(-2));
|
||||
SquirrelDbContext.InsertSalaryToDatabaseAndReturn(_employee.Id, salaryDate: DateTime.UtcNow.AddDays(-1).AddMinutes(-5));
|
||||
SquirrelDbContext.InsertSalaryToDatabaseAndReturn(_employee.Id, salaryDate: DateTime.UtcNow.AddDays(-1).AddMinutes(5));
|
||||
SquirrelDbContext.InsertSalaryToDatabaseAndReturn(_employee.Id, salaryDate: DateTime.UtcNow.AddDays(1).AddMinutes(-5));
|
||||
SquirrelDbContext.InsertSalaryToDatabaseAndReturn(_employee.Id, salaryDate: DateTime.UtcNow.AddDays(1).AddMinutes(5));
|
||||
SquirrelDbContext.InsertSalaryToDatabaseAndReturn(_employee.Id, salaryDate: DateTime.UtcNow.AddDays(-2));
|
||||
var list = _salaryStorageContract.GetList(DateTime.UtcNow.AddDays(-1), DateTime.UtcNow.AddDays(1));
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
@@ -67,10 +68,10 @@ internal class SalaryStorageContractTests : BaseStorageContractTest
|
||||
[Test]
|
||||
public void Try_GetList_ByEmployee_Test()
|
||||
{
|
||||
var employee = InsertEmployeeToDatabaseAndReturn("name 2");
|
||||
InsertSalaryToDatabaseAndReturn(_employee.Id);
|
||||
InsertSalaryToDatabaseAndReturn(_employee.Id);
|
||||
InsertSalaryToDatabaseAndReturn(employee.Id);
|
||||
var employee = SquirrelDbContext.InsertEmployeeToDatabaseAndReturn("name 2");
|
||||
SquirrelDbContext.InsertSalaryToDatabaseAndReturn(_employee.Id);
|
||||
SquirrelDbContext.InsertSalaryToDatabaseAndReturn(_employee.Id);
|
||||
SquirrelDbContext.InsertSalaryToDatabaseAndReturn(employee.Id);
|
||||
var list = _salaryStorageContract.GetList(DateTime.UtcNow.AddDays(-1), DateTime.UtcNow.AddDays(1), _employee.Id);
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
@@ -83,13 +84,13 @@ internal class SalaryStorageContractTests : BaseStorageContractTest
|
||||
[Test]
|
||||
public void Try_GetList_ByEmployeeOnlyInDatePeriod_Test()
|
||||
{
|
||||
var employee = InsertEmployeeToDatabaseAndReturn("name 2");
|
||||
InsertSalaryToDatabaseAndReturn(_employee.Id, salaryDate: DateTime.UtcNow.AddDays(-2));
|
||||
InsertSalaryToDatabaseAndReturn(_employee.Id, salaryDate: DateTime.UtcNow.AddDays(-1).AddMinutes(5));
|
||||
InsertSalaryToDatabaseAndReturn(employee.Id, salaryDate: DateTime.UtcNow.AddDays(-1).AddMinutes(5));
|
||||
InsertSalaryToDatabaseAndReturn(_employee.Id, salaryDate: DateTime.UtcNow.AddDays(1).AddMinutes(-5));
|
||||
InsertSalaryToDatabaseAndReturn(employee.Id, salaryDate: DateTime.UtcNow.AddDays(1).AddMinutes(-5));
|
||||
InsertSalaryToDatabaseAndReturn(_employee.Id, salaryDate: DateTime.UtcNow.AddDays(-2));
|
||||
var employee = SquirrelDbContext.InsertEmployeeToDatabaseAndReturn(fio: "name 2");
|
||||
SquirrelDbContext.InsertSalaryToDatabaseAndReturn(_employee.Id, salaryDate: DateTime.UtcNow.AddDays(-2));
|
||||
SquirrelDbContext.InsertSalaryToDatabaseAndReturn(_employee.Id, salaryDate: DateTime.UtcNow.AddDays(-1).AddMinutes(5));
|
||||
SquirrelDbContext.InsertSalaryToDatabaseAndReturn(employee.Id, salaryDate: DateTime.UtcNow.AddDays(-1).AddMinutes(5));
|
||||
SquirrelDbContext.InsertSalaryToDatabaseAndReturn(_employee.Id, salaryDate: DateTime.UtcNow.AddDays(1).AddMinutes(-5));
|
||||
SquirrelDbContext.InsertSalaryToDatabaseAndReturn(employee.Id, salaryDate: DateTime.UtcNow.AddDays(1).AddMinutes(-5));
|
||||
SquirrelDbContext.InsertSalaryToDatabaseAndReturn(_employee.Id, salaryDate: DateTime.UtcNow.AddDays(-2));
|
||||
var list = _salaryStorageContract.GetList(DateTime.UtcNow.AddDays(-1), DateTime.UtcNow.AddDays(1), _employee.Id);
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
@@ -104,23 +105,7 @@ internal class SalaryStorageContractTests : BaseStorageContractTest
|
||||
{
|
||||
var salary = CreateModel(_employee.Id);
|
||||
_salaryStorageContract.AddElement(salary);
|
||||
AssertElement(GetSalaryFromDatabaseByEmployeeId(_employee.Id), salary);
|
||||
}
|
||||
|
||||
private Employee InsertEmployeeToDatabaseAndReturn(string employeeFIO = "fio", string employeeEmail = "abc@mail.ru")
|
||||
{
|
||||
var employee = new Employee() { Id = Guid.NewGuid().ToString(), PostId = Guid.NewGuid().ToString(), FIO = employeeFIO, Email = employeeEmail, IsDeleted = false };
|
||||
SquirrelDbContext.Employees.Add(employee);
|
||||
SquirrelDbContext.SaveChanges();
|
||||
return employee;
|
||||
}
|
||||
|
||||
private Salary InsertSalaryToDatabaseAndReturn(string employeeId, double employeeSalary = 1, DateTime? salaryDate = null)
|
||||
{
|
||||
var salary = new Salary() { EmployeeId = employeeId, EmployeeSalary = employeeSalary, SalaryDate = salaryDate ?? DateTime.UtcNow };
|
||||
SquirrelDbContext.Salaries.Add(salary);
|
||||
SquirrelDbContext.SaveChanges();
|
||||
return salary;
|
||||
AssertElement(SquirrelDbContext.GetSalariesFromDatabaseByEmployeeId(_employee.Id).First(), salary);
|
||||
}
|
||||
|
||||
private static void AssertElement(SalaryDataModel? actual, Salary expected)
|
||||
@@ -136,8 +121,6 @@ internal class SalaryStorageContractTests : BaseStorageContractTest
|
||||
private static SalaryDataModel CreateModel(string employeeId, double employeeSalary = 1, DateTime? salaryDate = null)
|
||||
=> new(employeeId, salaryDate ?? DateTime.UtcNow, employeeSalary);
|
||||
|
||||
private Salary? GetSalaryFromDatabaseByEmployeeId(string id) => SquirrelDbContext.Salaries.FirstOrDefault(x => x.EmployeeId == id);
|
||||
|
||||
private static void AssertElement(Salary? actual, SalaryDataModel expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
|
||||
@@ -3,17 +3,15 @@ using SquirrelContract.Enums;
|
||||
using SquirrelContract.Exceptions;
|
||||
using SquirrelDatabase.Implementations;
|
||||
using SquirrelDatabase.Models;
|
||||
using static NUnit.Framework.Internal.OSPlatform;
|
||||
using System;
|
||||
using SquirrelTests.StoragesContracts;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using SquirrelTests.Infrastructure;
|
||||
|
||||
namespace SquirrelTests.StorageContracts;
|
||||
|
||||
[TestFixture]
|
||||
internal class SaleStorageContractTests : BaseStorageContractTest
|
||||
{
|
||||
private SaleStorageContract _saleStorageContract;
|
||||
private SaleStorageContract _saletStorageContract;
|
||||
private Client _client;
|
||||
private Employee _employee;
|
||||
private Cocktail _cocktail;
|
||||
@@ -21,28 +19,28 @@ internal class SaleStorageContractTests : BaseStorageContractTest
|
||||
[SetUp]
|
||||
public void SetUp()
|
||||
{
|
||||
_saleStorageContract = new SaleStorageContract(SquirrelDbContext);
|
||||
_client = InsertClientToDatabaseAndReturn();
|
||||
_employee = InsertEmployeeToDatabaseAndReturn();
|
||||
_cocktail = InsertCocktailToDatabaseAndReturn();
|
||||
_saletStorageContract = new SaleStorageContract(SquirrelDbContext);
|
||||
_client = SquirrelDbContext.InsertClientToDatabaseAndReturn();
|
||||
_employee = SquirrelDbContext.InsertEmployeeToDatabaseAndReturn();
|
||||
_cocktail = SquirrelDbContext.InsertCocktailToDatabaseAndReturn();
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
SquirrelDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Sales\" CASCADE;");
|
||||
SquirrelDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Clients\" CASCADE;");
|
||||
SquirrelDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Employees\" CASCADE;");
|
||||
SquirrelDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Cocktails\" CASCADE;");
|
||||
SquirrelDbContext.RemoveSalesFromDatabase();
|
||||
SquirrelDbContext.RemoveEmployeesFromDatabase();
|
||||
SquirrelDbContext.RemoveClientsFromDatabase();
|
||||
SquirrelDbContext.RemoveCocktailsFromDatabase();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_WhenHaveRecords_Test()
|
||||
{
|
||||
var sale = InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, cocktails: [(_cocktail.Id, 1)]);
|
||||
InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, cocktails: [(_cocktail.Id, 5)]);
|
||||
InsertSaleToDatabaseAndReturn(_employee.Id, null, cocktails: [(_cocktail.Id, 10)]);
|
||||
var list = _saleStorageContract.GetList();
|
||||
var sale = SquirrelDbContext.InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, cocktails: [(_cocktail.Id, 1, 1.2)]);
|
||||
SquirrelDbContext.InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, cocktails: [(_cocktail.Id, 5, 1.2)]);
|
||||
SquirrelDbContext.InsertSaleToDatabaseAndReturn(_employee.Id, null, cocktails: [(_cocktail.Id, 10, 1.2)]);
|
||||
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);
|
||||
@@ -51,7 +49,7 @@ internal class SaleStorageContractTests : BaseStorageContractTest
|
||||
[Test]
|
||||
public void Try_GetList_WhenNoRecords_Test()
|
||||
{
|
||||
var list = _saleStorageContract.GetList();
|
||||
var list = _saletStorageContract.GetList();
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Is.Empty);
|
||||
}
|
||||
@@ -59,11 +57,11 @@ internal class SaleStorageContractTests : BaseStorageContractTest
|
||||
[Test]
|
||||
public void Try_GetList_ByPeriod_Test()
|
||||
{
|
||||
InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(-3), cocktails: [(_cocktail.Id, 1)]);
|
||||
InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(3), cocktails: [(_cocktail.Id, 1)]);
|
||||
InsertSaleToDatabaseAndReturn(_employee.Id, null, saleDate: DateTime.UtcNow.AddDays(1).AddMinutes(-3), cocktails: [(_cocktail.Id, 1)]);
|
||||
InsertSaleToDatabaseAndReturn(_employee.Id, null, saleDate: DateTime.UtcNow.AddDays(1).AddMinutes(3), cocktails: [(_cocktail.Id, 1)]);
|
||||
var list = _saleStorageContract.GetList(startDate: DateTime.UtcNow.AddDays(-1), endDate: DateTime.UtcNow.AddDays(1));
|
||||
SquirrelDbContext.InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(-3), cocktails: [(_cocktail.Id, 1, 1.2)]);
|
||||
SquirrelDbContext.InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(3), cocktails: [(_cocktail.Id, 1, 1.2)]);
|
||||
SquirrelDbContext.InsertSaleToDatabaseAndReturn(_employee.Id, null, saleDate: DateTime.UtcNow.AddDays(1).AddMinutes(-3), cocktails: [(_cocktail.Id, 1, 1.2)]);
|
||||
SquirrelDbContext.InsertSaleToDatabaseAndReturn(_employee.Id, null, saleDate: DateTime.UtcNow.AddDays(1).AddMinutes(3), cocktails: [(_cocktail.Id, 1, 1.2)]);
|
||||
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));
|
||||
}
|
||||
@@ -71,11 +69,11 @@ internal class SaleStorageContractTests : BaseStorageContractTest
|
||||
[Test]
|
||||
public void Try_GetList_ByEmployeeId_Test()
|
||||
{
|
||||
var employee = InsertEmployeeToDatabaseAndReturn("Other employee");
|
||||
InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, cocktails: [(_cocktail.Id, 1)]);
|
||||
InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, cocktails: [(_cocktail.Id, 1)]);
|
||||
InsertSaleToDatabaseAndReturn(employee.Id, null, cocktails: [(_cocktail.Id, 1)]);
|
||||
var list = _saleStorageContract.GetList(employeeId: _employee.Id);
|
||||
var employee = SquirrelDbContext.InsertEmployeeToDatabaseAndReturn(fio: "Other employee");
|
||||
SquirrelDbContext.InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, cocktails: [(_cocktail.Id, 1, 1.2)]);
|
||||
SquirrelDbContext.InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, cocktails: [(_cocktail.Id, 1, 1.2)]);
|
||||
SquirrelDbContext.InsertSaleToDatabaseAndReturn(employee.Id, null, cocktails: [(_cocktail.Id, 1, 1.2)]);
|
||||
var list = _saletStorageContract.GetList(employeeId: _employee.Id);
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(2));
|
||||
Assert.That(list.All(x => x.EmployeeId == _employee.Id));
|
||||
@@ -84,12 +82,12 @@ internal class SaleStorageContractTests : BaseStorageContractTest
|
||||
[Test]
|
||||
public void Try_GetList_ByClientId_Test()
|
||||
{
|
||||
var client = InsertClientToDatabaseAndReturn("Other fio", "+8-888-888-88-88");
|
||||
InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, cocktails: [(_cocktail.Id, 1)]);
|
||||
InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, cocktails: [(_cocktail.Id, 1)]);
|
||||
InsertSaleToDatabaseAndReturn(_employee.Id, client.Id, cocktails: [(_cocktail.Id, 1)]);
|
||||
InsertSaleToDatabaseAndReturn(_employee.Id, null, cocktails: [(_cocktail.Id, 1)]);
|
||||
var list = _saleStorageContract.GetList(clientId: _client.Id);
|
||||
var client = SquirrelDbContext.InsertClientToDatabaseAndReturn(fio: "Other fio", phoneNumber: "+8-888-888-88-88");
|
||||
SquirrelDbContext.InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, cocktails: [(_cocktail.Id, 1, 1.2)]);
|
||||
SquirrelDbContext.InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, cocktails: [(_cocktail.Id, 1, 1.2)]);
|
||||
SquirrelDbContext.InsertSaleToDatabaseAndReturn(_employee.Id, client.Id, cocktails: [(_cocktail.Id, 1, 1.2)]);
|
||||
SquirrelDbContext.InsertSaleToDatabaseAndReturn(_employee.Id, null, cocktails: [(_cocktail.Id, 1, 1.2)]);
|
||||
var list = _saletStorageContract.GetList(clientId: _client.Id);
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(2));
|
||||
Assert.That(list.All(x => x.ClientId == _client.Id));
|
||||
@@ -98,31 +96,31 @@ internal class SaleStorageContractTests : BaseStorageContractTest
|
||||
[Test]
|
||||
public void Try_GetList_ByCocktailId_Test()
|
||||
{
|
||||
var cocktail = InsertCocktailToDatabaseAndReturn("Other name");
|
||||
InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, cocktails: [(_cocktail.Id, 5)]);
|
||||
InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, cocktails: [(_cocktail.Id, 1), (cocktail.Id, 4)]);
|
||||
InsertSaleToDatabaseAndReturn(_employee.Id, null, cocktails: [(cocktail.Id, 1)]);
|
||||
InsertSaleToDatabaseAndReturn(_employee.Id, null, cocktails: [(cocktail.Id, 1), (_cocktail.Id, 1)]);
|
||||
var list = _saleStorageContract.GetList(cocktailId: _cocktail.Id);
|
||||
var cocktail = SquirrelDbContext.InsertCocktailToDatabaseAndReturn(cocktailName: "Other name");
|
||||
SquirrelDbContext.InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, cocktails: [(_cocktail.Id, 5, 1.2)]);
|
||||
SquirrelDbContext.InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, cocktails: [(_cocktail.Id, 1, 1.2), (cocktail.Id, 4, 1.2)]);
|
||||
SquirrelDbContext.InsertSaleToDatabaseAndReturn(_employee.Id, null, cocktails: [(cocktail.Id, 1, 1.2)]);
|
||||
SquirrelDbContext.InsertSaleToDatabaseAndReturn(_employee.Id, null, cocktails: [(cocktail.Id, 1, 1.2), (_cocktail.Id, 1, 1.2)]);
|
||||
var list = _saletStorageContract.GetList(cocktailId: _cocktail.Id);
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(3));
|
||||
Assert.That(list.All(x => x.Cocktails.Any(y => y.CocktailId == _cocktail.Id)));
|
||||
Assert.That(list.All(x => x.Cocktails!.Any(y => y.CocktailId == _cocktail.Id)));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_ByAllParameters_Test()
|
||||
{
|
||||
var employee = InsertEmployeeToDatabaseAndReturn("Other employee");
|
||||
var client = InsertClientToDatabaseAndReturn("Other fio", "+8-888-888-88-88");
|
||||
var cocktail = InsertCocktailToDatabaseAndReturn("Other name");
|
||||
InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(-3), cocktails: [(_cocktail.Id, 1)]);
|
||||
InsertSaleToDatabaseAndReturn(employee.Id, null, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(3), cocktails: [(_cocktail.Id, 1)]);
|
||||
InsertSaleToDatabaseAndReturn(employee.Id, _client.Id, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(3), cocktails: [(_cocktail.Id, 1)]);
|
||||
InsertSaleToDatabaseAndReturn(employee.Id, _client.Id, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(3), cocktails: [(cocktail.Id, 1)]);
|
||||
InsertSaleToDatabaseAndReturn(_employee.Id, client.Id, saleDate: DateTime.UtcNow.AddDays(1).AddMinutes(-3), cocktails: [(_cocktail.Id, 1)]);
|
||||
InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, saleDate: DateTime.UtcNow.AddDays(1).AddMinutes(-3), cocktails: [(cocktail.Id, 1)]);
|
||||
InsertSaleToDatabaseAndReturn(employee.Id, null, saleDate: DateTime.UtcNow.AddDays(1).AddMinutes(-3), cocktails: [(_cocktail.Id, 1)]);
|
||||
var list = _saleStorageContract.GetList(startDate: DateTime.UtcNow.AddDays(-1), endDate: DateTime.UtcNow.AddDays(1), employeeId: _employee.Id, clientId: _client.Id, cocktailId: cocktail.Id);
|
||||
var employee = SquirrelDbContext.InsertEmployeeToDatabaseAndReturn(fio: "Other employee");
|
||||
var client = SquirrelDbContext.InsertClientToDatabaseAndReturn(fio: "Other fio", phoneNumber: "+8-888-888-88-88");
|
||||
var cocktail = SquirrelDbContext.InsertCocktailToDatabaseAndReturn(cocktailName: "Other name");
|
||||
SquirrelDbContext.InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(-3), cocktails: [(_cocktail.Id, 1, 1.2)]);
|
||||
SquirrelDbContext.InsertSaleToDatabaseAndReturn(employee.Id, null, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(3), cocktails: [(_cocktail.Id, 1, 1.2)]);
|
||||
SquirrelDbContext.InsertSaleToDatabaseAndReturn(employee.Id, _client.Id, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(3), cocktails: [(_cocktail.Id, 1, 1.2)]);
|
||||
SquirrelDbContext.InsertSaleToDatabaseAndReturn(employee.Id, _client.Id, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(3), cocktails: [(cocktail.Id, 1, 1.2)]);
|
||||
SquirrelDbContext.InsertSaleToDatabaseAndReturn(_employee.Id, client.Id, saleDate: DateTime.UtcNow.AddDays(1).AddMinutes(-3), cocktails: [(_cocktail.Id, 1, 1.2)]);
|
||||
SquirrelDbContext.InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, saleDate: DateTime.UtcNow.AddDays(1).AddMinutes(-3), cocktails: [(cocktail.Id, 1, 1.2)]);
|
||||
SquirrelDbContext.InsertSaleToDatabaseAndReturn(employee.Id, null, saleDate: DateTime.UtcNow.AddDays(1).AddMinutes(-3), cocktails: [(_cocktail.Id, 1, 1.2)]);
|
||||
var list = _saletStorageContract.GetList(startDate: DateTime.UtcNow.AddDays(-1), endDate: DateTime.UtcNow.AddDays(1), employeeId: _employee.Id, clientId: _client.Id, cocktailId: cocktail.Id);
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(1));
|
||||
}
|
||||
@@ -130,46 +128,46 @@ internal class SaleStorageContractTests : BaseStorageContractTest
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenHaveRecord_Test()
|
||||
{
|
||||
var sale = InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, cocktails: [(_cocktail.Id, 1)]);
|
||||
AssertElement(_saleStorageContract.GetElementById(sale.Id), sale);
|
||||
var sale = SquirrelDbContext.InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, cocktails: [(_cocktail.Id, 1, 1.2)]);
|
||||
AssertElement(_saletStorageContract.GetElementById(sale.Id), sale);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenNoRecord_Test()
|
||||
{
|
||||
InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, cocktails: [(_cocktail.Id, 1)]);
|
||||
Assert.That(() => _saleStorageContract.GetElementById(Guid.NewGuid().ToString()), Is.Null);
|
||||
SquirrelDbContext.InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, cocktails: [(_cocktail.Id, 1, 1.2)]);
|
||||
Assert.That(() => _saletStorageContract.GetElementById(Guid.NewGuid().ToString()), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenRecordHasCanceled_Test()
|
||||
{
|
||||
var sale = InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, cocktails: [(_cocktail.Id, 1)], isCancel: true);
|
||||
AssertElement(_saleStorageContract.GetElementById(sale.Id), sale);
|
||||
var sale = SquirrelDbContext.InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, cocktails: [(_cocktail.Id, 1, 1.2)], isCancel: true);
|
||||
AssertElement(_saletStorageContract.GetElementById(sale.Id), sale);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_Test()
|
||||
{
|
||||
var sale = CreateModel(Guid.NewGuid().ToString(), _employee.Id, _client.Id, 1, DiscountType.RegularCustomer, 1, false, [_cocktail.Id]);
|
||||
_saleStorageContract.AddElement(sale);
|
||||
AssertElement(GetSaleFromDatabaseById(sale.Id), sale);
|
||||
var sale = CreateModel(Guid.NewGuid().ToString(), _employee.Id, _client.Id, DiscountType.RegularCustomer, false, [_cocktail.Id]);
|
||||
_saletStorageContract.AddElement(sale);
|
||||
AssertElement(SquirrelDbContext.GetSaleFromDatabaseById(sale.Id), sale);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_WhenIsDeletedIsTrue_Test()
|
||||
{
|
||||
var sale = CreateModel(Guid.NewGuid().ToString(), _employee.Id, _client.Id, 1, DiscountType.RegularCustomer, 1, true, [_cocktail.Id]);
|
||||
Assert.That(() => _saleStorageContract.AddElement(sale), Throws.Nothing);
|
||||
AssertElement(GetSaleFromDatabaseById(sale.Id), CreateModel(sale.Id, _employee.Id, _client.Id, 1, DiscountType.RegularCustomer, 1, false, [_cocktail.Id]));
|
||||
var sale = CreateModel(Guid.NewGuid().ToString(), _employee.Id, _client.Id, DiscountType.RegularCustomer, true, [_cocktail.Id]);
|
||||
Assert.That(() => _saletStorageContract.AddElement(sale), Throws.Nothing);
|
||||
AssertElement(SquirrelDbContext.GetSaleFromDatabaseById(sale.Id), CreateModel(sale.Id, _employee.Id, _client.Id, DiscountType.RegularCustomer, false, [_cocktail.Id]));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_DelElement_Test()
|
||||
{
|
||||
var sale = InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, cocktails: [(_cocktail.Id, 1)], isCancel: false);
|
||||
_saleStorageContract.DelElement(sale.Id);
|
||||
var element = GetSaleFromDatabaseById(sale.Id);
|
||||
var sale = SquirrelDbContext.InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, cocktails: [(_cocktail.Id, 1, 1.2)], isCancel: false);
|
||||
_saletStorageContract.DelElement(sale.Id);
|
||||
var element = SquirrelDbContext.GetSaleFromDatabaseById(sale.Id);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(element, Is.Not.Null);
|
||||
@@ -180,53 +178,14 @@ internal class SaleStorageContractTests : BaseStorageContractTest
|
||||
[Test]
|
||||
public void Try_DelElement_WhenNoRecordWithThisId_Test()
|
||||
{
|
||||
Assert.That(() => _saleStorageContract.DelElement(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
|
||||
Assert.That(() => _saletStorageContract.DelElement(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_DelElement_WhenRecordWasCanceled_Test()
|
||||
{
|
||||
var sale = InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, cocktails: [(_cocktail.Id, 1)], isCancel: true);
|
||||
Assert.That(() => _saleStorageContract.DelElement(sale.Id), Throws.TypeOf<ElementDeletedException>());
|
||||
}
|
||||
|
||||
private Client InsertClientToDatabaseAndReturn(string fio = "test", string phoneNumber = "+7-777-777-77-77")
|
||||
{
|
||||
var client = new Client() { Id = Guid.NewGuid().ToString(), FIO = fio, PhoneNumber = phoneNumber, DiscountSize = 10 };
|
||||
SquirrelDbContext.Clients.Add(client);
|
||||
SquirrelDbContext.SaveChanges();
|
||||
return client;
|
||||
}
|
||||
|
||||
private Employee InsertEmployeeToDatabaseAndReturn(string fio = "test", string employeeEmail = "abc@gmail.com")
|
||||
{
|
||||
var employee = new Employee() { Id = Guid.NewGuid().ToString(), FIO = fio, Email = employeeEmail, PostId = Guid.NewGuid().ToString() };
|
||||
SquirrelDbContext.Employees.Add(employee);
|
||||
SquirrelDbContext.SaveChanges();
|
||||
return employee;
|
||||
}
|
||||
|
||||
private Cocktail InsertCocktailToDatabaseAndReturn(string cocktailName = "test", AlcoholType baseAlcohol = AlcoholType.Whiskey, double price = 1)
|
||||
{
|
||||
var cocktail = new Cocktail() { Id = Guid.NewGuid().ToString(), CocktailName = cocktailName, BaseAlcohol = baseAlcohol, Price = price };
|
||||
SquirrelDbContext.Cocktails.Add(cocktail);
|
||||
SquirrelDbContext.SaveChanges();
|
||||
return cocktail;
|
||||
}
|
||||
|
||||
private Sale InsertSaleToDatabaseAndReturn(string employeeId, string? clientId, DateTime? saleDate = null, double sum = 1, DiscountType discountType = DiscountType.OnSale, double discount = 0, bool isCancel = false, List<(string, int)>? cocktails = null)
|
||||
{
|
||||
var sale = new Sale() { EmployeeId = employeeId, ClientId = clientId, SaleDate = saleDate ?? DateTime.UtcNow, Sum = sum, DiscountType = discountType, Discount = discount, IsCancel = isCancel, SaleCocktails = [] };
|
||||
if (cocktails is not null)
|
||||
{
|
||||
foreach (var elem in cocktails)
|
||||
{
|
||||
sale.SaleCocktails.Add(new SaleCocktail { CocktailId = elem.Item1, SaleId = sale.Id, Count = elem.Item2 });
|
||||
}
|
||||
}
|
||||
SquirrelDbContext.Sales.Add(sale);
|
||||
SquirrelDbContext.SaveChanges();
|
||||
return sale;
|
||||
var sale = SquirrelDbContext.InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, cocktails: [(_cocktail.Id, 1, 1.2)], isCancel: true);
|
||||
Assert.That(() => _saletStorageContract.DelElement(sale.Id), Throws.TypeOf<ElementDeletedException>());
|
||||
}
|
||||
|
||||
private static void AssertElement(SaleDataModel? actual, Sale expected)
|
||||
@@ -261,14 +220,12 @@ internal class SaleStorageContractTests : BaseStorageContractTest
|
||||
}
|
||||
}
|
||||
|
||||
private static SaleDataModel CreateModel(string id, string employeeId, string? clientId, double sum, DiscountType discountType, double discount, bool isCancel, List<string> cocktailIds)
|
||||
private static SaleDataModel CreateModel(string id, string employeeId, string? clientId, DiscountType discountType, bool isCancel, List<string> cocktailIds)
|
||||
{
|
||||
var cocktails = cocktailIds.Select(x => new SaleCocktailDataModel(id, x, 1)).ToList();
|
||||
return new(id, employeeId, clientId, sum, discountType, discount, isCancel, cocktails);
|
||||
var cocktails = cocktailIds.Select(x => new SaleCocktailDataModel(id, x, 1, 1.1)).ToList();
|
||||
return new(id, employeeId, clientId, discountType, isCancel, cocktails);
|
||||
}
|
||||
|
||||
private Sale? GetSaleFromDatabaseById(string id) => SquirrelDbContext.Sales.Include(x => x.SaleCocktails).FirstOrDefault(x => x.Id == id);
|
||||
|
||||
private static void AssertElement(Sale? actual, SaleDataModel expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
@@ -292,6 +249,7 @@ internal class SaleStorageContractTests : BaseStorageContractTest
|
||||
{
|
||||
Assert.That(actual.SaleCocktails[i].CocktailId, Is.EqualTo(expected.Cocktails[i].CocktailId));
|
||||
Assert.That(actual.SaleCocktails[i].Count, Is.EqualTo(expected.Cocktails[i].Count));
|
||||
Assert.That(actual.SaleCocktails[i].Price, Is.EqualTo(expected.Cocktails[i].Price));
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
using SquirrelDatabase;
|
||||
using SquirrelTests.Infrastructure;
|
||||
using Microsoft.AspNetCore.Mvc.Testing;
|
||||
using Microsoft.AspNetCore.TestHost;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Serilog;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace SquirrelTests.WebApiControllersTests;
|
||||
|
||||
internal class BaseWebApiControllerTest
|
||||
{
|
||||
private WebApplicationFactory<Program> _webApplication;
|
||||
|
||||
protected HttpClient HttpClient { get; private set; }
|
||||
|
||||
protected SquirrelDbContext SquirrelDbContext { get; private set; }
|
||||
|
||||
protected static readonly JsonSerializerOptions JsonSerializerOptions = new() { PropertyNameCaseInsensitive = true };
|
||||
|
||||
[OneTimeSetUp]
|
||||
public void OneTimeSetUp()
|
||||
{
|
||||
_webApplication = new CustomWebApplicationFactory<Program>();
|
||||
HttpClient = _webApplication
|
||||
.WithWebHostBuilder(builder =>
|
||||
{
|
||||
builder.ConfigureTestServices(services =>
|
||||
{
|
||||
using var loggerFactory = new LoggerFactory();
|
||||
loggerFactory.AddSerilog(new LoggerConfiguration()
|
||||
.ReadFrom.Configuration(new ConfigurationBuilder()
|
||||
.SetBasePath(Directory.GetCurrentDirectory())
|
||||
.AddJsonFile("appsettings.json")
|
||||
.Build())
|
||||
.CreateLogger());
|
||||
services.AddSingleton(loggerFactory);
|
||||
});
|
||||
})
|
||||
.CreateClient();
|
||||
|
||||
var request = HttpClient.GetAsync("/login/user").GetAwaiter().GetResult();
|
||||
var data = request.Content.ReadAsStringAsync().GetAwaiter().GetResult();
|
||||
HttpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {data}");
|
||||
|
||||
SquirrelDbContext = _webApplication.Services.GetRequiredService<SquirrelDbContext>();
|
||||
SquirrelDbContext.Database.EnsureDeleted();
|
||||
SquirrelDbContext.Database.EnsureCreated();
|
||||
}
|
||||
|
||||
[OneTimeTearDown]
|
||||
public void OneTimeTearDown()
|
||||
{
|
||||
SquirrelDbContext?.Database.EnsureDeleted();
|
||||
SquirrelDbContext?.Dispose();
|
||||
HttpClient?.Dispose();
|
||||
_webApplication?.Dispose();
|
||||
}
|
||||
|
||||
protected static async Task<T?> GetModelFromResponseAsync<T>(HttpResponseMessage response) =>
|
||||
JsonSerializer.Deserialize<T>(await response.Content.ReadAsStringAsync(), JsonSerializerOptions);
|
||||
|
||||
protected static StringContent MakeContent(object model) =>
|
||||
new(JsonSerializer.Serialize(model), Encoding.UTF8, "application/json");
|
||||
}
|
||||
@@ -0,0 +1,371 @@
|
||||
using System.Net;
|
||||
using System;
|
||||
using SquirrelContract.ViewModels;
|
||||
using SquirrelTests.Infrastructure;
|
||||
using SquirrelDatabase.Models;
|
||||
using SquirrelContract.BindingModels;
|
||||
|
||||
namespace SquirrelTests.WebApiControllersTests;
|
||||
|
||||
[TestFixture]
|
||||
internal class ClientControllerTests : BaseWebApiControllerTest
|
||||
{
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
SquirrelDbContext.RemoveSalesFromDatabase();
|
||||
SquirrelDbContext.RemoveEmployeesFromDatabase();
|
||||
SquirrelDbContext.RemoveClientsFromDatabase();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_WhenHaveRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var client = SquirrelDbContext.InsertClientToDatabaseAndReturn(phoneNumber: "+5-555-555-55-55");
|
||||
SquirrelDbContext.InsertClientToDatabaseAndReturn(phoneNumber: "+6-666-666-66-66");
|
||||
SquirrelDbContext.InsertClientToDatabaseAndReturn(phoneNumber: "+7-777-777-77-77");
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync("/api/clients");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<ClientViewModel>>(response);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(3));
|
||||
});
|
||||
AssertElement(data.First(x => x.Id == client.Id), client);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_WhenNoRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync("/api/clients");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<ClientViewModel>>(response);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(0));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ById_WhenHaveRecord_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var client = SquirrelDbContext.InsertClientToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/clients/{client.Id}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
AssertElement(await GetModelFromResponseAsync<ClientViewModel>(response), client);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ById_WhenNoRecord_ShouldNotFound_Test()
|
||||
{
|
||||
//Arrange
|
||||
SquirrelDbContext.InsertClientToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/clients/{Guid.NewGuid()}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ByFIO_WhenHaveRecord_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var client = SquirrelDbContext.InsertClientToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/clients/{client.FIO}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
AssertElement(await GetModelFromResponseAsync<ClientViewModel>(response), client);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ByFIO_WhenNoRecord_ShouldNotFound_Test()
|
||||
{
|
||||
//Arrange
|
||||
SquirrelDbContext.InsertClientToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/clients/New%20Fio");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ByPhoneNumber_WhenHaveRecord_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var client = SquirrelDbContext.InsertClientToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/clients/{client.PhoneNumber}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
AssertElement(await GetModelFromResponseAsync<ClientViewModel>(response), client);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ByPhoneNumber_WhenNoRecord_ShouldNotFound_Test()
|
||||
{
|
||||
//Arrange
|
||||
SquirrelDbContext.InsertClientToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/clients/+8-888-888-88-88");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
SquirrelDbContext.InsertClientToDatabaseAndReturn();
|
||||
var clientModel = CreateBindingModel();
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/clients", MakeContent(clientModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
AssertElement(SquirrelDbContext.GetClientFromDatabase(clientModel.Id!), clientModel);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenHaveRecordWithSameId_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var clientModel = CreateBindingModel();
|
||||
SquirrelDbContext.InsertClientToDatabaseAndReturn(clientModel.Id);
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/clients", MakeContent(clientModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenHaveRecordWithSamePhoneNumber_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var clientModel = CreateBindingModel();
|
||||
SquirrelDbContext.InsertClientToDatabaseAndReturn(phoneNumber: clientModel.PhoneNumber!);
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/clients", MakeContent(clientModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenDataIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var clientModelWithIdIncorrect = new ClientBindingModel { Id = "Id", FIO = "fio", PhoneNumber = "+7-111-111-11-11", DiscountSize = 10 };
|
||||
var clientModelWithFioIncorrect = new ClientBindingModel { Id = Guid.NewGuid().ToString(), FIO = string.Empty, PhoneNumber = "+7-111-111-11-11", DiscountSize = 10 };
|
||||
var clientModelWithPhoneNumberIncorrect = new ClientBindingModel { Id = Guid.NewGuid().ToString(), FIO = "fio", PhoneNumber = "71", DiscountSize = 10 };
|
||||
//Act
|
||||
var responseWithIdIncorrect = await HttpClient.PostAsync($"/api/clients", MakeContent(clientModelWithIdIncorrect));
|
||||
var responseWithFioIncorrect = await HttpClient.PostAsync($"/api/clients", MakeContent(clientModelWithFioIncorrect));
|
||||
var responseWithPhoneNumberIncorrect = await HttpClient.PostAsync($"/api/clients", MakeContent(clientModelWithPhoneNumberIncorrect));
|
||||
//Assert
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(responseWithIdIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Id is incorrect");
|
||||
Assert.That(responseWithFioIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Fio is incorrect");
|
||||
Assert.That(responseWithPhoneNumberIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "PhoneNumber is incorrect");
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenSendEmptyData_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/clients", MakeContent(string.Empty));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenSendWrongFormatData_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/clients", MakeContent(new { Data = "test", Position = 10 }));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var clientModel = CreateBindingModel(fio: "new fio");
|
||||
SquirrelDbContext.InsertClientToDatabaseAndReturn(clientModel.Id);
|
||||
//Act
|
||||
var response = await HttpClient.PutAsync($"/api/clients", MakeContent(clientModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
SquirrelDbContext.ChangeTracker.Clear();
|
||||
AssertElement(SquirrelDbContext.GetClientFromDatabase(clientModel.Id!), clientModel);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WhenNoFoundRecord_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var clientModel = CreateBindingModel(fio: "new fio");
|
||||
SquirrelDbContext.InsertClientToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.PutAsync($"/api/clients", MakeContent(clientModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WhenHaveRecordWithSamePhoneNumber_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var clientModel = CreateBindingModel(fio: "new fio");
|
||||
SquirrelDbContext.InsertClientToDatabaseAndReturn(clientModel.Id);
|
||||
SquirrelDbContext.InsertClientToDatabaseAndReturn(phoneNumber: clientModel.PhoneNumber!);
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/clients", MakeContent(clientModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WhenDataIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var clientModelWithIdIncorrect = new ClientBindingModel { Id = "Id", FIO = "fio", PhoneNumber = "+7-111-111-11-11", DiscountSize = 10 };
|
||||
var clientModelWithFioIncorrect = new ClientBindingModel { Id = Guid.NewGuid().ToString(), FIO = string.Empty, PhoneNumber = "+7-111-111-11-11", DiscountSize = 10 };
|
||||
var clientModelWithPhoneNumberIncorrect = new ClientBindingModel { Id = Guid.NewGuid().ToString(), FIO = "fio", PhoneNumber = "71", DiscountSize = 10 };
|
||||
//Act
|
||||
var responseWithIdIncorrect = await HttpClient.PutAsync($"/api/clients", MakeContent(clientModelWithIdIncorrect));
|
||||
var responseWithFioIncorrect = await HttpClient.PutAsync($"/api/clients", MakeContent(clientModelWithFioIncorrect));
|
||||
var responseWithPhoneNumberIncorrect = await HttpClient.PutAsync($"/api/clients", MakeContent(clientModelWithPhoneNumberIncorrect));
|
||||
//Assert
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(responseWithIdIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Id is incorrect");
|
||||
Assert.That(responseWithFioIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Fio is incorrect");
|
||||
Assert.That(responseWithPhoneNumberIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "PhoneNumber is incorrect");
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WhenSendEmptyData_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.PutAsync($"/api/clients", MakeContent(string.Empty));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WhenSendWrongFormatData_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.PutAsync($"/api/clients", MakeContent(new { Data = "test", Position = 10 }));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Delete_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var clientId = Guid.NewGuid().ToString();
|
||||
SquirrelDbContext.InsertClientToDatabaseAndReturn(clientId);
|
||||
//Act
|
||||
var response = await HttpClient.DeleteAsync($"/api/clients/{clientId}");
|
||||
//Assert
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
Assert.That(SquirrelDbContext.GetClientFromDatabase(clientId), Is.Null);
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Delete_WhenHaveSalesByThisClient_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var client = SquirrelDbContext.InsertClientToDatabaseAndReturn();
|
||||
var employee = SquirrelDbContext.InsertEmployeeToDatabaseAndReturn();
|
||||
SquirrelDbContext.InsertSaleToDatabaseAndReturn(employee.Id, client.Id);
|
||||
SquirrelDbContext.InsertSaleToDatabaseAndReturn(employee.Id, client.Id);
|
||||
var salesBeforeDelete = SquirrelDbContext.GetSalesByClientId(client.Id);
|
||||
//Act
|
||||
var response = await HttpClient.DeleteAsync($"/api/clients/{client.Id}");
|
||||
//Assert
|
||||
SquirrelDbContext.ChangeTracker.Clear();
|
||||
var element = SquirrelDbContext.GetClientFromDatabase(client.Id);
|
||||
var salesAfterDelete = SquirrelDbContext.GetSalesByClientId(client.Id);
|
||||
var salesNoClients = SquirrelDbContext.GetSalesByClientId(null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
Assert.That(element, Is.Null);
|
||||
Assert.That(salesBeforeDelete, Has.Length.EqualTo(2));
|
||||
Assert.That(salesAfterDelete, Is.Empty);
|
||||
Assert.That(salesNoClients, Has.Length.EqualTo(2));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Delete_WhenNoFoundRecord_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
SquirrelDbContext.InsertClientToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.DeleteAsync($"/api/clients/{Guid.NewGuid()}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Delete_WhenSendWrongFormatData_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.DeleteAsync($"/api/clients/id");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
private static void AssertElement(ClientViewModel? actual, Client expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.Id, Is.EqualTo(expected.Id));
|
||||
Assert.That(actual.FIO, Is.EqualTo(expected.FIO));
|
||||
Assert.That(actual.PhoneNumber, Is.EqualTo(expected.PhoneNumber));
|
||||
Assert.That(actual.DiscountSize, Is.EqualTo(expected.DiscountSize));
|
||||
});
|
||||
}
|
||||
|
||||
private static ClientBindingModel CreateBindingModel(string? id = null, string fio = "fio", string phoneNumber = "+7-666-666-66-66", double discountSize = 10) =>
|
||||
new()
|
||||
{
|
||||
Id = id ?? Guid.NewGuid().ToString(),
|
||||
FIO = fio,
|
||||
PhoneNumber = phoneNumber,
|
||||
DiscountSize = discountSize
|
||||
};
|
||||
|
||||
private static void AssertElement(Client? actual, ClientBindingModel expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.Id, Is.EqualTo(expected.Id));
|
||||
Assert.That(actual.FIO, Is.EqualTo(expected.FIO));
|
||||
Assert.That(actual.PhoneNumber, Is.EqualTo(expected.PhoneNumber));
|
||||
Assert.That(actual.DiscountSize, Is.EqualTo(expected.DiscountSize));
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,384 @@
|
||||
using static NUnit.Framework.Internal.OSPlatform;
|
||||
using System.Net;
|
||||
using SquirrelTests.Infrastructure;
|
||||
using SquirrelContract.ViewModels;
|
||||
using SquirrelContract.BindingModels;
|
||||
using SquirrelDatabase.Models;
|
||||
using SquirrelContract.Enums;
|
||||
|
||||
namespace SquirrelTests.WebApiControllersTests;
|
||||
|
||||
[TestFixture]
|
||||
internal class CocktailControllerTests : BaseWebApiControllerTest
|
||||
{
|
||||
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
SquirrelDbContext.RemoveCocktailsFromDatabase();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_WhenHaveRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var cocktail = SquirrelDbContext.InsertCocktailToDatabaseAndReturn(cocktailName: "name 1");
|
||||
SquirrelDbContext.InsertCocktailToDatabaseAndReturn(cocktailName: "name 2");
|
||||
SquirrelDbContext.InsertCocktailToDatabaseAndReturn(cocktailName: "name 3");
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync("/api/cocktails/getrecords");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<CocktailViewModel>>(response);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(3));
|
||||
});
|
||||
AssertElement(data.First(x => x.Id == cocktail.Id), cocktail);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_WhenNoRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync("/api/cocktails/getrecords");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<CocktailViewModel>>(response);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(0));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetHistoryByCocktailId_WhenHaveRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var cocktail = SquirrelDbContext.InsertCocktailToDatabaseAndReturn();
|
||||
SquirrelDbContext.InsertCocktailHistoryToDatabaseAndReturn(cocktail.Id, 20, DateTime.UtcNow.AddDays(-1));
|
||||
SquirrelDbContext.InsertCocktailHistoryToDatabaseAndReturn(cocktail.Id, 30, DateTime.UtcNow.AddMinutes(-10));
|
||||
var history = SquirrelDbContext.InsertCocktailHistoryToDatabaseAndReturn(cocktail.Id, 40, DateTime.UtcNow.AddDays(1));
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/cocktails/gethistory?id={cocktail.Id}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<CocktailHistoryViewModel>>(response);
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(3));
|
||||
AssertElement(data[0], history);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetHistoryByCocktailId_WhenNoRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var cocktail = SquirrelDbContext.InsertCocktailToDatabaseAndReturn();
|
||||
SquirrelDbContext.InsertCocktailHistoryToDatabaseAndReturn(cocktail.Id, 20, DateTime.UtcNow.AddDays(-1));
|
||||
SquirrelDbContext.InsertCocktailHistoryToDatabaseAndReturn(cocktail.Id, 30, DateTime.UtcNow.AddMinutes(-10));
|
||||
SquirrelDbContext.InsertCocktailHistoryToDatabaseAndReturn(cocktail.Id, 40, DateTime.UtcNow.AddDays(1));
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/cocktails/gethistory?id={Guid.NewGuid()}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<CocktailViewModel>>(response);
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(0));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetHistoryByCocktailId_WhenCocktailIdIsNotGuid_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/cocktails/gethistory?id=id");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ById_WhenHaveRecord_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var cocktail = SquirrelDbContext.InsertCocktailToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/cocktails/getrecord/{cocktail.Id}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
AssertElement(await GetModelFromResponseAsync<CocktailViewModel>(response), cocktail);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ById_WhenNoRecord_ShouldNotFound_Test()
|
||||
{
|
||||
//Arrange
|
||||
SquirrelDbContext.InsertCocktailToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/cocktails/getrecord/{Guid.NewGuid()}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ByName_WhenHaveRecord_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var cocktail = SquirrelDbContext.InsertCocktailToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/cocktails/getrecord/{cocktail.CocktailName}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
AssertElement(await GetModelFromResponseAsync<CocktailViewModel>(response), cocktail);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ByName_WhenNoRecord_ShouldNotFound_Test()
|
||||
{
|
||||
//Arrange
|
||||
SquirrelDbContext.InsertCocktailToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/cocktails/getrecord/New%20Name");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
|
||||
}
|
||||
|
||||
|
||||
[Test]
|
||||
public async Task Post_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
SquirrelDbContext.InsertCocktailToDatabaseAndReturn();
|
||||
var cocktailModel = CreateModel();
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/cocktails/register", MakeContent(cocktailModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
AssertElement(SquirrelDbContext.GetCocktailFromDatabaseById(cocktailModel.Id!), cocktailModel);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenHaveRecordWithSameId_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var cocktailModel = CreateModel();
|
||||
SquirrelDbContext.InsertCocktailToDatabaseAndReturn(cocktailModel.Id);
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/cocktails/register", MakeContent(cocktailModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenHaveRecordWithSameName_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var cocktailModel = CreateModel(cocktailName: "unique name");
|
||||
SquirrelDbContext.InsertCocktailToDatabaseAndReturn(cocktailName: cocktailModel.CocktailName!);
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/cocktails/register", MakeContent(cocktailModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenDataIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var cocktailModelWithIdIncorrect = new CocktailBindingModel { Id = "Id", CocktailName = "name", Price = 100, BaseAlcohol = AlcoholType.Vodka.ToString() };
|
||||
var cocktailModelWithNameIncorrect = new CocktailBindingModel { Id = Guid.NewGuid().ToString(), CocktailName = string.Empty, Price = 100, BaseAlcohol = AlcoholType.Vodka.ToString() };
|
||||
var cocktailModelWithBaseAlcoholIncorrect = new CocktailBindingModel { Id = Guid.NewGuid().ToString(), CocktailName = "name", Price = 100, BaseAlcohol = string.Empty };
|
||||
var cocktailModelWithPriceIncorrect = new CocktailBindingModel { Id = Guid.NewGuid().ToString(), CocktailName = "name", Price = 0, BaseAlcohol = AlcoholType.Vodka.ToString() };
|
||||
//Act
|
||||
var responseWithIdIncorrect = await HttpClient.PostAsync($"/api/cocktails/register", MakeContent(cocktailModelWithIdIncorrect));
|
||||
var responseWithNameIncorrect = await HttpClient.PostAsync($"/api/cocktails/register", MakeContent(cocktailModelWithNameIncorrect));
|
||||
var responseWithBaseAlcoholIncorrect = await HttpClient.PostAsync($"/api/cocktails/register", MakeContent(cocktailModelWithBaseAlcoholIncorrect));
|
||||
var responseWithPriceIncorrect = await HttpClient.PostAsync($"/api/cocktails/register", MakeContent(cocktailModelWithPriceIncorrect));
|
||||
//Assert
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(responseWithIdIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Id is incorrect");
|
||||
Assert.That(responseWithNameIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Name is incorrect");
|
||||
Assert.That(responseWithBaseAlcoholIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Name is incorrect");
|
||||
Assert.That(responseWithPriceIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Name is incorrect");
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenSendEmptyData_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/cocktails/register", MakeContent(string.Empty));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenSendWrongFormatData_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/cocktails/register", MakeContent(new { Data = "test", Position = 10 }));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var cocktailModel = CreateModel();
|
||||
SquirrelDbContext.InsertCocktailToDatabaseAndReturn(cocktailModel.Id);
|
||||
//Act
|
||||
var response = await HttpClient.PutAsync($"/api/cocktails/changeinfo", MakeContent(cocktailModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
SquirrelDbContext.ChangeTracker.Clear();
|
||||
AssertElement(SquirrelDbContext.GetCocktailFromDatabaseById(cocktailModel.Id!), cocktailModel);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WhenNoFoundRecord_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var cocktailModel = CreateModel();
|
||||
SquirrelDbContext.InsertCocktailToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.PutAsync($"/api/cocktails/changeinfo", MakeContent(cocktailModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WhenHaveRecordWithSameName_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var cocktailModel = CreateModel(cocktailName: "unique name");
|
||||
SquirrelDbContext.InsertCocktailToDatabaseAndReturn(cocktailModel.Id);
|
||||
SquirrelDbContext.InsertCocktailToDatabaseAndReturn(cocktailName: cocktailModel.CocktailName!);
|
||||
//Act
|
||||
var response = await HttpClient.PutAsync($"/api/cocktails/changeinfo", MakeContent(cocktailModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WhenDataIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var cocktailModelWithIdIncorrect = new CocktailBindingModel { Id = "Id", CocktailName = "name", Price = 100, BaseAlcohol = AlcoholType.Vodka.ToString() };
|
||||
var cocktailModelWithNameIncorrect = new CocktailBindingModel { Id = Guid.NewGuid().ToString(), CocktailName = string.Empty, Price = 100, BaseAlcohol = AlcoholType.Vodka.ToString() };
|
||||
var cocktailModelWithBaseAlcoholIncorrect = new CocktailBindingModel { Id = Guid.NewGuid().ToString(), CocktailName = "name", Price = 100, BaseAlcohol = string.Empty };
|
||||
var cocktailModelWithPriceIncorrect = new CocktailBindingModel { Id = Guid.NewGuid().ToString(), CocktailName = "name", Price = 0, BaseAlcohol = AlcoholType.Vodka.ToString() };
|
||||
//Act
|
||||
var responseWithIdIncorrect = await HttpClient.PutAsync($"/api/cocktails/changeinfo", MakeContent(cocktailModelWithIdIncorrect));
|
||||
var responseWithNameIncorrect = await HttpClient.PutAsync($"/api/cocktails/changeinfo", MakeContent(cocktailModelWithNameIncorrect));
|
||||
var responseWithBaseAlcoholIncorrect = await HttpClient.PutAsync($"/api/cocktails/changeinfo", MakeContent(cocktailModelWithBaseAlcoholIncorrect));
|
||||
var responseWithPriceIncorrect = await HttpClient.PutAsync($"/api/cocktails/changeinfo", MakeContent(cocktailModelWithPriceIncorrect));
|
||||
//Assert
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(responseWithIdIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Id is incorrect");
|
||||
Assert.That(responseWithNameIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Name is incorrect");
|
||||
Assert.That(responseWithBaseAlcoholIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Name is incorrect");
|
||||
Assert.That(responseWithPriceIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Name is incorrect");
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WhenSendEmptyData_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.PutAsync($"/api/cocktails/changeinfo", MakeContent(string.Empty));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WhenSendWrongFormatData_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.PutAsync($"/api/cocktails/changeinfo", MakeContent(new { Data = "test", Position = 10 }));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Delete_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var cocktailId = Guid.NewGuid().ToString();
|
||||
SquirrelDbContext.InsertCocktailToDatabaseAndReturn(cocktailId);
|
||||
//Act
|
||||
var response = await HttpClient.DeleteAsync($"/api/cocktails/delete/{cocktailId}");
|
||||
SquirrelDbContext.ChangeTracker.Clear();
|
||||
//Assert
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Delete_WhenNoFoundRecord_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
SquirrelDbContext.InsertCocktailToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.DeleteAsync($"/api/cocktails/delete/{Guid.NewGuid()}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Delete_WhenSendWrongFormatData_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.DeleteAsync($"/api/cocktails/delete/id");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
private static void AssertElement(CocktailViewModel? actual, Cocktail expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.Id, Is.EqualTo(expected.Id));
|
||||
Assert.That(actual.CocktailName, Is.EqualTo(expected.CocktailName));
|
||||
Assert.That(actual.BaseAlcohol, Is.EqualTo(expected.BaseAlcohol.ToString()));
|
||||
Assert.That(actual.Price, Is.EqualTo(expected.Price));
|
||||
});
|
||||
}
|
||||
|
||||
private static void AssertElement(CocktailHistoryViewModel? actual, CocktailHistory expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.CocktailName, Is.EqualTo(expected.Cocktail!.CocktailName));
|
||||
Assert.That(actual.OldPrice, Is.EqualTo(expected.OldPrice));
|
||||
Assert.That(actual.ChangeDate.ToString(), Is.EqualTo(expected.ChangeDate.ToString()));
|
||||
});
|
||||
}
|
||||
|
||||
private static CocktailBindingModel CreateModel(string? id = null, string cocktailName = "name", AlcoholType cocktailType = AlcoholType.Vodka, double price = 1)
|
||||
=> new()
|
||||
{
|
||||
Id = id ?? Guid.NewGuid().ToString(),
|
||||
CocktailName = cocktailName,
|
||||
BaseAlcohol = cocktailType.ToString(),
|
||||
Price = price
|
||||
};
|
||||
|
||||
private static void AssertElement(Cocktail? actual, CocktailBindingModel expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.Id, Is.EqualTo(expected.Id));
|
||||
Assert.That(actual.CocktailName, Is.EqualTo(expected.CocktailName));
|
||||
Assert.That(actual.BaseAlcohol.ToString(), Is.EqualTo(expected.BaseAlcohol));
|
||||
Assert.That(actual.Price, Is.EqualTo(expected.Price));
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,551 @@
|
||||
using SquirrelContract.BindingModels;
|
||||
using SquirrelContract.ViewModels;
|
||||
using SquirrelDatabase.Models;
|
||||
using SquirrelTests.Infrastructure;
|
||||
using System.Net;
|
||||
|
||||
namespace SquirrelTests.WebApiControllersTests;
|
||||
|
||||
[TestFixture]
|
||||
internal class EmployeeControllerTests : BaseWebApiControllerTest
|
||||
{
|
||||
private Post _post;
|
||||
|
||||
[SetUp]
|
||||
public void SetUp()
|
||||
{
|
||||
_post = SquirrelDbContext.InsertPostToDatabaseAndReturn();
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
SquirrelDbContext.RemovePostsFromDatabase();
|
||||
SquirrelDbContext.RemoveEmployeesFromDatabase();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_WhenHaveRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var employee = SquirrelDbContext.InsertEmployeeToDatabaseAndReturn(fio: "fio 1", postId: _post.PostId)
|
||||
.AddPost(_post);
|
||||
SquirrelDbContext.InsertEmployeeToDatabaseAndReturn(fio: "fio 2", postId: _post.PostId);
|
||||
SquirrelDbContext.InsertEmployeeToDatabaseAndReturn(fio: "fio 3", postId: _post.PostId);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync("/api/employees/getrecords");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<EmployeeViewModel>>(response);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(3));
|
||||
});
|
||||
AssertElement(data.First(x => x.Id == employee.Id), employee);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_WhenNoRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync("/api/employees/getrecords");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<EmployeeViewModel>>(response);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(0));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_OnlyActual_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
SquirrelDbContext.InsertEmployeeToDatabaseAndReturn(fio: "fio 1", postId: _post.PostId, isDeleted: true);
|
||||
SquirrelDbContext.InsertEmployeeToDatabaseAndReturn(fio: "fio 2", postId: _post.PostId, isDeleted: false);
|
||||
SquirrelDbContext.InsertEmployeeToDatabaseAndReturn(fio: "fio 3", postId: _post.PostId, isDeleted: false);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync("/api/employees/getrecords?includeDeleted=false");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<EmployeeViewModel>>(response);
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Has.Count.EqualTo(2));
|
||||
Assert.That(data.All(x => !x.IsDeleted));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_IncludeNoActual_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
SquirrelDbContext.InsertEmployeeToDatabaseAndReturn(fio: "fio 1", postId: _post.PostId, isDeleted: true);
|
||||
SquirrelDbContext.InsertEmployeeToDatabaseAndReturn(fio: "fio 2", postId: _post.PostId, isDeleted: true);
|
||||
SquirrelDbContext.InsertEmployeeToDatabaseAndReturn(fio: "fio 3", postId: _post.PostId, isDeleted: false);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync("/api/employees/getrecords?includeDeleted=true");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<EmployeeViewModel>>(response);
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Has.Count.EqualTo(3));
|
||||
Assert.That(data.Any(x => x.IsDeleted));
|
||||
Assert.That(data.Any(x => !x.IsDeleted));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_ByPostId_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
SquirrelDbContext.InsertEmployeeToDatabaseAndReturn(fio: "fio 1", postId: _post.PostId);
|
||||
SquirrelDbContext.InsertEmployeeToDatabaseAndReturn(fio: "fio 2", postId: _post.PostId);
|
||||
SquirrelDbContext.InsertEmployeeToDatabaseAndReturn(fio: "fio 3", postId: _post.PostId, isDeleted: true);
|
||||
SquirrelDbContext.InsertEmployeeToDatabaseAndReturn(fio: "fio 4");
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/employees/getpostrecords?id={_post.PostId}&includeDeleted=true");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<EmployeeViewModel>>(response);
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Has.Count.EqualTo(3));
|
||||
Assert.That(data.All(x => x.PostId == _post.PostId));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_ByPostId_WhenNoRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
SquirrelDbContext.InsertEmployeeToDatabaseAndReturn(fio: "fio 1", postId: _post.PostId);
|
||||
SquirrelDbContext.InsertEmployeeToDatabaseAndReturn(fio: "fio 4");
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/employees/getpostrecords?id={Guid.NewGuid()}&includeDeleted=true");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<EmployeeViewModel>>(response);
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(0));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_ByPostId_WhenIdIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/employees/getpostrecords?id=id&includeDeleted=true");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_ByBirthDate_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
SquirrelDbContext.InsertEmployeeToDatabaseAndReturn(fio: "fio 1", birthDate: DateTime.UtcNow.AddYears(-25));
|
||||
SquirrelDbContext.InsertEmployeeToDatabaseAndReturn(fio: "fio 2", birthDate: DateTime.UtcNow.AddYears(-21));
|
||||
SquirrelDbContext.InsertEmployeeToDatabaseAndReturn(fio: "fio 3", birthDate: DateTime.UtcNow.AddYears(-20), isDeleted: true);
|
||||
SquirrelDbContext.InsertEmployeeToDatabaseAndReturn(fio: "fio 4", birthDate: DateTime.UtcNow.AddYears(-19));
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/employees/getbirthdaterecords?fromDate={DateTime.UtcNow.AddYears(-21).AddMinutes(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddYears(-20).AddMinutes(1):MM/dd/yyyy HH:mm:ss}&includeDeleted=true");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<EmployeeViewModel>>(response);
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Has.Count.EqualTo(2));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_ByBirthDate_WhenDateIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/employees/getbirthdaterecords?fromDate={DateTime.UtcNow.AddMinutes(1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddMinutes(-1):MM/dd/yyyy HH:mm:ss}&includeDeleted=true");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_ByEmploymentDate_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
SquirrelDbContext.InsertEmployeeToDatabaseAndReturn(fio: "fio 1", employmentDate: DateTime.UtcNow.AddDays(-2));
|
||||
SquirrelDbContext.InsertEmployeeToDatabaseAndReturn(fio: "fio 2", employmentDate: DateTime.UtcNow.AddDays(-1));
|
||||
SquirrelDbContext.InsertEmployeeToDatabaseAndReturn(fio: "fio 3", employmentDate: DateTime.UtcNow.AddDays(1), isDeleted: true);
|
||||
SquirrelDbContext.InsertEmployeeToDatabaseAndReturn(fio: "fio 4", employmentDate: DateTime.UtcNow.AddDays(2));
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/employees/getemploymentrecords?fromDate={DateTime.UtcNow.AddDays(-1).AddMinutes(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1).AddMinutes(1):MM/dd/yyyy HH:mm:ss}&includeDeleted=true");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<EmployeeViewModel>>(response);
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Has.Count.EqualTo(2));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_ByEmploymentDate_WhenDateIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/employees/getemploymentrecords?fromDate={DateTime.UtcNow.AddMinutes(1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddMinutes(-1):MM/dd/yyyy HH:mm:ss}&includeDeleted=true");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ById_WhenHaveRecord_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var employee = SquirrelDbContext.InsertEmployeeToDatabaseAndReturn(postId: _post.PostId).AddPost(_post);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/employees/getrecord/{employee.Id}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
AssertElement(await GetModelFromResponseAsync<EmployeeViewModel>(response), employee);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ById_WhenNoRecord_ShouldNotFound_Test()
|
||||
{
|
||||
//Arrange
|
||||
SquirrelDbContext.InsertEmployeeToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/employees/getrecord/{Guid.NewGuid()}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ById_WhenRecordWasDeleted_ShouldNotFound_Test()
|
||||
{
|
||||
//Arrange
|
||||
var employee = SquirrelDbContext.InsertEmployeeToDatabaseAndReturn(postId: _post.PostId, isDeleted: true);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/employees/getrecord/{employee.Id}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ByFIO_WhenHaveRecord_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var employee = SquirrelDbContext.InsertEmployeeToDatabaseAndReturn(postId: _post.PostId).AddPost(_post);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/employees/getrecord/{employee.FIO}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
AssertElement(await GetModelFromResponseAsync<EmployeeViewModel>(response), employee);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ByFIO_WhenNoRecord_ShouldNotFound_Test()
|
||||
{
|
||||
//Arrange
|
||||
SquirrelDbContext.InsertEmployeeToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/employees/getrecord/New%20Fio");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ByFIO_WhenRecordWasDeleted_ShouldNotFound_Test()
|
||||
{
|
||||
//Arrange
|
||||
var employee = SquirrelDbContext.InsertEmployeeToDatabaseAndReturn(postId: _post.PostId, isDeleted: true);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/employees/getrecord/{employee.FIO}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ByEmail_WhenHaveRecord_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var employee = SquirrelDbContext.InsertEmployeeToDatabaseAndReturn(postId: _post.PostId).AddPost(_post);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/employees/getrecord/{employee.Email}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
AssertElement(await GetModelFromResponseAsync<EmployeeViewModel>(response), employee);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ByEmail_WhenNoRecord_ShouldNotFound_Test()
|
||||
{
|
||||
//Arrange
|
||||
SquirrelDbContext.InsertEmployeeToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/employees/getrecord/New%20Email");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ByEmail_WhenRecordWasDeleted_ShouldNotFound_Test()
|
||||
{
|
||||
//Arrange
|
||||
var employee = SquirrelDbContext.InsertEmployeeToDatabaseAndReturn(postId: _post.PostId, isDeleted: true);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/employees/getrecord/{employee.Email}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
SquirrelDbContext.InsertEmployeeToDatabaseAndReturn();
|
||||
var employeeModel = CreateModel(_post.Id);
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/employees/register", MakeContent(employeeModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
AssertElement(SquirrelDbContext.GetEmployeeFromDatabaseById(employeeModel.Id!), employeeModel);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenHaveRecordWithSameId_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var employeeModel = CreateModel(_post.Id);
|
||||
SquirrelDbContext.InsertEmployeeToDatabaseAndReturn(employeeModel.Id);
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/employees/register", MakeContent(employeeModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenDataIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var employeeModelWithIdIncorrect = new EmployeeBindingModel { Id = "Id", FIO = "fio", BirthDate = DateTime.UtcNow.AddYears(-22), EmploymentDate = DateTime.UtcNow.AddDays(-5), PostId = _post.Id };
|
||||
var employeeModelWithFioIncorrect = new EmployeeBindingModel { Id = Guid.NewGuid().ToString(), FIO = string.Empty, BirthDate = DateTime.UtcNow.AddYears(-22), EmploymentDate = DateTime.UtcNow.AddDays(-5), PostId = _post.Id };
|
||||
var employeeModelWithEmailIncorrect = new EmployeeBindingModel { Id = Guid.NewGuid().ToString(), FIO = "fio", Email = "abc", BirthDate = DateTime.UtcNow.AddYears(-22), EmploymentDate = DateTime.UtcNow.AddDays(-5), PostId = _post.Id };
|
||||
var employeeModelWithPostIdIncorrect = new EmployeeBindingModel { Id = Guid.NewGuid().ToString(), FIO = "fio", BirthDate = DateTime.UtcNow.AddYears(-22), EmploymentDate = DateTime.UtcNow.AddDays(-5), PostId = "Id" };
|
||||
var employeeModelWithBirthDateIncorrect = new EmployeeBindingModel { Id = Guid.NewGuid().ToString(), FIO = "fio", BirthDate = DateTime.UtcNow.AddYears(-15), EmploymentDate = DateTime.UtcNow.AddDays(-5), PostId = _post.Id };
|
||||
//Act
|
||||
var responseWithIdIncorrect = await HttpClient.PostAsync($"/api/employees/register", MakeContent(employeeModelWithIdIncorrect));
|
||||
var responseWithFioIncorrect = await HttpClient.PostAsync($"/api/employees/register", MakeContent(employeeModelWithFioIncorrect));
|
||||
var responseWithEmailIncorrect = await HttpClient.PostAsync($"/api/employees/register", MakeContent(employeeModelWithEmailIncorrect));
|
||||
var responseWithPostIdIncorrect = await HttpClient.PostAsync($"/api/employees/register", MakeContent(employeeModelWithPostIdIncorrect));
|
||||
var responseWithBirthDateIncorrect = await HttpClient.PostAsync($"/api/employees/register", MakeContent(employeeModelWithBirthDateIncorrect));
|
||||
//Assert
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(responseWithIdIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Id is incorrect");
|
||||
Assert.That(responseWithFioIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Fio is incorrect");
|
||||
Assert.That(responseWithEmailIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Email is incorrect");
|
||||
Assert.That(responseWithPostIdIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "PostId is incorrect");
|
||||
Assert.That(responseWithBirthDateIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "BirthDate is incorrect");
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenSendEmptyData_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/employees/register", MakeContent(string.Empty));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenSendWrongFormatData_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/employees/register", MakeContent(new { Data = "test", Position = 10 }));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var employeeModel = CreateModel(_post.Id);
|
||||
SquirrelDbContext.InsertEmployeeToDatabaseAndReturn(employeeModel.Id);
|
||||
//Act
|
||||
var response = await HttpClient.PutAsync($"/api/employees/changeinfo", MakeContent(employeeModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
SquirrelDbContext.ChangeTracker.Clear();
|
||||
AssertElement(SquirrelDbContext.GetEmployeeFromDatabaseById(employeeModel.Id!), employeeModel);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WhenNoFoundRecord_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var employeeModel = CreateModel(_post.Id, fio: "new fio");
|
||||
SquirrelDbContext.InsertEmployeeToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.PutAsync($"/api/employees/changeinfo", MakeContent(employeeModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WhenRecordWasDeleted_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var employeeModel = CreateModel(_post.Id, fio: "new fio");
|
||||
SquirrelDbContext.InsertEmployeeToDatabaseAndReturn(employeeModel.Id, isDeleted: true);
|
||||
//Act
|
||||
var response = await HttpClient.PutAsync($"/api/employees/changeinfo", MakeContent(employeeModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WhenDataIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var employeeModelWithIdIncorrect = new EmployeeBindingModel { Id = "Id", FIO = "fio", Email = "abc@mail.ru", BirthDate = DateTime.UtcNow.AddYears(-22), EmploymentDate = DateTime.UtcNow.AddDays(-5), PostId = _post.Id };
|
||||
var employeeModelWithFioIncorrect = new EmployeeBindingModel { Id = Guid.NewGuid().ToString(), FIO = string.Empty, Email = "abc@mail.ru", BirthDate = DateTime.UtcNow.AddYears(-22), EmploymentDate = DateTime.UtcNow.AddDays(-5), PostId = _post.Id };
|
||||
var employeeModelWithEmailIncorrect = new EmployeeBindingModel { Id = Guid.NewGuid().ToString(), FIO = "fio", Email = "abc", BirthDate = DateTime.UtcNow.AddYears(-22), EmploymentDate = DateTime.UtcNow.AddDays(-5), PostId = _post.Id };
|
||||
var employeeModelWithPostIdIncorrect = new EmployeeBindingModel { Id = Guid.NewGuid().ToString(), FIO = "fio", Email = "abc@mail.ru", BirthDate = DateTime.UtcNow.AddYears(-22), EmploymentDate = DateTime.UtcNow.AddDays(-5), PostId = "Id" };
|
||||
var employeeModelWithBirthDateIncorrect = new EmployeeBindingModel { Id = Guid.NewGuid().ToString(), FIO = "fio", Email = "abc@mail.ru", BirthDate = DateTime.UtcNow.AddYears(-15), EmploymentDate = DateTime.UtcNow.AddDays(-5), PostId = _post.Id };
|
||||
//Act
|
||||
var responseWithIdIncorrect = await HttpClient.PutAsync($"/api/employees/changeinfo", MakeContent(employeeModelWithIdIncorrect));
|
||||
var responseWithFioIncorrect = await HttpClient.PutAsync($"/api/employees/changeinfo", MakeContent(employeeModelWithFioIncorrect));
|
||||
var responseWithEmailIncorrect = await HttpClient.PutAsync($"/api/employees/changeinfo", MakeContent(employeeModelWithEmailIncorrect));
|
||||
var responseWithPostIdIncorrect = await HttpClient.PutAsync($"/api/employees/changeinfo", MakeContent(employeeModelWithPostIdIncorrect));
|
||||
var responseWithBirthDateIncorrect = await HttpClient.PutAsync($"/api/employees/changeinfo", MakeContent(employeeModelWithBirthDateIncorrect));
|
||||
//Assert
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(responseWithIdIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Id is incorrect");
|
||||
Assert.That(responseWithFioIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Fio is incorrect");
|
||||
Assert.That(responseWithEmailIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Email is incorrect");
|
||||
Assert.That(responseWithPostIdIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "PostId is incorrect");
|
||||
Assert.That(responseWithBirthDateIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "BirthDate is incorrect");
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WhenSendEmptyData_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.PutAsync($"/api/employees/changeinfo", MakeContent(string.Empty));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WhenSendWrongFormatData_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.PutAsync($"/api/employees/changeinfo", MakeContent(new { Data = "test", Position = 10 }));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Delete_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var employeeId = Guid.NewGuid().ToString();
|
||||
SquirrelDbContext.InsertEmployeeToDatabaseAndReturn(employeeId);
|
||||
//Act
|
||||
var response = await HttpClient.DeleteAsync($"/api/employees/delete/{employeeId}");
|
||||
SquirrelDbContext.ChangeTracker.Clear();
|
||||
//Assert
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
Assert.That(SquirrelDbContext.GetEmployeeFromDatabaseById(employeeId)!.IsDeleted);
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Delete_WhenNoFoundRecord_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
SquirrelDbContext.InsertEmployeeToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.DeleteAsync($"/api/employees/delete/{Guid.NewGuid()}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Delete_WhenSendWrongFormatData_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.DeleteAsync($"/api/employees/delete/id");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Delete_WhenRecordWasDeleted_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var employeeId = SquirrelDbContext.InsertEmployeeToDatabaseAndReturn(isDeleted: true).Id;
|
||||
//Act
|
||||
var response = await HttpClient.DeleteAsync($"/api/employees/delete/{employeeId}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
private static void AssertElement(EmployeeViewModel? actual, Employee expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.Id, Is.EqualTo(expected.Id));
|
||||
Assert.That(actual.PostId, Is.EqualTo(expected.PostId));
|
||||
Assert.That(actual.PostName, Is.EqualTo(expected.Post!.PostName));
|
||||
Assert.That(actual.FIO, Is.EqualTo(expected.FIO));
|
||||
Assert.That(actual.Email, Is.EqualTo(expected.Email));
|
||||
Assert.That(actual.BirthDate.ToString(), Is.EqualTo(expected.BirthDate.ToString()));
|
||||
Assert.That(actual.EmploymentDate.ToString(), Is.EqualTo(expected.EmploymentDate.ToString()));
|
||||
Assert.That(actual.IsDeleted, Is.EqualTo(expected.IsDeleted));
|
||||
});
|
||||
}
|
||||
|
||||
private static EmployeeBindingModel CreateModel(string postId, string? id = null, string fio = "fio", string email = "abc@gmail.com", DateTime? birthDate = null, DateTime? employmentDate = null)
|
||||
{
|
||||
return new()
|
||||
{
|
||||
Id = id ?? Guid.NewGuid().ToString(),
|
||||
FIO = fio,
|
||||
Email = email,
|
||||
BirthDate = birthDate ?? DateTime.UtcNow.AddYears(-22),
|
||||
EmploymentDate = employmentDate ?? DateTime.UtcNow.AddDays(-5),
|
||||
PostId = postId
|
||||
};
|
||||
}
|
||||
|
||||
private static void AssertElement(Employee? actual, EmployeeBindingModel expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.Id, Is.EqualTo(expected.Id));
|
||||
Assert.That(actual.PostId, Is.EqualTo(expected.PostId));
|
||||
Assert.That(actual.FIO, Is.EqualTo(expected.FIO));
|
||||
Assert.That(actual.Email, Is.EqualTo(expected.Email));
|
||||
Assert.That(actual.BirthDate.ToString(), Is.EqualTo(expected.BirthDate.ToString()));
|
||||
Assert.That(actual.EmploymentDate.ToString(), Is.EqualTo(expected.EmploymentDate.ToString()));
|
||||
Assert.That(!actual.IsDeleted);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,455 @@
|
||||
using SquirrelContract.BindingModels;
|
||||
using SquirrelContract.Enums;
|
||||
using SquirrelContract.ViewModels;
|
||||
using SquirrelDatabase.Models;
|
||||
using SquirrelTests.Infrastructure;
|
||||
using System.Net;
|
||||
|
||||
namespace SquirrelTests.WebApiControllersTests;
|
||||
|
||||
[TestFixture]
|
||||
internal class PostControllerTests : BaseWebApiControllerTest
|
||||
{
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
SquirrelDbContext.RemovePostsFromDatabase();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetRecords_WhenHaveRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var post = SquirrelDbContext.InsertPostToDatabaseAndReturn(postName: "name 1");
|
||||
SquirrelDbContext.InsertPostToDatabaseAndReturn(postName: "name 2");
|
||||
SquirrelDbContext.InsertPostToDatabaseAndReturn(postName: "name 3");
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync("/api/posts");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<PostViewModel>>(response);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(3));
|
||||
});
|
||||
AssertElement(data.First(x => x.Id == post.PostId), post);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetHistory_WhenHaveRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var postId = Guid.NewGuid().ToString();
|
||||
SquirrelDbContext.InsertPostToDatabaseAndReturn(postName: "name 1", isActual: true);
|
||||
var post = SquirrelDbContext.InsertPostToDatabaseAndReturn(postId, "name 2", isActual: true);
|
||||
SquirrelDbContext.InsertPostToDatabaseAndReturn(postId, "name 2", isActual: false);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/posthistory/{postId}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<PostViewModel>>(response);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(2));
|
||||
});
|
||||
AssertElement(data.First(x => x.Id == post.PostId), post);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetHistory_WhenNoRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var postId = Guid.NewGuid().ToString();
|
||||
SquirrelDbContext.InsertPostToDatabaseAndReturn(postName: "name 1", isActual: true);
|
||||
SquirrelDbContext.InsertPostToDatabaseAndReturn(postId, "name 2", isActual: true);
|
||||
SquirrelDbContext.InsertPostToDatabaseAndReturn(postId, "name 2", isActual: false);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/posthistory/{Guid.NewGuid()}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<PostViewModel>>(response);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(0));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetHistory_WhenWrongData_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/posthistory/id");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ById_WhenHaveRecord_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var post = SquirrelDbContext.InsertPostToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/posts/{post.PostId}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
AssertElement(await GetModelFromResponseAsync<PostViewModel>(response), post);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ById_WhenNoRecord_ShouldNotFound_Test()
|
||||
{
|
||||
//Arrange
|
||||
SquirrelDbContext.InsertPostToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/posts/{Guid.NewGuid()}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ById_WhenRecordWasDeleted_ShouldNotFound_Test()
|
||||
{
|
||||
//Arrange
|
||||
var post = SquirrelDbContext.InsertPostToDatabaseAndReturn(isActual: false);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/posts/{post.PostId}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ByName_WhenHaveRecord_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var post = SquirrelDbContext.InsertPostToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/posts/{post.PostName}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
AssertElement(await GetModelFromResponseAsync<PostViewModel>(response), post);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ByName_WhenNoRecord_ShouldNotFound_Test()
|
||||
{
|
||||
//Arrange
|
||||
SquirrelDbContext.InsertPostToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/posts/New%20Name");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ByName_WhenRecordWasDeleted_ShouldNotFound_Test()
|
||||
{
|
||||
//Arrange
|
||||
var post = SquirrelDbContext.InsertPostToDatabaseAndReturn(isActual: false);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/posts/{post.PostName}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
SquirrelDbContext.InsertPostToDatabaseAndReturn();
|
||||
var postModel = CreateModel();
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/posts", MakeContent(postModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
AssertElement(SquirrelDbContext.GetPostFromDatabaseByPostId(postModel.Id!), postModel);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenHaveRecordWithSameId_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var postModel = CreateModel();
|
||||
SquirrelDbContext.InsertPostToDatabaseAndReturn(postModel.Id);
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/posts", MakeContent(postModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenHaveRecordWithSameName_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var postModel = CreateModel(postName: "unique name");
|
||||
SquirrelDbContext.InsertPostToDatabaseAndReturn(postName: postModel.PostName!);
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/posts", MakeContent(postModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenDataIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var postModelWithIdIncorrect = new PostBindingModel { Id = "Id", PostName = "name", PostType = PostType.Manager.ToString(), Salary = 10 };
|
||||
var postModelWithNameIncorrect = new PostBindingModel { Id = Guid.NewGuid().ToString(), PostName = string.Empty, PostType = PostType.Manager.ToString(), Salary = 10 };
|
||||
var postModelWithPostTypeIncorrect = new PostBindingModel { Id = Guid.NewGuid().ToString(), PostName = string.Empty, PostType = string.Empty, Salary = 10 };
|
||||
var postModelWithSalaryIncorrect = new PostBindingModel { Id = Guid.NewGuid().ToString(), PostName = string.Empty, PostType = PostType.Manager.ToString(), Salary = -10 };
|
||||
//Act
|
||||
var responseWithIdIncorrect = await HttpClient.PostAsync($"/api/posts", MakeContent(postModelWithIdIncorrect));
|
||||
var responseWithNameIncorrect = await HttpClient.PostAsync($"/api/posts", MakeContent(postModelWithNameIncorrect));
|
||||
var responseWithPostTypeIncorrect = await HttpClient.PostAsync($"/api/posts", MakeContent(postModelWithPostTypeIncorrect));
|
||||
var responseWithSalaryIncorrect = await HttpClient.PostAsync($"/api/posts", MakeContent(postModelWithSalaryIncorrect));
|
||||
//Assert
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(responseWithIdIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Id is incorrect");
|
||||
Assert.That(responseWithNameIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Name is incorrect");
|
||||
Assert.That(responseWithPostTypeIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Type is incorrect");
|
||||
Assert.That(responseWithSalaryIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Salary is incorrect");
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenSendEmptyData_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/posts", MakeContent(string.Empty));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenSendWrongFormatData_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/posts", MakeContent(new { Data = "test", Position = 10 }));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var postModel = CreateModel();
|
||||
SquirrelDbContext.InsertPostToDatabaseAndReturn(postModel.Id);
|
||||
//Act
|
||||
var response = await HttpClient.PutAsync($"/api/posts", MakeContent(postModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
SquirrelDbContext.ChangeTracker.Clear();
|
||||
AssertElement(SquirrelDbContext.GetPostFromDatabaseByPostId(postModel.Id!), postModel);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WhenNoFoundRecord_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var postModel = CreateModel();
|
||||
SquirrelDbContext.InsertPostToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.PutAsync($"/api/posts", MakeContent(postModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WhenRecordWasDeleted_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var postModel = CreateModel();
|
||||
SquirrelDbContext.InsertPostToDatabaseAndReturn(postModel.Id, isActual: false);
|
||||
//Act
|
||||
var response = await HttpClient.PutAsync($"/api/posts", MakeContent(postModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WhenHaveRecordWithSameName_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var postModel = CreateModel(postName: "unique name");
|
||||
SquirrelDbContext.InsertPostToDatabaseAndReturn(postModel.Id);
|
||||
SquirrelDbContext.InsertPostToDatabaseAndReturn(postName: postModel.PostName!);
|
||||
//Act
|
||||
var response = await HttpClient.PutAsync($"/api/posts", MakeContent(postModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WhenDataIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var postModelWithIdIncorrect = new PostBindingModel { Id = "Id", PostName = "name", PostType = PostType.Manager.ToString(), Salary = 10 };
|
||||
var postModelWithNameIncorrect = new PostBindingModel { Id = Guid.NewGuid().ToString(), PostName = string.Empty, PostType = PostType.Manager.ToString(), Salary = 10 };
|
||||
var postModelWithPostTypeIncorrect = new PostBindingModel { Id = Guid.NewGuid().ToString(), PostName = string.Empty, PostType = string.Empty, Salary = 10 };
|
||||
var postModelWithSalaryIncorrect = new PostBindingModel { Id = Guid.NewGuid().ToString(), PostName = string.Empty, PostType = PostType.Manager.ToString(), Salary = -10 };
|
||||
//Act
|
||||
var responseWithIdIncorrect = await HttpClient.PutAsync($"/api/posts", MakeContent(postModelWithIdIncorrect));
|
||||
var responseWithNameIncorrect = await HttpClient.PutAsync($"/api/posts", MakeContent(postModelWithNameIncorrect));
|
||||
var responseWithPostTypeIncorrect = await HttpClient.PutAsync($"/api/posts", MakeContent(postModelWithPostTypeIncorrect));
|
||||
var responseWithSalaryIncorrect = await HttpClient.PutAsync($"/api/posts", MakeContent(postModelWithSalaryIncorrect));
|
||||
//Assert
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(responseWithIdIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Id is incorrect");
|
||||
Assert.That(responseWithNameIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Name is incorrect");
|
||||
Assert.That(responseWithPostTypeIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Type is incorrect");
|
||||
Assert.That(responseWithSalaryIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Salary is incorrect");
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WhenSendEmptyData_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.PutAsync($"/api/posts", MakeContent(string.Empty));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WhenSendWrongFormatData_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.PutAsync($"/api/posts", MakeContent(new { Data = "test", Position = 10 }));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Delete_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var postId = SquirrelDbContext.InsertPostToDatabaseAndReturn().PostId;
|
||||
//Act
|
||||
var response = await HttpClient.DeleteAsync($"/api/posts/{postId}");
|
||||
//Assert
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
Assert.That(SquirrelDbContext.GetPostFromDatabaseByPostId(postId), Is.Null);
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Delete_WhenNoFoundRecord_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
SquirrelDbContext.InsertPostToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.DeleteAsync($"/api/posts/{Guid.NewGuid()}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Delete_WhenRecordWasDeleted_Test()
|
||||
{
|
||||
//Arrange
|
||||
var postId = SquirrelDbContext.InsertPostToDatabaseAndReturn(isActual: false).PostId;
|
||||
//Act
|
||||
var response = await HttpClient.DeleteAsync($"/api/posts/{postId}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Delete_WhenSendWrongFormatData_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.DeleteAsync($"/api/posts/id");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Patch_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var postId = SquirrelDbContext.InsertPostToDatabaseAndReturn(isActual: false).PostId;
|
||||
//Act
|
||||
var response = await HttpClient.PatchAsync($"/api/posts/{postId}", null);
|
||||
//Assert
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
Assert.That(SquirrelDbContext.GetPostFromDatabaseByPostId(postId), Is.Not.Null);
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Patch_WhenNoFoundRecord_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
SquirrelDbContext.InsertPostToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.PatchAsync($"/api/posts/{Guid.NewGuid()}", null);
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Patch_WhenRecordNotWasDeleted_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var postId = SquirrelDbContext.InsertPostToDatabaseAndReturn().PostId;
|
||||
//Act
|
||||
var response = await HttpClient.PatchAsync($"/api/posts/{postId}", null);
|
||||
//Assert
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
Assert.That(SquirrelDbContext.GetPostFromDatabaseByPostId(postId), Is.Not.Null);
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Patch_WhenSendWrongFormatData_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.PatchAsync($"/api/posts/id", null);
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
private static void AssertElement(PostViewModel? actual, Post expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.Id, Is.EqualTo(expected.PostId));
|
||||
Assert.That(actual.PostName, Is.EqualTo(expected.PostName));
|
||||
Assert.That(actual.PostType, Is.EqualTo(expected.PostType.ToString()));
|
||||
Assert.That(actual.Salary, Is.EqualTo(expected.Salary));
|
||||
});
|
||||
}
|
||||
|
||||
private static PostBindingModel CreateModel(string? postId = null, string postName = "name", PostType postType = PostType.Manager, double salary = 10)
|
||||
=> new()
|
||||
{
|
||||
Id = postId ?? Guid.NewGuid().ToString(),
|
||||
PostName = postName,
|
||||
PostType = postType.ToString(),
|
||||
Salary = salary
|
||||
};
|
||||
|
||||
private static void AssertElement(Post? actual, PostBindingModel 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.ToString(), Is.EqualTo(expected.PostType));
|
||||
Assert.That(actual.Salary, Is.EqualTo(expected.Salary));
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
using SquirrelContract.ViewModels;
|
||||
using SquirrelDatabase.Models;
|
||||
using SquirrelTests.Infrastructure;
|
||||
using System.Net;
|
||||
|
||||
namespace SquirrelTests.WebApiControllersTests;
|
||||
|
||||
[TestFixture]
|
||||
internal class SalaryControllerTests : BaseWebApiControllerTest
|
||||
{
|
||||
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
SquirrelDbContext.RemovePostsFromDatabase();
|
||||
SquirrelDbContext.RemoveEmployeesFromDatabase();
|
||||
SquirrelDbContext.RemoveSalariesFromDatabase();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_WhenHaveRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var employee = SquirrelDbContext.InsertEmployeeToDatabaseAndReturn(fio: "Иванов И.И.");
|
||||
var salary = SquirrelDbContext.InsertSalaryToDatabaseAndReturn(employee.Id, employeeSalary: 100);
|
||||
SquirrelDbContext.InsertSalaryToDatabaseAndReturn(employee.Id);
|
||||
SquirrelDbContext.InsertSalaryToDatabaseAndReturn(employee.Id);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/salary/getrecords?fromDate={DateTime.UtcNow.AddDays(-10):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(10):MM/dd/yyyy HH:mm:ss}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<SalaryViewModel>>(response);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(3));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_WhenNoRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/salary/getrecords?fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<SalaryViewModel>>(response);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(0));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_OnlyInDatePeriod_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var employee = SquirrelDbContext.InsertEmployeeToDatabaseAndReturn(fio: "Иванов И.И.");
|
||||
SquirrelDbContext.InsertSalaryToDatabaseAndReturn(employee.Id, salaryDate: DateTime.UtcNow.AddDays(-2));
|
||||
SquirrelDbContext.InsertSalaryToDatabaseAndReturn(employee.Id, salaryDate: DateTime.UtcNow.AddDays(-1).AddMinutes(5));
|
||||
SquirrelDbContext.InsertSalaryToDatabaseAndReturn(employee.Id, salaryDate: DateTime.UtcNow.AddDays(1).AddMinutes(-5));
|
||||
SquirrelDbContext.InsertSalaryToDatabaseAndReturn(employee.Id, salaryDate: DateTime.UtcNow.AddDays(-2));
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/salary/getrecords?fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<SalaryViewModel>>(response);
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Has.Count.EqualTo(2));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_WhenDateIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/salary/getemployeerecords?fromDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_ByEmployee_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var employee1 = SquirrelDbContext.InsertEmployeeToDatabaseAndReturn(fio: "Иванов И.И.");
|
||||
var employee2 = SquirrelDbContext.InsertEmployeeToDatabaseAndReturn(fio: "Иванов И.И.");
|
||||
SquirrelDbContext.InsertSalaryToDatabaseAndReturn(employee1.Id);
|
||||
SquirrelDbContext.InsertSalaryToDatabaseAndReturn(employee1.Id);
|
||||
SquirrelDbContext.InsertSalaryToDatabaseAndReturn(employee2.Id);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/salary/getemployeerecords?fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}&id={employee1.Id}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<SalaryViewModel>>(response);
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Has.Count.EqualTo(2));
|
||||
Assert.That(data.All(x => x.EmployeeId == employee1.Id));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_ByEmployee_OnlyInDatePeriod_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var employee1 = SquirrelDbContext.InsertEmployeeToDatabaseAndReturn(fio: "Иванов И.И.");
|
||||
var employee2 = SquirrelDbContext.InsertEmployeeToDatabaseAndReturn(fio: "Иванов И.И.");
|
||||
SquirrelDbContext.InsertSalaryToDatabaseAndReturn(employee1.Id, salaryDate: DateTime.UtcNow.AddDays(-2));
|
||||
SquirrelDbContext.InsertSalaryToDatabaseAndReturn(employee1.Id, salaryDate: DateTime.UtcNow.AddDays(-1).AddMinutes(5));
|
||||
SquirrelDbContext.InsertSalaryToDatabaseAndReturn(employee2.Id, salaryDate: DateTime.UtcNow.AddDays(-1).AddMinutes(5));
|
||||
SquirrelDbContext.InsertSalaryToDatabaseAndReturn(employee1.Id, salaryDate: DateTime.UtcNow.AddDays(1).AddMinutes(-5));
|
||||
SquirrelDbContext.InsertSalaryToDatabaseAndReturn(employee2.Id, salaryDate: DateTime.UtcNow.AddDays(1).AddMinutes(-5));
|
||||
SquirrelDbContext.InsertSalaryToDatabaseAndReturn(employee1.Id, salaryDate: DateTime.UtcNow.AddDays(-2));
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/salary/getemployeerecords?fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}&id={employee1.Id}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<SalaryViewModel>>(response);
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Has.Count.EqualTo(2));
|
||||
Assert.That(data.All(x => x.EmployeeId == employee1.Id));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_ByEmployee_WhenDateIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var employee = SquirrelDbContext.InsertEmployeeToDatabaseAndReturn(fio: "Иванов И.И.");
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/salary/getemployeerecords?fromDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&id={employee.Id}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_ByEmployee_WhenIdIsNotGuid_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/salary/getemployeerecords?fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}&id=id");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Calculate_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var post = SquirrelDbContext.InsertPostToDatabaseAndReturn(salary: 1000);
|
||||
var employee = SquirrelDbContext.InsertEmployeeToDatabaseAndReturn(fio: "Иванов И.И.", postId: post.PostId);
|
||||
var sale = SquirrelDbContext.InsertSaleToDatabaseAndReturn(employee.Id);
|
||||
|
||||
var expectedSum = sale.Sum * 0.1 + post.Salary;
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/salary/calculate?date={DateTime.UtcNow:MM/dd/yyyy}", null);
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
var salaries = SquirrelDbContext.GetSalariesFromDatabaseByEmployeeId(employee.Id);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(salaries, Has.Length.EqualTo(1));
|
||||
Assert.That(salaries.First().EmployeeSalary, Is.EqualTo(expectedSum));
|
||||
Assert.That(salaries.First().SalaryDate.Month, Is.EqualTo(DateTime.UtcNow.Month));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Calculate_WithoutEmployees_ShouldSuccess_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/salary/calculate?date={DateTime.UtcNow:MM/dd/yyyy}", null);
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
var salaries = SquirrelDbContext.Salaries.ToArray();
|
||||
Assert.That(salaries, Has.Length.EqualTo(0));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Calculate_WithoutSalesByEmployee_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var post = SquirrelDbContext.InsertPostToDatabaseAndReturn(salary: 1000);
|
||||
var employee1 = SquirrelDbContext.InsertEmployeeToDatabaseAndReturn(fio: "name 1", postId: post.PostId);
|
||||
var employee2 = SquirrelDbContext.InsertEmployeeToDatabaseAndReturn(fio: "name 2", postId: post.PostId);
|
||||
var sale = SquirrelDbContext.InsertSaleToDatabaseAndReturn(employee1.Id);
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/salary/calculate?date={DateTime.UtcNow:MM/dd/yyyy}", null);
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
var salary1 = SquirrelDbContext.GetSalariesFromDatabaseByEmployeeId(employee1.Id).First().EmployeeSalary;
|
||||
var salary2 = SquirrelDbContext.GetSalariesFromDatabaseByEmployeeId(employee2.Id).First().EmployeeSalary;
|
||||
Assert.That(salary1, Is.Not.EqualTo(salary2));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Calculate_PostNotFound_ShouldNotFound_Test()
|
||||
{
|
||||
//Arrange
|
||||
SquirrelDbContext.InsertPostToDatabaseAndReturn();
|
||||
var employee = SquirrelDbContext.InsertEmployeeToDatabaseAndReturn(fio: "name", postId: Guid.NewGuid().ToString());
|
||||
var sale = SquirrelDbContext.InsertSaleToDatabaseAndReturn(employee.Id);
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/salary/calculate?date={DateTime.UtcNow:MM/dd/yyyy}", null);
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,503 @@
|
||||
using SquirrelContract.BindingModels;
|
||||
using SquirrelContract.Enums;
|
||||
using SquirrelContract.ViewModels;
|
||||
using SquirrelDatabase.Models;
|
||||
using SquirrelTests.Infrastructure;
|
||||
using System.Net;
|
||||
|
||||
namespace SquirrelTests.WebApiControllersTests;
|
||||
|
||||
[TestFixture]
|
||||
internal class SaleControllerTests : BaseWebApiControllerTest
|
||||
{
|
||||
private string _clientId;
|
||||
private string _employeeId;
|
||||
private string _cocktailId;
|
||||
|
||||
[SetUp]
|
||||
public void SetUp()
|
||||
{
|
||||
_clientId = SquirrelDbContext.InsertClientToDatabaseAndReturn().Id;
|
||||
_employeeId = SquirrelDbContext.InsertEmployeeToDatabaseAndReturn().Id;
|
||||
_cocktailId = SquirrelDbContext.InsertCocktailToDatabaseAndReturn().Id;
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
SquirrelDbContext.RemoveSalesFromDatabase();
|
||||
SquirrelDbContext.RemoveEmployeesFromDatabase();
|
||||
SquirrelDbContext.RemoveClientsFromDatabase();
|
||||
SquirrelDbContext.RemoveCocktailsFromDatabase();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_WhenHaveRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var sale = SquirrelDbContext.InsertSaleToDatabaseAndReturn(_employeeId, _clientId, sum: 10, cocktails: [(_cocktailId, 10, 1.1)]);
|
||||
SquirrelDbContext.InsertSaleToDatabaseAndReturn(_employeeId, _clientId, cocktails: [(_cocktailId, 10, 1.1)]);
|
||||
SquirrelDbContext.InsertSaleToDatabaseAndReturn(_employeeId, _clientId, cocktails: [(_cocktailId, 10, 1.1)]);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/sales/getrecords?fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}");
|
||||
//Assert
|
||||
var data = await GetModelFromResponseAsync<List<SaleViewModel>>(response);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(3));
|
||||
});
|
||||
AssertElement(data.First(x => x.Sum == sale.Sum), sale);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_WhenNoRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/sales/getrecords?fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<SaleViewModel>>(response);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(0));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_ByPeriod_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
SquirrelDbContext.InsertSaleToDatabaseAndReturn(_employeeId, _clientId, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(-3), cocktails: [(_cocktailId, 1, 1.1)]);
|
||||
SquirrelDbContext.InsertSaleToDatabaseAndReturn(_employeeId, _clientId, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(3), cocktails: [(_cocktailId, 1, 1.1)]);
|
||||
SquirrelDbContext.InsertSaleToDatabaseAndReturn(_employeeId, null, saleDate: DateTime.UtcNow.AddDays(1).AddMinutes(-3), cocktails: [(_cocktailId, 1, 1.1)]);
|
||||
SquirrelDbContext.InsertSaleToDatabaseAndReturn(_employeeId, null, saleDate: DateTime.UtcNow.AddDays(1).AddMinutes(3), cocktails: [(_cocktailId, 1, 1.1)]);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/sales/getrecords?fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<SaleViewModel>>(response);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(2));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_ByPeriod_WhenDateIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/sales/getrecords?fromDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_ByEmployeeId_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var employee = SquirrelDbContext.InsertEmployeeToDatabaseAndReturn(fio: "Other employee");
|
||||
SquirrelDbContext.InsertSaleToDatabaseAndReturn(_employeeId, _clientId, cocktails: [(_cocktailId, 1, 1.1)]);
|
||||
SquirrelDbContext.InsertSaleToDatabaseAndReturn(_employeeId, _clientId, cocktails: [(_cocktailId, 1, 1.1)]);
|
||||
SquirrelDbContext.InsertSaleToDatabaseAndReturn(employee.Id, null, cocktails: [(_cocktailId, 1, 1.1)]);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/sales/getemployeerecords?id={_employeeId}&fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<SaleViewModel>>(response);
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Has.Count.EqualTo(2));
|
||||
Assert.That(data.All(x => x.EmployeeId == _employeeId));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_ByEmployeeId_WhenNoRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var employee = SquirrelDbContext.InsertEmployeeToDatabaseAndReturn(fio: "Other employee");
|
||||
SquirrelDbContext.InsertSaleToDatabaseAndReturn(_employeeId, _clientId, cocktails: [(_cocktailId, 1, 1.1)]);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/sales/getemployeerecords?id={employee.Id}&fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<SaleViewModel>>(response);
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(0));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_ByEmployeeId_WhenDateIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/sales/getemployeerecords?id={_employeeId}&fromDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_ByEmployeeId_WhenIdIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/sales/getemployeerecords?id=Id&fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_ByClientId_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var client = SquirrelDbContext.InsertClientToDatabaseAndReturn(fio: "Other fio", phoneNumber: "+8-888-888-88-88");
|
||||
SquirrelDbContext.InsertSaleToDatabaseAndReturn(_employeeId, _clientId, cocktails: [(_cocktailId, 1, 1.1)]);
|
||||
SquirrelDbContext.InsertSaleToDatabaseAndReturn(_employeeId, _clientId, cocktails: [(_cocktailId, 1, 1.1)]);
|
||||
SquirrelDbContext.InsertSaleToDatabaseAndReturn(_employeeId, client.Id, cocktails: [(_cocktailId, 1, 1.1)]);
|
||||
SquirrelDbContext.InsertSaleToDatabaseAndReturn(_employeeId, null, cocktails: [(_cocktailId, 1, 1.1)]);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/sales/getclientrecords?id={_clientId}&fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<SaleViewModel>>(response);
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Has.Count.EqualTo(2));
|
||||
Assert.That(data.All(x => x.ClientId == _clientId));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_ByClientId_WhenNoRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var client = SquirrelDbContext.InsertClientToDatabaseAndReturn(fio: "Other client", phoneNumber: "+8-888-888-88-88");
|
||||
SquirrelDbContext.InsertSaleToDatabaseAndReturn(_employeeId, _clientId, cocktails: [(_cocktailId, 1, 1.1)]);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/sales/getclientrecords?id={client.Id}&fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<SaleViewModel>>(response);
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(0));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_ByClientId_WhenDateIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/sales/getclientrecords?id={_clientId}&fromDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_ByClientId_WhenIdIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/sales/getclientrecords?id=Id&fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_ByCocktailId_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var cocktail = SquirrelDbContext.InsertCocktailToDatabaseAndReturn(cocktailName: "Other name");
|
||||
SquirrelDbContext.InsertSaleToDatabaseAndReturn(_employeeId, _clientId, cocktails: [(_cocktailId, 5, 1.1)]);
|
||||
SquirrelDbContext.InsertSaleToDatabaseAndReturn(_employeeId, _clientId, cocktails: [(_cocktailId, 1, 1.1), (cocktail.Id, 4, 1.1)]);
|
||||
SquirrelDbContext.InsertSaleToDatabaseAndReturn(_employeeId, null, cocktails: [(cocktail.Id, 1, 1.1)]);
|
||||
SquirrelDbContext.InsertSaleToDatabaseAndReturn(_employeeId, null, cocktails: [(cocktail.Id, 1, 1.1), (_cocktailId, 1, 1.1)]);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/sales/getcocktailrecords?id={_cocktailId}&fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<SaleViewModel>>(response);
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Has.Count.EqualTo(3));
|
||||
Assert.That(data.All(x => x.Cocktails.Any(y => y.CocktailId == _cocktailId)));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_ByCocktailId_WhenNoRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var cocktail = SquirrelDbContext.InsertCocktailToDatabaseAndReturn(cocktailName: "Other cocktail");
|
||||
SquirrelDbContext.InsertSaleToDatabaseAndReturn(_employeeId, _clientId, cocktails: [(_cocktailId, 1, 1.1)]);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/sales/getcocktailrecords?id={cocktail.Id}&fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<SaleViewModel>>(response);
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(0));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_ByCocktailId_WhenDateIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/sales/getcocktailrecords?id={_cocktailId}&fromDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_ByCocktailId_WhenIdIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/sales/getcocktailrecords?id=Id&fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ById_WhenHaveRecord_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var sale = SquirrelDbContext.InsertSaleToDatabaseAndReturn(_employeeId, _clientId, cocktails: [(_cocktailId, 5, 1.1)]);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/sales/getrecord/{sale.Id}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
AssertElement(await GetModelFromResponseAsync<SaleViewModel>(response), sale);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ById_WhenNoRecord_ShouldNotFound_Test()
|
||||
{
|
||||
//Arrange
|
||||
SquirrelDbContext.InsertSaleToDatabaseAndReturn(_employeeId, _clientId, cocktails: [(_cocktailId, 5, 1.1)]);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/sales/getrecord/{Guid.NewGuid()}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ById_WhenRecordHasCanceled_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var sale = SquirrelDbContext.InsertSaleToDatabaseAndReturn(_employeeId, _clientId, cocktails: [(_cocktailId, 1, 1.2)], isCancel: true);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/sales/getrecord/{sale.Id}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ById_WhenIdIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/sales/getrecord/Id");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
SquirrelDbContext.InsertSaleToDatabaseAndReturn(_employeeId, null, cocktails: [(_cocktailId, 5, 1.1)]);
|
||||
var saleModel = CreateModel(_employeeId, _clientId, _cocktailId);
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/sales/sale", MakeContent(saleModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
AssertElement(SquirrelDbContext.GetSalesByClientId(_clientId)[0], saleModel);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenNoClient_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
SquirrelDbContext.InsertSaleToDatabaseAndReturn(_employeeId, _clientId, cocktails: [(_cocktailId, 5, 1.1)]);
|
||||
var saleModel = CreateModel(_employeeId, null, _cocktailId);
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/sales/sale", MakeContent(saleModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
AssertElement(SquirrelDbContext.GetSalesByClientId(null)[0], saleModel);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenDataIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var saleId = Guid.NewGuid().ToString();
|
||||
var saleModelWithIdIncorrect = new SaleBindingModel { Id = "Id", EmployeeId = _employeeId, ClientId = _clientId, DiscountType = 1, Cocktails = [new SaleCocktailBindingModel { SaleId = saleId, CocktailId = _cocktailId, Count = 10, Price = 1.1 }] };
|
||||
var saleModelWithEmployeeIdIncorrect = new SaleBindingModel { Id = saleId, EmployeeId = "Id", ClientId = _clientId, DiscountType = 1, Cocktails = [new SaleCocktailBindingModel { SaleId = saleId, CocktailId = _cocktailId, Count = 10, Price = 1.1 }] };
|
||||
var saleModelWithClientIdIncorrect = new SaleBindingModel { Id = saleId, EmployeeId = _employeeId, ClientId = "Id", DiscountType = 1, Cocktails = [new SaleCocktailBindingModel { SaleId = saleId, CocktailId = _cocktailId, Count = 10, Price = 1.1 }] };
|
||||
var saleModelWithCocktailsIncorrect = new SaleBindingModel { Id = saleId, EmployeeId = _employeeId, ClientId = _clientId, DiscountType = 1, Cocktails = null };
|
||||
var saleModelWithCocktailIdIncorrect = new SaleBindingModel { Id = saleId, EmployeeId = _employeeId, ClientId = _clientId, DiscountType = 1, Cocktails = [new SaleCocktailBindingModel { SaleId = saleId, CocktailId = "Id", Count = 10, Price = 1.1 }] };
|
||||
var saleModelWithCountIncorrect = new SaleBindingModel { Id = saleId, EmployeeId = _employeeId, ClientId = _clientId, DiscountType = 1, Cocktails = [new SaleCocktailBindingModel { SaleId = saleId, CocktailId = _cocktailId, Count = -10, Price = 1.1 }] };
|
||||
var saleModelWithPriceIncorrect = new SaleBindingModel { Id = saleId, EmployeeId = _employeeId, ClientId = _clientId, DiscountType = 1, Cocktails = [new SaleCocktailBindingModel { SaleId = saleId, CocktailId = _cocktailId, Count = 10, Price = -1.1 }] };
|
||||
//Act
|
||||
var responseWithIdIncorrect = await HttpClient.PostAsync($"/api/sales/sale", MakeContent(saleModelWithIdIncorrect));
|
||||
var responseWithEmployeeIdIncorrect = await HttpClient.PostAsync($"/api/sales/sale", MakeContent(saleModelWithEmployeeIdIncorrect));
|
||||
var responseWithClientIdIncorrect = await HttpClient.PostAsync($"/api/sales/sale", MakeContent(saleModelWithClientIdIncorrect));
|
||||
var responseWithCocktailsIncorrect = await HttpClient.PostAsync($"/api/sales/sale", MakeContent(saleModelWithCocktailsIncorrect));
|
||||
var responseWithCocktailIdIncorrect = await HttpClient.PostAsync($"/api/sales/sale", MakeContent(saleModelWithCocktailIdIncorrect));
|
||||
var responseWithCountIncorrect = await HttpClient.PostAsync($"/api/sales/sale", MakeContent(saleModelWithCountIncorrect));
|
||||
var responseWithPriceIncorrect = await HttpClient.PostAsync($"/api/sales/sale", MakeContent(saleModelWithPriceIncorrect));
|
||||
//Assert
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(responseWithIdIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "EmployeeId is incorrect");
|
||||
Assert.That(responseWithEmployeeIdIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "EmployeeId is incorrect");
|
||||
Assert.That(responseWithClientIdIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "ClientId is incorrect");
|
||||
Assert.That(responseWithCocktailsIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Cocktails is incorrect");
|
||||
Assert.That(responseWithCocktailIdIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "CocktailId is incorrect");
|
||||
Assert.That(responseWithCountIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Count is incorrect");
|
||||
Assert.That(responseWithPriceIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Price is incorrect");
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenSendEmptyData_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/sales/sale", MakeContent(string.Empty));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenSendWrongFormatData_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/sales/sale", MakeContent(new { Data = "test", Position = 10 }));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Delete_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var sale = SquirrelDbContext.InsertSaleToDatabaseAndReturn(_employeeId, _clientId, cocktails: [(_cocktailId, 5, 1.1)]);
|
||||
//Act
|
||||
var response = await HttpClient.DeleteAsync($"/api/sales/cancel/{sale.Id}");
|
||||
SquirrelDbContext.ChangeTracker.Clear();
|
||||
//Assert
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
Assert.That(SquirrelDbContext.GetSaleFromDatabaseById(sale.Id)!.IsCancel);
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Delete_WhenNoFoundRecord_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
SquirrelDbContext.InsertSaleToDatabaseAndReturn(_employeeId, _clientId, cocktails: [(_cocktailId, 5, 1.1)]);
|
||||
//Act
|
||||
var response = await HttpClient.DeleteAsync($"/api/sales/cancel/{Guid.NewGuid()}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Delete_WhenIsCanceled_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var sale = SquirrelDbContext.InsertSaleToDatabaseAndReturn(_employeeId, _clientId, cocktails: [(_cocktailId, 5, 1.1)], isCancel: true);
|
||||
//Act
|
||||
var response = await HttpClient.DeleteAsync($"/api/sales/cancel/{sale.Id}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Delete_WhenSendWrongFormatData_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.DeleteAsync($"/api/sales/cancel/id");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
private static void AssertElement(SaleViewModel? actual, Sale expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.Id, Is.EqualTo(expected.Id));
|
||||
Assert.That(actual.EmployeeFIO, Is.EqualTo(expected.Employee!.FIO));
|
||||
Assert.That(actual.ClientFIO, Is.EqualTo(expected.Client?.FIO));
|
||||
Assert.That(actual.DiscountType, Is.EqualTo(expected.DiscountType.ToString()));
|
||||
Assert.That(actual.Discount, Is.EqualTo(expected.Discount));
|
||||
Assert.That(actual.IsCancel, Is.EqualTo(expected.IsCancel));
|
||||
});
|
||||
|
||||
if (expected.SaleCocktails is not null)
|
||||
{
|
||||
Assert.That(actual.Cocktails, Is.Not.Null);
|
||||
Assert.That(actual.Cocktails, Has.Count.EqualTo(expected.SaleCocktails.Count));
|
||||
for (int i = 0; i < actual.Cocktails.Count; ++i)
|
||||
{
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.Cocktails[i].CocktailName, Is.EqualTo(expected.SaleCocktails[i].Cocktail!.CocktailName));
|
||||
Assert.That(actual.Cocktails[i].Count, Is.EqualTo(expected.SaleCocktails[i].Count));
|
||||
});
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
Assert.That(actual.Cocktails, Is.Null);
|
||||
}
|
||||
}
|
||||
|
||||
private static SaleBindingModel CreateModel(string employeeId, string? clientId, string cocktailId, string? id = null, DiscountType discountType = DiscountType.OnSale, int count = 1, double price = 1.1)
|
||||
{
|
||||
var saleId = id ?? Guid.NewGuid().ToString();
|
||||
return new()
|
||||
{
|
||||
Id = saleId,
|
||||
EmployeeId = employeeId,
|
||||
ClientId = clientId,
|
||||
DiscountType = (int)discountType,
|
||||
Cocktails = [new SaleCocktailBindingModel { SaleId = saleId, CocktailId = cocktailId, Count = count, Price = price }]
|
||||
};
|
||||
}
|
||||
|
||||
private static void AssertElement(Sale? actual, SaleBindingModel expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.EmployeeId, Is.EqualTo(expected.EmployeeId));
|
||||
Assert.That(actual.ClientId, Is.EqualTo(expected.ClientId));
|
||||
Assert.That((int)actual.DiscountType, Is.EqualTo(expected.DiscountType));
|
||||
Assert.That(!actual.IsCancel);
|
||||
});
|
||||
|
||||
if (expected.Cocktails is not null)
|
||||
{
|
||||
Assert.That(actual.SaleCocktails, Is.Not.Null);
|
||||
Assert.That(actual.SaleCocktails, Has.Count.EqualTo(expected.Cocktails.Count));
|
||||
for (int i = 0; i < actual.SaleCocktails.Count; ++i)
|
||||
{
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.SaleCocktails[i].CocktailId, Is.EqualTo(expected.Cocktails[i].CocktailId));
|
||||
Assert.That(actual.SaleCocktails[i].Count, Is.EqualTo(expected.Cocktails[i].Count));
|
||||
Assert.That(actual.SaleCocktails[i].Price, Is.EqualTo(expected.Cocktails[i].Price));
|
||||
});
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
Assert.That(actual.SaleCocktails, Is.Null);
|
||||
}
|
||||
}
|
||||
}
|
||||
24
SquirrelContract/SquirrelTests/appsettings.json
Normal file
24
SquirrelContract/SquirrelTests/appsettings.json
Normal file
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
}
|
||||
},
|
||||
"Serilog": {
|
||||
"Using": [ "Serilog.Sinks.File" ],
|
||||
"MinimumLevel": {
|
||||
"Default": "Information"
|
||||
},
|
||||
"WriteTo": [
|
||||
{
|
||||
"Name": "File",
|
||||
"Args": {
|
||||
"path": "../logs/squirrel-.log",
|
||||
"rollingInterval": "Day",
|
||||
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} {CorrelationId} {Level:u3} {Username} {Message:lj}{Exception}{NewLine}"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
189
SquirrelContract/SquirrelWebApi/Adapters/ClientAdapter.cs
Normal file
189
SquirrelContract/SquirrelWebApi/Adapters/ClientAdapter.cs
Normal file
@@ -0,0 +1,189 @@
|
||||
using AutoMapper;
|
||||
using SquirrelContract.AdapterContracts;
|
||||
using SquirrelContract.AdapterContracts.OperationResponses;
|
||||
using SquirrelContract.BindingModels;
|
||||
using SquirrelContract.BusinessLogicContracts;
|
||||
using SquirrelContract.DataModels;
|
||||
using SquirrelContract.Exceptions;
|
||||
using SquirrelContract.ViewModels;
|
||||
|
||||
namespace SquirrelWebApi.Adapters;
|
||||
|
||||
public class ClientAdapter : IClientAdapter
|
||||
{
|
||||
private readonly IClientBusinessLogicContract _clientBusinessLogicContract;
|
||||
|
||||
private readonly ILogger _logger;
|
||||
|
||||
private readonly Mapper _mapper;
|
||||
|
||||
public ClientAdapter(IClientBusinessLogicContract clientBusinessLogicContract, ILogger<ClientAdapter> logger)
|
||||
{
|
||||
_clientBusinessLogicContract = clientBusinessLogicContract;
|
||||
_logger = logger;
|
||||
var config = new MapperConfiguration(cfg =>
|
||||
{
|
||||
cfg.CreateMap<ClientBindingModel, ClientDataModel>();
|
||||
cfg.CreateMap<ClientDataModel, ClientViewModel>();
|
||||
});
|
||||
_mapper = new Mapper(config);
|
||||
}
|
||||
|
||||
public ClientOperationResponse GetList()
|
||||
{
|
||||
try
|
||||
{
|
||||
return ClientOperationResponse.OK([.. _clientBusinessLogicContract.GetAllClients().Select(x => _mapper.Map<ClientViewModel>(x))]);
|
||||
}
|
||||
catch (NullListException)
|
||||
{
|
||||
_logger.LogError("NullListException");
|
||||
return ClientOperationResponse.NotFound("The list is not initialized");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return ClientOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return ClientOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public ClientOperationResponse GetElement(string data)
|
||||
{
|
||||
try
|
||||
{
|
||||
return ClientOperationResponse.OK(_mapper.Map<ClientViewModel>(_clientBusinessLogicContract.GetClientByData(data)));
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return ClientOperationResponse.BadRequest("Data is empty");
|
||||
}
|
||||
catch (ElementNotFoundException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementNotFoundException");
|
||||
return ClientOperationResponse.NotFound($"Not found element by data {data}");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return ClientOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return ClientOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public ClientOperationResponse RegisterClient(ClientBindingModel clientModel)
|
||||
{
|
||||
try
|
||||
{
|
||||
_clientBusinessLogicContract.InsertClient(_mapper.Map<ClientDataModel>(clientModel));
|
||||
return ClientOperationResponse.NoContent();
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return ClientOperationResponse.BadRequest("Data is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return ClientOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (ElementExistsException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementExistsException");
|
||||
return ClientOperationResponse.BadRequest(ex.Message);
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return ClientOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return ClientOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public ClientOperationResponse ChangeClientInfo(ClientBindingModel clientModel)
|
||||
{
|
||||
try
|
||||
{
|
||||
_clientBusinessLogicContract.UpdateClient(_mapper.Map<ClientDataModel>(clientModel));
|
||||
return ClientOperationResponse.NoContent();
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return ClientOperationResponse.BadRequest("Data is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return ClientOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (ElementNotFoundException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementNotFoundException");
|
||||
return ClientOperationResponse.BadRequest($"Not found element by Id {clientModel.Id}");
|
||||
}
|
||||
catch (ElementExistsException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementExistsException");
|
||||
return ClientOperationResponse.BadRequest(ex.Message);
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return ClientOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return ClientOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public ClientOperationResponse RemoveClient(string id)
|
||||
{
|
||||
try
|
||||
{
|
||||
_clientBusinessLogicContract.DeleteClient(id);
|
||||
return ClientOperationResponse.NoContent();
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return ClientOperationResponse.BadRequest("Id is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return ClientOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (ElementNotFoundException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementNotFoundException");
|
||||
return ClientOperationResponse.BadRequest($"Not found element by id: {id}");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return ClientOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return ClientOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
233
SquirrelContract/SquirrelWebApi/Adapters/CocktailAdapter.cs
Normal file
233
SquirrelContract/SquirrelWebApi/Adapters/CocktailAdapter.cs
Normal file
@@ -0,0 +1,233 @@
|
||||
using AutoMapper;
|
||||
using SquirrelContract.AdapterContracts;
|
||||
using SquirrelContract.AdapterContracts.OperationResponses;
|
||||
using SquirrelContract.BindingModels;
|
||||
using SquirrelContract.BusinessLogicContracts;
|
||||
using SquirrelContract.DataModels;
|
||||
using SquirrelContract.Exceptions;
|
||||
using SquirrelContract.ViewModels;
|
||||
|
||||
namespace SquirrelWebApi.Adapters;
|
||||
|
||||
public class CocktailAdapter : ICocktailAdapter
|
||||
{
|
||||
private readonly ICocktailBusinessLogicContract _cocktailBusinessLogicContract;
|
||||
|
||||
private readonly ILogger _logger;
|
||||
|
||||
private readonly Mapper _mapper;
|
||||
|
||||
public CocktailAdapter(ICocktailBusinessLogicContract cocktailBusinessLogicContract, ILogger<CocktailAdapter> logger)
|
||||
{
|
||||
_cocktailBusinessLogicContract = cocktailBusinessLogicContract;
|
||||
_logger = logger;
|
||||
var config = new MapperConfiguration(cfg =>
|
||||
{
|
||||
cfg.CreateMap<CocktailBindingModel, CocktailDataModel>();
|
||||
cfg.CreateMap<CocktailDataModel, CocktailViewModel>();
|
||||
cfg.CreateMap<CocktailHistoryDataModel, CocktailHistoryViewModel>();
|
||||
|
||||
});
|
||||
_mapper = new Mapper(config);
|
||||
}
|
||||
|
||||
public CocktailOperationResponse GetList(bool includeDeleted)
|
||||
{
|
||||
try
|
||||
{
|
||||
return CocktailOperationResponse.OK([.. _cocktailBusinessLogicContract.GetAllCocktails().Select(x => _mapper.Map<CocktailViewModel>(x))]);
|
||||
}
|
||||
catch (NullListException)
|
||||
{
|
||||
_logger.LogError("NullListException");
|
||||
return CocktailOperationResponse.NotFound("The list is not initialized");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return CocktailOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return CocktailOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
public CocktailOperationResponse GetHistory(string id)
|
||||
{
|
||||
try
|
||||
{
|
||||
return CocktailOperationResponse.OK([.. _cocktailBusinessLogicContract.GetCocktailHistoryByCocktail(id).Select(x => _mapper.Map<CocktailHistoryViewModel>(x))]);
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return CocktailOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (NullListException)
|
||||
{
|
||||
_logger.LogError("NullListException");
|
||||
return CocktailOperationResponse.NotFound("The list is not initialized");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return CocktailOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return CocktailOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public CocktailOperationResponse GetElement(string data)
|
||||
{
|
||||
try
|
||||
{
|
||||
return CocktailOperationResponse.OK(_mapper.Map<CocktailViewModel>(_cocktailBusinessLogicContract.GetCocktailByData(data)));
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return CocktailOperationResponse.BadRequest("Data is empty");
|
||||
}
|
||||
catch (ElementNotFoundException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementNotFoundException");
|
||||
return CocktailOperationResponse.NotFound($"Not found element by data {data}");
|
||||
}
|
||||
catch (ElementDeletedException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementDeletedException");
|
||||
return CocktailOperationResponse.BadRequest($"Element by data: {data} was deleted");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return CocktailOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return CocktailOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public CocktailOperationResponse RegisterCocktail(CocktailBindingModel cocktailModel)
|
||||
{
|
||||
try
|
||||
{
|
||||
_cocktailBusinessLogicContract.InsertCocktail(_mapper.Map<CocktailDataModel>(cocktailModel));
|
||||
return CocktailOperationResponse.NoContent();
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return CocktailOperationResponse.BadRequest("Data is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return CocktailOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (ElementExistsException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementExistsException");
|
||||
return CocktailOperationResponse.BadRequest(ex.Message);
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return CocktailOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return CocktailOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public CocktailOperationResponse ChangeCocktailInfo(CocktailBindingModel cocktailModel)
|
||||
{
|
||||
try
|
||||
{
|
||||
_cocktailBusinessLogicContract.UpdateCocktail(_mapper.Map<CocktailDataModel>(cocktailModel));
|
||||
return CocktailOperationResponse.NoContent();
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return CocktailOperationResponse.BadRequest("Data is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return CocktailOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (ElementNotFoundException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementNotFoundException");
|
||||
return CocktailOperationResponse.BadRequest($"Not found element by Id {cocktailModel.Id}");
|
||||
}
|
||||
catch (ElementExistsException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementExistsException");
|
||||
return CocktailOperationResponse.BadRequest(ex.Message);
|
||||
}
|
||||
catch (ElementDeletedException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementDeletedException");
|
||||
return CocktailOperationResponse.BadRequest($"Element by id: {cocktailModel.Id} was deleted");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return CocktailOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return CocktailOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public CocktailOperationResponse RemoveCocktail(string id)
|
||||
{
|
||||
try
|
||||
{
|
||||
_cocktailBusinessLogicContract.DeleteCocktail(id);
|
||||
return CocktailOperationResponse.NoContent();
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return CocktailOperationResponse.BadRequest("Id is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return CocktailOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (ElementNotFoundException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementNotFoundException");
|
||||
return CocktailOperationResponse.BadRequest($"Not found element by id: {id}");
|
||||
}
|
||||
catch (ElementDeletedException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementDeletedException");
|
||||
return CocktailOperationResponse.BadRequest($"Element by id: {id} was deleted");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return CocktailOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return CocktailOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
278
SquirrelContract/SquirrelWebApi/Adapters/EmployeeAdapter.cs
Normal file
278
SquirrelContract/SquirrelWebApi/Adapters/EmployeeAdapter.cs
Normal file
@@ -0,0 +1,278 @@
|
||||
using AutoMapper;
|
||||
using SquirrelContract.AdapterContracts;
|
||||
using SquirrelContract.AdapterContracts.OperationResponses;
|
||||
using SquirrelContract.BindingModels;
|
||||
using SquirrelContract.BusinessLogicContracts;
|
||||
using SquirrelContract.DataModels;
|
||||
using SquirrelContract.Exceptions;
|
||||
using SquirrelContract.ViewModels;
|
||||
|
||||
namespace SquirrelWebApi.Adapters;
|
||||
|
||||
public class EmployeeAdapter : IEmployeeAdapter
|
||||
{
|
||||
private readonly IEmployeeBusinessLogicContract _employeeBusinessLogicContract;
|
||||
|
||||
private readonly ILogger _logger;
|
||||
|
||||
private readonly Mapper _mapper;
|
||||
|
||||
public EmployeeAdapter(IEmployeeBusinessLogicContract employeeBusinessLogicContract, ILogger<EmployeeAdapter> logger)
|
||||
{
|
||||
_employeeBusinessLogicContract = employeeBusinessLogicContract;
|
||||
_logger = logger;
|
||||
var config = new MapperConfiguration(cfg =>
|
||||
{
|
||||
cfg.CreateMap<EmployeeBindingModel, EmployeeDataModel>();
|
||||
cfg.CreateMap<EmployeeDataModel, EmployeeViewModel>();
|
||||
});
|
||||
_mapper = new Mapper(config);
|
||||
}
|
||||
|
||||
public EmployeeOperationResponse GetList(bool includeDeleted)
|
||||
{
|
||||
try
|
||||
{
|
||||
return EmployeeOperationResponse.OK([.. _employeeBusinessLogicContract.GetAllEmployees(!includeDeleted).Select(x => _mapper.Map<EmployeeViewModel>(x))]);
|
||||
}
|
||||
catch (NullListException)
|
||||
{
|
||||
_logger.LogError("NullListException");
|
||||
return EmployeeOperationResponse.NotFound("The list is not initialized");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return EmployeeOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return EmployeeOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public EmployeeOperationResponse GetPostList(string id, bool includeDeleted)
|
||||
{
|
||||
try
|
||||
{
|
||||
return EmployeeOperationResponse.OK([.. _employeeBusinessLogicContract.GetAllEmployeesByPost(id, !includeDeleted).Select(x => _mapper.Map<EmployeeViewModel>(x))]);
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return EmployeeOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (NullListException)
|
||||
{
|
||||
_logger.LogError("NullListException");
|
||||
return EmployeeOperationResponse.NotFound("The list is not initialized");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return EmployeeOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return EmployeeOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public EmployeeOperationResponse GetListByBirthDate(DateTime fromDate, DateTime toDate, bool includeDeleted)
|
||||
{
|
||||
try
|
||||
{
|
||||
return EmployeeOperationResponse.OK([.. _employeeBusinessLogicContract.GetAllEmployeesByBirthDate(fromDate, toDate, !includeDeleted).Select(x => _mapper.Map<EmployeeViewModel>(x))]);
|
||||
}
|
||||
catch (IncorrectDatesException ex)
|
||||
{
|
||||
_logger.LogError(ex, "IncorrectDatesException");
|
||||
return EmployeeOperationResponse.BadRequest($"Incorrect dates: {ex.Message}");
|
||||
}
|
||||
catch (NullListException)
|
||||
{
|
||||
_logger.LogError("NullListException");
|
||||
return EmployeeOperationResponse.NotFound("The list is not initialized");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return EmployeeOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return EmployeeOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public EmployeeOperationResponse GetListByEmploymentDate(DateTime fromDate, DateTime toDate, bool includeDeleted)
|
||||
{
|
||||
try
|
||||
{
|
||||
return EmployeeOperationResponse.OK([.. _employeeBusinessLogicContract.GetAllEmployeesByEmploymentDate(fromDate, toDate, !includeDeleted).Select(x => _mapper.Map<EmployeeViewModel>(x))]);
|
||||
}
|
||||
catch (IncorrectDatesException ex)
|
||||
{
|
||||
_logger.LogError(ex, "IncorrectDatesException");
|
||||
return EmployeeOperationResponse.BadRequest($"Incorrect dates: {ex.Message}");
|
||||
}
|
||||
catch (NullListException)
|
||||
{
|
||||
_logger.LogError("NullListException");
|
||||
return EmployeeOperationResponse.NotFound("The list is not initialized");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return EmployeeOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return EmployeeOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public EmployeeOperationResponse GetElement(string data)
|
||||
{
|
||||
try
|
||||
{
|
||||
return EmployeeOperationResponse.OK(_mapper.Map<EmployeeViewModel>(_employeeBusinessLogicContract.GetEmployeeByData(data)));
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return EmployeeOperationResponse.BadRequest("Data is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return EmployeeOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (ElementNotFoundException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementNotFoundException");
|
||||
return EmployeeOperationResponse.NotFound($"Not found element by data {data}");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return EmployeeOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return EmployeeOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public EmployeeOperationResponse RegisterEmployee(EmployeeBindingModel employeeModel)
|
||||
{
|
||||
try
|
||||
{
|
||||
_employeeBusinessLogicContract.InsertEmployee(_mapper.Map<EmployeeDataModel>(employeeModel));
|
||||
return EmployeeOperationResponse.NoContent();
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return EmployeeOperationResponse.BadRequest("Data is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return EmployeeOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (ElementExistsException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementExistsException");
|
||||
return EmployeeOperationResponse.BadRequest(ex.Message);
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return EmployeeOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return EmployeeOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public EmployeeOperationResponse ChangeEmployeeInfo(EmployeeBindingModel employeeModel)
|
||||
{
|
||||
try
|
||||
{
|
||||
_employeeBusinessLogicContract.UpdateEmployee(_mapper.Map<EmployeeDataModel>(employeeModel));
|
||||
return EmployeeOperationResponse.NoContent();
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return EmployeeOperationResponse.BadRequest("Data is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return EmployeeOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (ElementNotFoundException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementNotFoundException");
|
||||
return EmployeeOperationResponse.BadRequest($"Not found element by Id {employeeModel.Id}");
|
||||
}
|
||||
catch (ElementExistsException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementExistsException");
|
||||
return EmployeeOperationResponse.BadRequest(ex.Message);
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return EmployeeOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return EmployeeOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public EmployeeOperationResponse RemoveEmployee(string id)
|
||||
{
|
||||
try
|
||||
{
|
||||
_employeeBusinessLogicContract.DeleteEmployee(id);
|
||||
return EmployeeOperationResponse.NoContent();
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return EmployeeOperationResponse.BadRequest("Id is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return EmployeeOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (ElementNotFoundException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementNotFoundException");
|
||||
return EmployeeOperationResponse.BadRequest($"Not found element by id: {id}");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return EmployeeOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return EmployeeOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
266
SquirrelContract/SquirrelWebApi/Adapters/PostAdapter.cs
Normal file
266
SquirrelContract/SquirrelWebApi/Adapters/PostAdapter.cs
Normal file
@@ -0,0 +1,266 @@
|
||||
using AutoMapper;
|
||||
using SquirrelContract.AdapterContracts;
|
||||
using SquirrelContract.AdapterContracts.OperationResponses;
|
||||
using SquirrelContract.BindingModels;
|
||||
using SquirrelContract.BusinessLogicContracts;
|
||||
using SquirrelContract.DataModels;
|
||||
using SquirrelContract.Exceptions;
|
||||
using SquirrelContract.ViewModels;
|
||||
|
||||
namespace SquirrelWebApi.Adapters;
|
||||
|
||||
public class PostAdapter : IPostAdapter
|
||||
{
|
||||
private readonly IPostBusinessLogicContract _postBusinessLogicContract;
|
||||
|
||||
private readonly ILogger _logger;
|
||||
|
||||
private readonly Mapper _mapper;
|
||||
|
||||
public PostAdapter(IPostBusinessLogicContract postBusinessLogicContract, ILogger<PostAdapter> logger)
|
||||
{
|
||||
_postBusinessLogicContract = postBusinessLogicContract;
|
||||
_logger = logger;
|
||||
var config = new MapperConfiguration(cfg =>
|
||||
{
|
||||
cfg.CreateMap<PostBindingModel, PostDataModel>();
|
||||
cfg.CreateMap<PostDataModel, PostViewModel>();
|
||||
});
|
||||
_mapper = new Mapper(config);
|
||||
}
|
||||
|
||||
public PostOperationResponse GetList()
|
||||
{
|
||||
try
|
||||
{
|
||||
return PostOperationResponse.OK([.. _postBusinessLogicContract.GetAllPosts().Select(x => _mapper.Map<PostViewModel>(x))]);
|
||||
}
|
||||
catch (NullListException)
|
||||
{
|
||||
_logger.LogError("NullListException");
|
||||
return PostOperationResponse.NotFound("The list is not initialized");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return PostOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return PostOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public PostOperationResponse GetHistory(string id)
|
||||
{
|
||||
try
|
||||
{
|
||||
return PostOperationResponse.OK([.. _postBusinessLogicContract.GetAllDataOfPost(id).Select(x => _mapper.Map<PostViewModel>(x))]);
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return PostOperationResponse.BadRequest("Data is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return PostOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return PostOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return PostOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public PostOperationResponse GetElement(string data)
|
||||
{
|
||||
try
|
||||
{
|
||||
return PostOperationResponse.OK(_mapper.Map<PostViewModel>(_postBusinessLogicContract.GetPostByData(data)));
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return PostOperationResponse.BadRequest("Data is empty");
|
||||
}
|
||||
catch (ElementNotFoundException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementNotFoundException");
|
||||
return PostOperationResponse.NotFound($"Not found element by data {data}");
|
||||
}
|
||||
catch (ElementDeletedException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementDeletedException");
|
||||
return PostOperationResponse.BadRequest($"Element by data: {data} was deleted");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return PostOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return PostOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public PostOperationResponse RegisterPost(PostBindingModel postModel)
|
||||
{
|
||||
try
|
||||
{
|
||||
_postBusinessLogicContract.InsertPost(_mapper.Map<PostDataModel>(postModel));
|
||||
return PostOperationResponse.NoContent();
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return PostOperationResponse.BadRequest("Data is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return PostOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (ElementExistsException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementExistsException");
|
||||
return PostOperationResponse.BadRequest(ex.Message);
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return PostOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return PostOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public PostOperationResponse ChangePostInfo(PostBindingModel postModel)
|
||||
{
|
||||
try
|
||||
{
|
||||
_postBusinessLogicContract.UpdatePost(_mapper.Map<PostDataModel>(postModel));
|
||||
return PostOperationResponse.NoContent();
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return PostOperationResponse.BadRequest("Data is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return PostOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (ElementNotFoundException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementNotFoundException");
|
||||
return PostOperationResponse.BadRequest($"Not found element by Id {postModel.Id}");
|
||||
}
|
||||
catch (ElementExistsException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementExistsException");
|
||||
return PostOperationResponse.BadRequest(ex.Message);
|
||||
}
|
||||
catch (ElementDeletedException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementDeletedException");
|
||||
return PostOperationResponse.BadRequest($"Element by id: {postModel.Id} was deleted");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return PostOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return PostOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public PostOperationResponse RemovePost(string id)
|
||||
{
|
||||
try
|
||||
{
|
||||
_postBusinessLogicContract.DeletePost(id);
|
||||
return PostOperationResponse.NoContent();
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return PostOperationResponse.BadRequest("Id is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return PostOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (ElementNotFoundException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementNotFoundException");
|
||||
return PostOperationResponse.BadRequest($"Not found element by id: {id}");
|
||||
}
|
||||
catch (ElementDeletedException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementDeletedException");
|
||||
return PostOperationResponse.BadRequest($"Element by id: {id} was deleted");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return PostOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return PostOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public PostOperationResponse RestorePost(string id)
|
||||
{
|
||||
try
|
||||
{
|
||||
_postBusinessLogicContract.RestorePost(id);
|
||||
return PostOperationResponse.NoContent();
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return PostOperationResponse.BadRequest("Id is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return PostOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (ElementNotFoundException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementNotFoundException");
|
||||
return PostOperationResponse.BadRequest($"Not found element by id: {id}");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return PostOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return PostOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
119
SquirrelContract/SquirrelWebApi/Adapters/SalaryAdapter.cs
Normal file
119
SquirrelContract/SquirrelWebApi/Adapters/SalaryAdapter.cs
Normal file
@@ -0,0 +1,119 @@
|
||||
using AutoMapper;
|
||||
using BarBelochkaContract.DataModels;
|
||||
using SquirrelContract.AdapterContracts;
|
||||
using SquirrelContract.AdapterContracts.OperationResponses;
|
||||
using SquirrelContract.BusinessLogicContracts;
|
||||
using SquirrelContract.Exceptions;
|
||||
using SquirrelContract.ViewModels;
|
||||
|
||||
namespace SquirrelWebApi.Adapters;
|
||||
|
||||
public class SalaryAdapter : ISalaryAdapter
|
||||
{
|
||||
private readonly ISalaryBusinessLogicContract _salaryBusinessLogicContract;
|
||||
|
||||
private readonly ILogger _logger;
|
||||
|
||||
private readonly Mapper _mapper;
|
||||
|
||||
public SalaryAdapter(ISalaryBusinessLogicContract salaryBusinessLogicContract, ILogger<SalaryAdapter> logger)
|
||||
{
|
||||
_salaryBusinessLogicContract = salaryBusinessLogicContract;
|
||||
_logger = logger;
|
||||
var config = new MapperConfiguration(cfg =>
|
||||
{
|
||||
cfg.CreateMap<SalaryDataModel, SalaryViewModel>();
|
||||
});
|
||||
_mapper = new Mapper(config);
|
||||
}
|
||||
|
||||
public SalaryOperationResponse GetListByPeriod(DateTime fromDate, DateTime toDate)
|
||||
{
|
||||
try
|
||||
{
|
||||
return SalaryOperationResponse.OK([.. _salaryBusinessLogicContract.GetAllSalariesByPeriod(fromDate, toDate).Select(x => _mapper.Map<SalaryViewModel>(x))]);
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return SalaryOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (IncorrectDatesException ex)
|
||||
{
|
||||
_logger.LogError(ex, "IncorrectDatesException");
|
||||
return SalaryOperationResponse.BadRequest($"Incorrect dates: {ex.Message}");
|
||||
}
|
||||
catch (NullListException)
|
||||
{
|
||||
_logger.LogError("NullListException");
|
||||
return SalaryOperationResponse.NotFound("The list is not initialized");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return SalaryOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return SalaryOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public SalaryOperationResponse GetListByPeriodByEmployee(DateTime fromDate, DateTime toDate, string employeeId)
|
||||
{
|
||||
try
|
||||
{
|
||||
return SalaryOperationResponse.OK([.. _salaryBusinessLogicContract.GetAllSalariesByPeriodByEmployee(fromDate, toDate, employeeId).Select(x => _mapper.Map<SalaryViewModel>(x))]);
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return SalaryOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (IncorrectDatesException ex)
|
||||
{
|
||||
_logger.LogError(ex, "IncorrectDatesException");
|
||||
return SalaryOperationResponse.BadRequest($"Incorrect dates: {ex.Message}");
|
||||
}
|
||||
catch (NullListException)
|
||||
{
|
||||
_logger.LogError("NullListException");
|
||||
return SalaryOperationResponse.NotFound("The list is not initialized");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return SalaryOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return SalaryOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public SalaryOperationResponse CalculateSalary(DateTime date)
|
||||
{
|
||||
try
|
||||
{
|
||||
_salaryBusinessLogicContract.CalculateSalaryByMounth(date);
|
||||
return SalaryOperationResponse.NoContent();
|
||||
}
|
||||
catch (NullListException)
|
||||
{
|
||||
_logger.LogError("NullListException");
|
||||
return SalaryOperationResponse.NotFound("The list is not initialized");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return SalaryOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return SalaryOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
262
SquirrelContract/SquirrelWebApi/Adapters/SaleAdapter.cs
Normal file
262
SquirrelContract/SquirrelWebApi/Adapters/SaleAdapter.cs
Normal file
@@ -0,0 +1,262 @@
|
||||
using AutoMapper;
|
||||
using SquirrelContract.AdapterContracts;
|
||||
using SquirrelContract.AdapterContracts.OperationResponses;
|
||||
using SquirrelContract.BindingModels;
|
||||
using SquirrelContract.BusinessLogicContracts;
|
||||
using SquirrelContract.DataModels;
|
||||
using SquirrelContract.Exceptions;
|
||||
using SquirrelContract.ViewModels;
|
||||
|
||||
namespace SquirrelWebApi.Adapters;
|
||||
|
||||
public class SaleAdapter : ISaleAdapter
|
||||
{
|
||||
private readonly ISaleBusinessLogicContract _saleBusinessLogicContract;
|
||||
|
||||
private readonly ILogger _logger;
|
||||
|
||||
private readonly Mapper _mapper;
|
||||
|
||||
public SaleAdapter(ISaleBusinessLogicContract saleBusinessLogicContract, ILogger<SaleAdapter> logger)
|
||||
{
|
||||
_saleBusinessLogicContract = saleBusinessLogicContract;
|
||||
_logger = logger;
|
||||
var config = new MapperConfiguration(cfg =>
|
||||
{
|
||||
cfg.CreateMap<SaleBindingModel, SaleDataModel>();
|
||||
cfg.CreateMap<SaleDataModel, SaleViewModel>();
|
||||
cfg.CreateMap<SaleCocktailBindingModel, SaleCocktailDataModel>();
|
||||
cfg.CreateMap<SaleCocktailDataModel, SaleCocktailViewModel>();
|
||||
});
|
||||
_mapper = new Mapper(config);
|
||||
}
|
||||
|
||||
public SaleOperationResponse GetList(DateTime fromDate, DateTime toDate)
|
||||
{
|
||||
try
|
||||
{
|
||||
return SaleOperationResponse.OK([.. _saleBusinessLogicContract.GetAllSalesByPeriod(fromDate, toDate).Select(x => _mapper.Map<SaleViewModel>(x))]);
|
||||
}
|
||||
catch (IncorrectDatesException ex)
|
||||
{
|
||||
_logger.LogError(ex, "IncorrectDatesException");
|
||||
return SaleOperationResponse.BadRequest($"Incorrect dates: {ex.Message}");
|
||||
}
|
||||
catch (NullListException)
|
||||
{
|
||||
_logger.LogError("NullListException");
|
||||
return SaleOperationResponse.NotFound("The list is not initialized");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return SaleOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return SaleOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public SaleOperationResponse GetEmployeeList(string id, DateTime fromDate, DateTime toDate)
|
||||
{
|
||||
try
|
||||
{
|
||||
return SaleOperationResponse.OK([.. _saleBusinessLogicContract.GetAllSalesByEmployeeByPeriod(id, fromDate, toDate).Select(x => _mapper.Map<SaleViewModel>(x))]);
|
||||
}
|
||||
catch (IncorrectDatesException ex)
|
||||
{
|
||||
_logger.LogError(ex, "IncorrectDatesException");
|
||||
return SaleOperationResponse.BadRequest($"Incorrect dates: {ex.Message}");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return SaleOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (NullListException)
|
||||
{
|
||||
_logger.LogError("NullListException");
|
||||
return SaleOperationResponse.NotFound("The list is not initialized");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return SaleOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return SaleOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public SaleOperationResponse GetClientList(string id, DateTime fromDate, DateTime toDate)
|
||||
{
|
||||
try
|
||||
{
|
||||
return SaleOperationResponse.OK([.. _saleBusinessLogicContract.GetAllSalesByClientByPeriod(id, fromDate, toDate).Select(x => _mapper.Map<SaleViewModel>(x))]);
|
||||
}
|
||||
catch (IncorrectDatesException ex)
|
||||
{
|
||||
_logger.LogError(ex, "IncorrectDatesException");
|
||||
return SaleOperationResponse.BadRequest($"Incorrect dates: {ex.Message}");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return SaleOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (NullListException)
|
||||
{
|
||||
_logger.LogError("NullListException");
|
||||
return SaleOperationResponse.NotFound("The list is not initialized");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return SaleOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return SaleOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public SaleOperationResponse GetCocktailList(string id, DateTime fromDate, DateTime toDate)
|
||||
{
|
||||
try
|
||||
{
|
||||
return SaleOperationResponse.OK([.. _saleBusinessLogicContract.GetAllSalesByCocktailByPeriod(id, fromDate, toDate).Select(x => _mapper.Map<SaleViewModel>(x))]);
|
||||
}
|
||||
catch (IncorrectDatesException ex)
|
||||
{
|
||||
_logger.LogError(ex, "IncorrectDatesException");
|
||||
return SaleOperationResponse.BadRequest($"Incorrect dates: {ex.Message}");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return SaleOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (NullListException)
|
||||
{
|
||||
_logger.LogError("NullListException");
|
||||
return SaleOperationResponse.NotFound("The list is not initialized");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return SaleOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return SaleOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public SaleOperationResponse GetElement(string id)
|
||||
{
|
||||
try
|
||||
{
|
||||
return SaleOperationResponse.OK(_mapper.Map<SaleViewModel>(_saleBusinessLogicContract.GetSaleByData(id)));
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return SaleOperationResponse.BadRequest("Data is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return SaleOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (ElementNotFoundException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementNotFoundException");
|
||||
return SaleOperationResponse.NotFound($"Not found element by data {id}");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return SaleOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return SaleOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public SaleOperationResponse MakeSale(SaleBindingModel saleModel)
|
||||
{
|
||||
try
|
||||
{
|
||||
var data = _mapper.Map<SaleDataModel>(saleModel);
|
||||
_saleBusinessLogicContract.InsertSale(_mapper.Map<SaleDataModel>(saleModel));
|
||||
return SaleOperationResponse.NoContent();
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return SaleOperationResponse.BadRequest("Data is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return SaleOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return SaleOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return SaleOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public SaleOperationResponse CancelSale(string id)
|
||||
{
|
||||
try
|
||||
{
|
||||
_saleBusinessLogicContract.CancelSale(id);
|
||||
return SaleOperationResponse.NoContent();
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return SaleOperationResponse.BadRequest("Id is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return SaleOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (ElementNotFoundException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementNotFoundException");
|
||||
return SaleOperationResponse.BadRequest($"Not found element by id: {id}");
|
||||
}
|
||||
catch (ElementDeletedException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementDeletedException");
|
||||
return SaleOperationResponse.BadRequest($"Element by id: {id} was deleted");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return SaleOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return SaleOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
12
SquirrelContract/SquirrelWebApi/AuthOptions.cs
Normal file
12
SquirrelContract/SquirrelWebApi/AuthOptions.cs
Normal file
@@ -0,0 +1,12 @@
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using System.Text;
|
||||
|
||||
namespace SquirrelWebApi;
|
||||
|
||||
public class AuthOptions
|
||||
{
|
||||
public const string ISSUER = "Squirrel_AuthServer"; // издатель токена
|
||||
public const string AUDIENCE = "Squirrel_AuthClient"; // потребитель токена
|
||||
const string KEY = "catsecret_secretsecretsecretkey!123"; // ключ для шифрации
|
||||
public static SymmetricSecurityKey GetSymmetricSecurityKey() => new(Encoding.UTF8.GetBytes(KEY));
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using SquirrelContract.AdapterContracts;
|
||||
using SquirrelContract.BindingModels;
|
||||
|
||||
namespace SquirrelWebApi.Controllers;
|
||||
|
||||
[Authorize]
|
||||
[Route("api/[controller]")]
|
||||
[ApiController]
|
||||
[Produces("application/json")]
|
||||
public class ClientsController(IClientAdapter adapter) : ControllerBase
|
||||
{
|
||||
private readonly IClientAdapter _adapter = adapter;
|
||||
|
||||
[HttpGet]
|
||||
public IActionResult GetAllRecords()
|
||||
{
|
||||
return _adapter.GetList().GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpGet("{data}")]
|
||||
public IActionResult GetRecord(string data)
|
||||
{
|
||||
return _adapter.GetElement(data).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
public IActionResult Register([FromBody] ClientBindingModel model)
|
||||
{
|
||||
return _adapter.RegisterClient(model).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpPut]
|
||||
public IActionResult ChangeInfo([FromBody] ClientBindingModel model)
|
||||
{
|
||||
return _adapter.ChangeClientInfo(model).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpDelete("{id}")]
|
||||
public IActionResult Delete(string id)
|
||||
{
|
||||
return _adapter.RemoveClient(id).GetResponse(Request, Response);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using SquirrelContract.AdapterContracts;
|
||||
using SquirrelContract.BindingModels;
|
||||
|
||||
namespace SquirrelWebApi.Controllers;
|
||||
|
||||
|
||||
[Authorize]
|
||||
[Route("api/[controller]/[action]")]
|
||||
[ApiController]
|
||||
[Produces("application/json")]
|
||||
public class CocktailsController(ICocktailAdapter adapter) : ControllerBase
|
||||
{
|
||||
private readonly ICocktailAdapter _adapter = adapter;
|
||||
|
||||
[HttpGet]
|
||||
public IActionResult GetRecords(bool includeDeleted)
|
||||
{
|
||||
return _adapter.GetList(includeDeleted).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
public IActionResult GetHistory(string id)
|
||||
{
|
||||
return _adapter.GetHistory(id).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpGet("{data}")]
|
||||
public IActionResult GetRecord(string data)
|
||||
{
|
||||
return _adapter.GetElement(data).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
public IActionResult Register([FromBody] CocktailBindingModel model)
|
||||
{
|
||||
return _adapter.RegisterCocktail(model).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpPut]
|
||||
public IActionResult ChangeInfo([FromBody] CocktailBindingModel model)
|
||||
{
|
||||
return _adapter.ChangeCocktailInfo(model).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpDelete("{id}")]
|
||||
public IActionResult Delete(string id)
|
||||
{
|
||||
return _adapter.RemoveCocktail(id).GetResponse(Request, Response);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using SquirrelContract.AdapterContracts;
|
||||
using SquirrelContract.BindingModels;
|
||||
|
||||
namespace SquirrelWebApi.Controllers;
|
||||
|
||||
[Authorize]
|
||||
[Route("api/[controller]/[action]")]
|
||||
[ApiController]
|
||||
[Produces("application/json")]
|
||||
public class EmployeesController(IEmployeeAdapter adapter) : ControllerBase
|
||||
{
|
||||
private readonly IEmployeeAdapter _adapter = adapter;
|
||||
|
||||
[HttpGet]
|
||||
public IActionResult GetRecords(bool includeDeleted = false)
|
||||
{
|
||||
return _adapter.GetList(includeDeleted).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
public IActionResult GetPostRecords(string id, bool includeDeleted = false)
|
||||
{
|
||||
return _adapter.GetPostList(id, includeDeleted).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
public IActionResult GetBirthDateRecords(DateTime fromDate, DateTime toDate, bool includeDeleted = false)
|
||||
{
|
||||
return _adapter.GetListByBirthDate(fromDate, toDate, includeDeleted).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
public IActionResult GetEmploymentRecords(DateTime fromDate, DateTime toDate, bool includeDeleted = false)
|
||||
{
|
||||
return _adapter.GetListByEmploymentDate(fromDate, toDate, includeDeleted).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpGet("{data}")]
|
||||
public IActionResult GetRecord(string data)
|
||||
{
|
||||
return _adapter.GetElement(data).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
public IActionResult Register([FromBody] EmployeeBindingModel model)
|
||||
{
|
||||
return _adapter.RegisterEmployee(model).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpPut]
|
||||
public IActionResult ChangeInfo([FromBody] EmployeeBindingModel model)
|
||||
{
|
||||
return _adapter.ChangeEmployeeInfo(model).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpDelete("{id}")]
|
||||
public IActionResult Delete(string id)
|
||||
{
|
||||
return _adapter.RemoveEmployee(id).GetResponse(Request, Response);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using SquirrelContract.AdapterContracts;
|
||||
|
||||
namespace SquirrelWebApi.Controllers;
|
||||
|
||||
[Authorize]
|
||||
[Route("api/[controller]")]
|
||||
[ApiController]
|
||||
[Produces("application/json")]
|
||||
public class PostHistoryController(IPostAdapter adapter) : ControllerBase
|
||||
{
|
||||
private readonly IPostAdapter _adapter = adapter;
|
||||
|
||||
[HttpGet("{id}")]
|
||||
public IActionResult GetHistory(string id)
|
||||
{
|
||||
return _adapter.GetHistory(id).GetResponse(Request, Response);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using SquirrelContract.AdapterContracts;
|
||||
using SquirrelContract.BindingModels;
|
||||
|
||||
namespace SquirrelWebApi.Controllers;
|
||||
|
||||
[Authorize]
|
||||
[Route("api/[controller]")]
|
||||
[ApiController]
|
||||
[Produces("application/json")]
|
||||
public class PostsController(IPostAdapter adapter) : ControllerBase
|
||||
{
|
||||
private readonly IPostAdapter _adapter = adapter;
|
||||
|
||||
[HttpGet]
|
||||
public IActionResult GetRecords()
|
||||
{
|
||||
return _adapter.GetList().GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpGet("{data}")]
|
||||
public IActionResult GetRecord(string data)
|
||||
{
|
||||
return _adapter.GetElement(data).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
public IActionResult Register([FromBody] PostBindingModel model)
|
||||
{
|
||||
return _adapter.RegisterPost(model).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpPut]
|
||||
public IActionResult ChangeInfo([FromBody] PostBindingModel model)
|
||||
{
|
||||
return _adapter.ChangePostInfo(model).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpDelete("{id}")]
|
||||
public IActionResult Delete(string id)
|
||||
{
|
||||
return _adapter.RemovePost(id).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpPatch("{id}")]
|
||||
public IActionResult Restore(string id)
|
||||
{
|
||||
return _adapter.RestorePost(id).GetResponse(Request, Response);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using SquirrelContract.AdapterContracts;
|
||||
|
||||
namespace SquirrelWebApi.Controllers;
|
||||
|
||||
[Authorize]
|
||||
[Route("api/[controller]/[action]")]
|
||||
[ApiController]
|
||||
[Produces("application/json")]
|
||||
public class SalaryController(ISalaryAdapter adapter) : ControllerBase
|
||||
{
|
||||
private readonly ISalaryAdapter _adapter = adapter;
|
||||
|
||||
[HttpGet]
|
||||
public IActionResult GetRecords(DateTime fromDate, DateTime toDate)
|
||||
{
|
||||
return _adapter.GetListByPeriod(fromDate, toDate).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
public IActionResult GetEmployeeRecords(string id, DateTime fromDate, DateTime toDate)
|
||||
{
|
||||
return _adapter.GetListByPeriodByEmployee(fromDate, toDate, id).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
public IActionResult Calculate(DateTime date)
|
||||
{
|
||||
return _adapter.CalculateSalary(date).GetResponse(Request, Response);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using SquirrelContract.AdapterContracts;
|
||||
using SquirrelContract.BindingModels;
|
||||
|
||||
namespace SquirrelWebApi.Controllers;
|
||||
|
||||
[Authorize]
|
||||
[Route("api/[controller]/[action]")]
|
||||
[ApiController]
|
||||
[Produces("application/json")]
|
||||
public class SalesController(ISaleAdapter adapter) : ControllerBase
|
||||
{
|
||||
private readonly ISaleAdapter _adapter = adapter;
|
||||
|
||||
[HttpGet]
|
||||
public IActionResult GetRecords(DateTime fromDate, DateTime toDate)
|
||||
{
|
||||
return _adapter.GetList(fromDate, toDate).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
public IActionResult GetEmployeeRecords(string id, DateTime fromDate, DateTime toDate)
|
||||
{
|
||||
return _adapter.GetEmployeeList(id, fromDate, toDate).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
public IActionResult GetClientRecords(string id, DateTime fromDate, DateTime toDate)
|
||||
{
|
||||
return _adapter.GetClientList(id, fromDate, toDate).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
public IActionResult GetCocktailRecords(string id, DateTime fromDate, DateTime toDate)
|
||||
{
|
||||
return _adapter.GetCocktailList(id, fromDate, toDate).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpGet("{data}")]
|
||||
public IActionResult GetRecord(string data)
|
||||
{
|
||||
return _adapter.GetElement(data).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
public IActionResult Sale([FromBody] SaleBindingModel model)
|
||||
{
|
||||
return _adapter.MakeSale(model).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpDelete("{id}")]
|
||||
public IActionResult Cancel(string id)
|
||||
{
|
||||
return _adapter.CancelSale(id).GetResponse(Request, Response);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace SquirrelWebApi.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Route("[controller]")]
|
||||
public class WeatherForecastController : ControllerBase
|
||||
{
|
||||
private static readonly string[] Summaries = new[]
|
||||
{
|
||||
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
|
||||
};
|
||||
|
||||
private readonly ILogger<WeatherForecastController> _logger;
|
||||
|
||||
public WeatherForecastController(ILogger<WeatherForecastController> logger)
|
||||
{
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
[HttpGet(Name = "GetWeatherForecast")]
|
||||
public IEnumerable<WeatherForecast> Get()
|
||||
{
|
||||
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
|
||||
{
|
||||
Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
|
||||
TemperatureC = Random.Shared.Next(-20, 55),
|
||||
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
|
||||
})
|
||||
.ToArray();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
using SquirrelContract.Infastructure;
|
||||
|
||||
namespace SquirrelWebApi.Infrastructure;
|
||||
|
||||
public class ConfigurationDatabase(IConfiguration configuration) : IConfigurationDatabase
|
||||
{
|
||||
private readonly Lazy<DataBaseSettings> _dataBaseSettings = new(() =>
|
||||
{
|
||||
return configuration.GetValue<DataBaseSettings>("DataBaseSettings") ?? throw new InvalidDataException(nameof(DataBaseSettings));
|
||||
});
|
||||
|
||||
public string ConnectionString => _dataBaseSettings.Value.ConnectionString;
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
namespace SquirrelWebApi.Infrastructure;
|
||||
|
||||
public class DataBaseSettings
|
||||
{
|
||||
public required string ConnectionString { get; set; }
|
||||
}
|
||||
109
SquirrelContract/SquirrelWebApi/Program.cs
Normal file
109
SquirrelContract/SquirrelWebApi/Program.cs
Normal file
@@ -0,0 +1,109 @@
|
||||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using Serilog;
|
||||
using SquirrelBusinessLogic.Implementations;
|
||||
using SquirrelContract.AdapterContracts;
|
||||
using SquirrelContract.BusinessLogicContracts;
|
||||
using SquirrelContract.Infastructure;
|
||||
using SquirrelContract.StoragesContracts;
|
||||
using SquirrelDatabase;
|
||||
using SquirrelDatabase.Implementations;
|
||||
using SquirrelWebApi;
|
||||
using SquirrelWebApi.Adapters;
|
||||
using SquirrelWebApi.Infrastructure;
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
using System.Security.Claims;
|
||||
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
|
||||
// Add services to the container.
|
||||
|
||||
builder.Services.AddControllers();
|
||||
using var loggerFactory = new LoggerFactory();
|
||||
loggerFactory.AddSerilog(new LoggerConfiguration().ReadFrom.Configuration(builder.Configuration).CreateLogger());
|
||||
builder.Services.AddSingleton(loggerFactory.CreateLogger("Any"));
|
||||
|
||||
builder.Services.AddAuthorization();
|
||||
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
|
||||
.AddJwtBearer(options =>
|
||||
{
|
||||
options.TokenValidationParameters = new TokenValidationParameters
|
||||
{
|
||||
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>, <20><><EFBFBD><EFBFBD><EFBFBD> <20><> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
|
||||
ValidateIssuer = true,
|
||||
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>, <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
|
||||
ValidIssuer = AuthOptions.ISSUER,
|
||||
// <20><><EFBFBD><EFBFBD><EFBFBD> <20><> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
|
||||
ValidateAudience = true,
|
||||
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
|
||||
ValidAudience = AuthOptions.AUDIENCE,
|
||||
// <20><><EFBFBD><EFBFBD><EFBFBD> <20><> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
|
||||
ValidateLifetime = true,
|
||||
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
|
||||
IssuerSigningKey = AuthOptions.GetSymmetricSecurityKey(),
|
||||
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
|
||||
ValidateIssuerSigningKey = true,
|
||||
};
|
||||
});
|
||||
|
||||
builder.Services.AddSingleton<IConfigurationDatabase, ConfigurationDatabase>();
|
||||
|
||||
builder.Services.AddTransient<IClientBusinessLogicContract, ClientBusinessLogicContract>();
|
||||
builder.Services.AddTransient<IPostBusinessLogicContract, PostBusinessLogicContract>();
|
||||
builder.Services.AddTransient<ICocktailBusinessLogicContract, CocktailBusinessLogicContract>();
|
||||
builder.Services.AddTransient<ISalaryBusinessLogicContract, SalaryBusinessLogicContract>();
|
||||
builder.Services.AddTransient<ISaleBusinessLogicContract, SaleBusinessLogicContract>();
|
||||
builder.Services.AddTransient<IEmployeeBusinessLogicContract, EmployeeBusinessLogicContract>();
|
||||
|
||||
builder.Services.AddTransient<SquirrelDbContext>();
|
||||
builder.Services.AddTransient<IClientStorageContract, ClientStorageContract>();
|
||||
builder.Services.AddTransient<IPostStorageContract, PostStorageContract>();
|
||||
builder.Services.AddTransient<ICocktailStorageContract, CocktailStorageContract>();
|
||||
builder.Services.AddTransient<ISalaryStorageContract, SalaryStorageContract>();
|
||||
builder.Services.AddTransient<ISaleStorageContract, SaleStorageContract>();
|
||||
builder.Services.AddTransient<IEmployeeStorageContract, EmployeeStorageContract>();
|
||||
|
||||
builder.Services.AddTransient<IClientAdapter, ClientAdapter>();
|
||||
builder.Services.AddTransient<IPostAdapter, PostAdapter>();
|
||||
builder.Services.AddTransient<ICocktailAdapter, CocktailAdapter>();
|
||||
builder.Services.AddTransient<ISaleAdapter, SaleAdapter>();
|
||||
builder.Services.AddTransient<IEmployeeAdapter, EmployeeAdapter>();
|
||||
builder.Services.AddTransient<ISalaryAdapter, SalaryAdapter>();
|
||||
|
||||
builder.Services.AddOpenApi();
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
// Configure the HTTP request pipeline.
|
||||
if (app.Environment.IsDevelopment())
|
||||
{
|
||||
app.MapOpenApi();
|
||||
}
|
||||
if (app.Environment.IsProduction())
|
||||
{
|
||||
var dbContext = app.Services.GetRequiredService<SquirrelDbContext>();
|
||||
if (dbContext.Database.CanConnect())
|
||||
{
|
||||
dbContext.Database.EnsureCreated();
|
||||
dbContext.Database.Migrate();
|
||||
}
|
||||
}
|
||||
|
||||
app.UseHttpsRedirection();
|
||||
app.UseAuthentication();
|
||||
app.UseAuthorization();
|
||||
|
||||
app.Map("/login/{username}", (string username) =>
|
||||
{
|
||||
return new JwtSecurityTokenHandler().WriteToken(new JwtSecurityToken(
|
||||
issuer: AuthOptions.ISSUER,
|
||||
audience: AuthOptions.AUDIENCE,
|
||||
claims: [new(ClaimTypes.Name, username)],
|
||||
expires: DateTime.UtcNow.Add(TimeSpan.FromMinutes(2)),
|
||||
signingCredentials: new SigningCredentials(AuthOptions.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256)));
|
||||
});
|
||||
|
||||
app.MapControllers();
|
||||
|
||||
app.Run();
|
||||
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"$schema": "https://json.schemastore.org/launchsettings.json",
|
||||
"profiles": {
|
||||
"http": {
|
||||
"commandName": "Project",
|
||||
"dotnetRunMessages": true,
|
||||
"launchBrowser": false,
|
||||
"applicationUrl": "http://localhost:5086",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
},
|
||||
"https": {
|
||||
"commandName": "Project",
|
||||
"dotnetRunMessages": true,
|
||||
"launchBrowser": false,
|
||||
"applicationUrl": "https://localhost:7009;http://localhost:5086",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
29
SquirrelContract/SquirrelWebApi/SquirrelWebApi.csproj
Normal file
29
SquirrelContract/SquirrelWebApi/SquirrelWebApi.csproj
Normal file
@@ -0,0 +1,29 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net9.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="9.0.3" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="9.0.3" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="9.0.2" />
|
||||
<PackageReference Include="Microsoft.IdentityModel.Tokens" Version="8.6.1" />
|
||||
<PackageReference Include="Serilog.AspNetCore" Version="9.0.0" />
|
||||
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="8.6.1" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\SquirrelBusinessLogic\SquirrelBusinessLogic.csproj" />
|
||||
<ProjectReference Include="..\SquirrelContract\SquirrelContract.csproj" />
|
||||
<ProjectReference Include="..\SquirrelDatabase\SquirrelDatabase.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<InternalsVisibleTo Include="SquirrelTests" />
|
||||
<InternalsVisibleTo Include="DynamicProxyGenAssembly2" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
6
SquirrelContract/SquirrelWebApi/SquirrelWebApi.http
Normal file
6
SquirrelContract/SquirrelWebApi/SquirrelWebApi.http
Normal file
@@ -0,0 +1,6 @@
|
||||
@SquirrelWebApi_HostAddress = http://localhost:5086
|
||||
|
||||
GET {{SquirrelWebApi_HostAddress}}/weatherforecast/
|
||||
Accept: application/json
|
||||
|
||||
###
|
||||
13
SquirrelContract/SquirrelWebApi/WeatherForecast.cs
Normal file
13
SquirrelContract/SquirrelWebApi/WeatherForecast.cs
Normal file
@@ -0,0 +1,13 @@
|
||||
namespace SquirrelWebApi
|
||||
{
|
||||
public class WeatherForecast
|
||||
{
|
||||
public DateOnly Date { get; set; }
|
||||
|
||||
public int TemperatureC { get; set; }
|
||||
|
||||
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
|
||||
|
||||
public string? Summary { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
}
|
||||
}
|
||||
}
|
||||
28
SquirrelContract/SquirrelWebApi/appsettings.json
Normal file
28
SquirrelContract/SquirrelWebApi/appsettings.json
Normal file
@@ -0,0 +1,28 @@
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
}
|
||||
},
|
||||
"Serilog": {
|
||||
"Using": [ "Serilog.Sinks.File" ],
|
||||
"MinimumLevel": {
|
||||
"Default": "Information"
|
||||
},
|
||||
"WriteTo": [
|
||||
{
|
||||
"Name": "File",
|
||||
"Args": {
|
||||
"path": "../logs/squirrel-.log",
|
||||
"rollingInterval": "Day",
|
||||
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} {CorrelationId} {Level:u3} {Username} {Message:lj}{Exception}{NewLine}"
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"AllowedHosts": "*",
|
||||
//"DataBaseSettings": {
|
||||
// "ConnectionString": "Host=127.0.0.1;Port=5432;Database=Squirrel;Username=postgres;Password=postgres;"
|
||||
//}
|
||||
}
|
||||
Reference in New Issue
Block a user