Compare commits

..

14 Commits

129 changed files with 5927 additions and 2489 deletions

View File

@@ -1,74 +0,0 @@
using MagicCarpetContracts.BusinessLogicContracts;
using MagicCarpetContracts.DataModels;
using MagicCarpetContracts.Enums;
using MagicCarpetContracts.Exceptions;
using MagicCarpetContracts.Extensions;
using MagicCarpetContracts.StoragesContracts;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
namespace MagicCarpetBusinessLogic.Implementations;
public class AgencyBusinessLogicContract(IAgencyStorageContract agencyStorageContract, ILogger logger) : IAgencyBusinessLogicContract
{
private readonly IAgencyStorageContract _agencyStorageContract = agencyStorageContract;
private readonly ILogger _logger = logger;
public List<AgencyDataModel> GetAllComponents()
{
_logger.LogInformation("GetAllComponents");
return _agencyStorageContract.GetList() ?? throw new NullListException();
return [];
}
public AgencyDataModel GetComponentByData(string data)
{
_logger.LogInformation("Get element by data: {data}", data);
if (data.IsEmpty())
{
throw new ArgumentNullException(nameof(data));
}
if (!data.IsGuid())
{
throw new ElementNotFoundException(data);
}
return _agencyStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data);
return new("", TourType.None, 0, []);
}
public void InsertComponent(AgencyDataModel agencyDataModel)
{
_logger.LogInformation("New data: {json}", JsonSerializer.Serialize(agencyDataModel));
ArgumentNullException.ThrowIfNull(agencyDataModel);
agencyDataModel.Validate();
_agencyStorageContract.AddElement(agencyDataModel);
}
public void UpdateComponent(AgencyDataModel agencyDataModel)
{
_logger.LogInformation("Update data: {json}", JsonSerializer.Serialize(agencyDataModel));
ArgumentNullException.ThrowIfNull(agencyDataModel);
agencyDataModel.Validate();
_agencyStorageContract.UpdElement(agencyDataModel);
}
public void DeleteComponent(string id)
{
logger.LogInformation("Delete by id: {id}", id);
if (id.IsEmpty())
{
throw new ArgumentNullException(nameof(id));
}
if (!id.IsGuid())
{
throw new ValidationException("Id is not a unique identifier");
}
_agencyStorageContract.DelElement(id);
}
}

View File

@@ -14,7 +14,7 @@ using System.Threading.Tasks;
namespace MagicCarpetBusinessLogic.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;

View File

@@ -14,7 +14,7 @@ using System.Threading.Tasks;
namespace MagicCarpetBusinessLogic.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;

View File

@@ -12,14 +12,14 @@ using System.Text.Json;
using System.Threading.Tasks;
namespace MagicCarpetBusinessLogic.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)

View File

@@ -11,7 +11,7 @@ using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetBusinessLogic.Implementations;
internal class SalaryBusinessLogicContract(ISalaryStorageContract salaryStorageContract,ISaleStorageContract saleStorageContract,
public class SalaryBusinessLogicContract(ISalaryStorageContract salaryStorageContract,ISaleStorageContract saleStorageContract,
IPostStorageContract postStorageContract, IEmployeeStorageContract employeeStorageContract, ILogger logger) : ISalaryBusinessLogicContract
{
private readonly ILogger _logger = logger;
@@ -61,7 +61,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));
}
}
}

View File

@@ -13,11 +13,10 @@ using System.Threading.Tasks;
namespace MagicCarpetBusinessLogic.Implementations;
internal class SaleBusinessLogicContract(ISaleStorageContract saleStorageContract, IAgencyStorageContract agencyStorageContract, ILogger logger) : ISaleBusinessLogicContract
public class SaleBusinessLogicContract(ISaleStorageContract saleStorageContract, ILogger logger) : ISaleBusinessLogicContract
{
private readonly ILogger _logger = logger;
private readonly ISaleStorageContract _saleStorageContract = saleStorageContract;
private readonly IAgencyStorageContract _agencyStorageContract = agencyStorageContract;
public List<SaleDataModel> GetAllSalesByPeriod(DateTime fromDate, DateTime toDate)
{
@@ -102,10 +101,6 @@ internal class SaleBusinessLogicContract(ISaleStorageContract saleStorageContrac
_logger.LogInformation("New data: {json}", JsonSerializer.Serialize(saleDataModel));
ArgumentNullException.ThrowIfNull(saleDataModel);
saleDataModel.Validate();
if (!_agencyStorageContract.CheckComponents(saleDataModel))
{
throw new InsufficientException("Dont have tour in agency");
}
_saleStorageContract.AddElement(saleDataModel);
}

View File

@@ -1,61 +0,0 @@
using MagicCarpetContracts.BusinessLogicContracts;
using MagicCarpetContracts.DataModels;
using MagicCarpetContracts.Enums;
using MagicCarpetContracts.Exceptions;
using MagicCarpetContracts.Extensions;
using MagicCarpetContracts.StoragesContracts;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
namespace MagicCarpetBusinessLogic.Implementations;
public class SuppliesBusinessLogicContract(ISuppliesStorageContract suppliesStorageContract, ILogger logger) : ISuppliesBusinessLogicContract
{
private readonly ISuppliesStorageContract _suppliesStorageContract = suppliesStorageContract;
private readonly ILogger _logger = logger;
public List<SuppliesDataModel> GetAllComponents()
{
_logger.LogInformation("GetAllComponents");
return _suppliesStorageContract.GetList() ?? throw new NullListException();
return [];
}
public SuppliesDataModel GetComponentByData(string data)
{
_logger.LogInformation("Get element by data: {data}", data);
if (data.IsEmpty())
{
throw new ArgumentNullException(nameof(data));
}
if (!data.IsGuid())
{
throw new ElementNotFoundException(data);
}
return _suppliesStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data);
return new("", TourType.None, DateTime.UtcNow, 0, []);
}
public void InsertComponent(SuppliesDataModel suppliesDataModel)
{
_logger.LogInformation("New data: {json}", JsonSerializer.Serialize(suppliesDataModel));
ArgumentNullException.ThrowIfNull(suppliesDataModel);
suppliesDataModel.Validate();
_suppliesStorageContract.AddElement(suppliesDataModel);
}
public void UpdateComponent(SuppliesDataModel suppliesDataModel)
{
_logger.LogInformation("Update data: {json}", JsonSerializer.Serialize(suppliesDataModel));
ArgumentNullException.ThrowIfNull(suppliesDataModel);
suppliesDataModel.Validate();
_suppliesStorageContract.UpdElement(suppliesDataModel);
}
}

View File

@@ -13,7 +13,7 @@ using System.Threading.Tasks;
namespace MagicCarpetBusinessLogic.Implementations;
internal class TourBusinessLogicContract(ITourStorageContract tourStorageContract, ILogger logger) : ITourBusinessLogicContract
public class TourBusinessLogicContract(ITourStorageContract tourStorageContract, ILogger logger) : ITourBusinessLogicContract
{
private readonly ILogger _logger = logger;
private readonly ITourStorageContract _tourStorageContract = tourStorageContract;
@@ -56,6 +56,7 @@ internal class TourBusinessLogicContract(ITourStorageContract tourStorageContrac
_logger.LogInformation("New data: {json}", JsonSerializer.Serialize(tourDataModel));
ArgumentNullException.ThrowIfNull(tourDataModel);
tourDataModel.Validate();
_tourStorageContract.AddElement(tourDataModel);
}
public void UpdateTour(TourDataModel tourDataModel)
@@ -63,6 +64,7 @@ internal class TourBusinessLogicContract(ITourStorageContract tourStorageContrac
_logger.LogInformation("Update data: {json}", JsonSerializer.Serialize(tourDataModel));
ArgumentNullException.ThrowIfNull(tourDataModel);
tourDataModel.Validate();
_tourStorageContract.UpdElement(tourDataModel);
}
public void DeleteTour(string id)

View File

@@ -7,6 +7,7 @@
</PropertyGroup>
<ItemGroup>
<InternalsVisibleTo Include="MagicCarpetTests" />
<InternalsVisibleTo Include="MagicCarpetWebApi" />
<InternalsVisibleTo Include="DynamicProxyGenAssembly2" />
</ItemGroup>
<ItemGroup>

View File

@@ -0,0 +1,22 @@
using MagicCarpetContracts.AdapterContracts.OperationResponses;
using MagicCarpetContracts.BindingModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetContracts.AdapterContracts;
public interface IClientAdapter
{
ClientOperationResponse GetList();
ClientOperationResponse GetElement(string data);
ClientOperationResponse RegisterClient(ClientBindingModel clientModel);
ClientOperationResponse ChangeClientInfo(ClientBindingModel clientModel);
ClientOperationResponse RemoveClient(string id);
}

View File

@@ -0,0 +1,28 @@
using MagicCarpetContracts.AdapterContracts.OperationResponses;
using MagicCarpetContracts.BindingModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetContracts.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);
}

View File

@@ -0,0 +1,26 @@
using MagicCarpetContracts.AdapterContracts.OperationResponses;
using MagicCarpetContracts.BindingModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetContracts.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);
}

View File

@@ -0,0 +1,15 @@
using MagicCarpetContracts.AdapterContracts.OperationResponses;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetContracts.AdapterContracts;
public interface ISalaryAdapter
{
SalaryOperationResponse GetListByPeriod(DateTime fromDate, DateTime toDate);
SalaryOperationResponse GetListByPeriodByEmployee(DateTime fromDate, DateTime toDate, string employeeId);
SalaryOperationResponse CalculateSalary(DateTime date);
}

View File

@@ -0,0 +1,26 @@
using MagicCarpetContracts.AdapterContracts.OperationResponses;
using MagicCarpetContracts.BindingModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetContracts.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 GetTourList(string id, DateTime fromDate, DateTime toDate);
SaleOperationResponse GetElement(string id);
SaleOperationResponse MakeSale(SaleBindingModel saleModel);
SaleOperationResponse CancelSale(string id);
}

View File

@@ -0,0 +1,24 @@
using MagicCarpetContracts.AdapterContracts.OperationResponses;
using MagicCarpetContracts.BindingModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetContracts.AdapterContracts;
public interface ITourAdapter
{
TourOperationResponse GetList(bool includeDeleted);
TourOperationResponse GetHistory(string id);
TourOperationResponse GetElement(string data);
TourOperationResponse RegisterTour(TourBindingModel tourModel);
TourOperationResponse ChangeTourInfo(TourBindingModel tourModel);
TourOperationResponse RemoveTour(string id);
}

View File

@@ -0,0 +1,24 @@
using MagicCarpetContracts.Infrastructure;
using MagicCarpetContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetContracts.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);
}

View File

@@ -0,0 +1,24 @@
using MagicCarpetContracts.Infrastructure;
using MagicCarpetContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetContracts.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);
}

View File

@@ -0,0 +1,24 @@
using MagicCarpetContracts.Infrastructure;
using MagicCarpetContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetContracts.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);
}

View File

@@ -0,0 +1,18 @@
using MagicCarpetContracts.Infrastructure;
using MagicCarpetContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetContracts.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);
}

View File

@@ -0,0 +1,24 @@
using MagicCarpetContracts.Infrastructure;
using MagicCarpetContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetContracts.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);
}

View File

@@ -0,0 +1,26 @@
using MagicCarpetContracts.Infrastructure;
using MagicCarpetContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetContracts.AdapterContracts.OperationResponses;
public class TourOperationResponse : OperationResponse
{
public static TourOperationResponse OK(List<TourViewModel> data) => OK<TourOperationResponse, List<TourViewModel>>(data);
public static TourOperationResponse OK(List<TourHistoryViewModel> data) => OK<TourOperationResponse, List<TourHistoryViewModel>>(data);
public static TourOperationResponse OK(TourViewModel data) => OK<TourOperationResponse, TourViewModel>(data);
public static TourOperationResponse NoContent() => NoContent<TourOperationResponse>();
public static TourOperationResponse NotFound(string message) => NotFound<TourOperationResponse>(message);
public static TourOperationResponse BadRequest(string message) => BadRequest<TourOperationResponse>(message);
public static TourOperationResponse InternalServerError(string message) => InternalServerError<TourOperationResponse>(message);
}

View File

@@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetContracts.BindingModels;
public class ClientBindingModel
{
public string? Id { get; set; }
public string? FIO { get; set; }
public string? PhoneNumber { get; set; }
public double DiscountSize { get; set; }
}

View File

@@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetContracts.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; }
}

View File

@@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetContracts.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; }
}

View File

@@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetContracts.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<SaleTourBindingModel>? Tours { get; set; }
}

View File

@@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetContracts.BindingModels;
public class SaleTourBindingModel
{
public string? SaleId { get; set; }
public string? TourId { get; set; }
public int Count { get; set; }
public double Price { get; set; }
}

View File

@@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetContracts.BindingModels;
public class TourBindingModel
{
public string? Id { get; set; }
public string? TourName { get; set; }
public string? TourCountry { get; set; }
public double Price { get; set; }
public string? TourType { get; set; }
}

View File

@@ -1,17 +0,0 @@
using MagicCarpetContracts.DataModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetContracts.BusinessLogicContracts;
public interface IAgencyBusinessLogicContract
{
List<AgencyDataModel> GetAllComponents();
AgencyDataModel GetComponentByData(string data);
void InsertComponent(AgencyDataModel agencyDataModel);
void UpdateComponent(AgencyDataModel agencyDataModel);
void DeleteComponent(string id);
}

View File

@@ -9,7 +9,7 @@ namespace MagicCarpetContracts.BuisnessLogicContracts;
public interface IPostBusinessLogicContract
{
List<PostDataModel> GetAllPosts(bool onlyActive);
List<PostDataModel> GetAllPosts();
List<PostDataModel> GetAllDataOfPost(string postId);

View File

@@ -1,16 +0,0 @@
using MagicCarpetContracts.DataModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetContracts.BusinessLogicContracts;
public interface ISuppliesBusinessLogicContract
{
List<SuppliesDataModel> GetAllComponents();
SuppliesDataModel GetComponentByData(string data);
void InsertComponent(SuppliesDataModel componentDataModel);
void UpdateComponent(SuppliesDataModel componentDataModel);
}

View File

@@ -1,33 +0,0 @@
using MagicCarpetContracts.Enums;
using MagicCarpetContracts.Exceptions;
using MagicCarpetContracts.Extensions;
using MagicCarpetContracts.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetContracts.DataModels;
public class AgencyDataModel(string id, TourType tourType, int count, List<TourAgencyDataModel> tours) : IValidation
{
public string Id { get; private set; } = id;
public TourType Type { get; private set; } = tourType;
public int Count { get; private set; } = count;
public List<TourAgencyDataModel> Tours { get; private set; } = tours;
public void Validate()
{
if (Id.IsEmpty())
throw new ValidationException("Field Id is empty");
if (!Id.IsGuid())
throw new ValidationException("The value in the field Id is not a unique identifier");
if (Type == TourType.None)
throw new ValidationException("Field Type is empty");
if (Count <= 0)
throw new ValidationException("Field Count is less than or equal to 0");
if ((Tours?.Count ?? 0) == 0)
throw new ValidationException("The sale must include tours");
}
}

View File

@@ -1,6 +1,7 @@
using MagicCarpetContracts.Exceptions;
using MagicCarpetContracts.Extensions;
using MagicCarpetContracts.Infrastructure;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -12,6 +13,8 @@ namespace MagicCarpetContracts.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;
@@ -26,6 +29,17 @@ 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())

View File

@@ -10,14 +10,12 @@ using System.Threading.Tasks;
namespace MagicCarpetContracts.DataModels;
public class PostDataModel(string id, string postName, PostType postType, double salary, bool isActual, DateTime changeDate) : IValidation
public class PostDataModel(string postId, string postName, PostType postType, double salary) : IValidation
{
public string Id { get; private set; } = id;
public string Id { get; private set; } = postId;
public string PostName { get; private set; } = postName;
public PostType PostType { get; private set; } = postType;
public double Salary { get; private set; } = salary;
public bool IsActual { get; private set; } = isActual;
public DateTime ChangeDate { get; private set; } = changeDate;
public double Salary { get; private set; } = salary;
public void Validate()
{

View File

@@ -11,12 +11,20 @@ namespace MagicCarpetContracts.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())

View File

@@ -10,25 +10,78 @@ using System.Threading.Tasks;
namespace MagicCarpetContracts.DataModels;
public class SaleDataModel(string id, string employeeId, string? clientId, double sum, DiscountType discountType,
double discount, bool isCancel, List<SaleTourDataModel> saleTours) : 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 DiscountType DiscountType { get; private set; } = discountType;
public double Sum { get; private set; }
public double Discount { get; private set; } = discount;
public DiscountType DiscountType { get; private set; }
public bool IsCancel { get; private set; } = isCancel;
public double Discount { get; private set; }
public List<SaleTourDataModel> Tours { get; private set; } = saleTours;
public bool IsCancel { get; private set; }
public List<SaleTourDataModel>? Tours { 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<SaleTourDataModel> saleTours)
{
Id = id;
EmployeeId = employeeId;
ClientId = clientId;
DiscountType = discountType;
IsCancel = isCancel;
Tours = saleTours;
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 = Tours?.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<SaleTourDataModel> saleTours, EmployeeDataModel employee, ClientDataModel? client) : this(id, employeeId, clientId, discountType, isCancel, saleTours)
{
Sum = sum;
Discount = discount;
_employee = employee;
_client = client;
}
public SaleDataModel(string id, string employeeId, string? clientId, int discountType,
List<SaleTourDataModel> tours) : this(id, employeeId, clientId, (DiscountType)discountType, false, tours) { }
public void Validate()
{

View File

@@ -3,20 +3,32 @@ using MagicCarpetContracts.Extensions;
using MagicCarpetContracts.Infrastructure;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetContracts.DataModels;
public class SaleTourDataModel(string saleId, string tourId, int count) : IValidation
public class SaleTourDataModel(string saleId, string tourId, int count, double price) : IValidation
{
private readonly TourDataModel? _tour;
public string SaleId { get; private set; } = saleId;
public string TourId { get; private set; } = tourId;
public int Count { get; private set; } = count;
public double Price { get; private set; } = price;
public string TourName => _tour?.TourName ?? string.Empty;
public SaleTourDataModel(string saleId, string tourId, int count, double price, TourDataModel tour) : this(saleId, tourId, count, price)
{
_tour = tour;
}
public void Validate()
{
if (SaleId.IsEmpty())
@@ -33,5 +45,8 @@ public class SaleTourDataModel(string saleId, string tourId, int count) : IValid
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");
}
}

View File

@@ -1,35 +0,0 @@
using MagicCarpetContracts.Enums;
using MagicCarpetContracts.Exceptions;
using MagicCarpetContracts.Extensions;
using MagicCarpetContracts.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Runtime.InteropServices.JavaScript.JSType;
namespace MagicCarpetContracts.DataModels;
public class SuppliesDataModel(string id, TourType tourType, DateTime date, int count, List<TourSuppliesDataModel> tours) : IValidation
{
public string Id { get; private set; } = id;
public TourType Type { get; private set; } = tourType;
public DateTime ProductuionDate { get; private set; } = date;
public int Count { get; private set; } = count;
public List<TourSuppliesDataModel> Tours { get; private set; } = tours;
public void Validate()
{
if (Id.IsEmpty())
throw new ValidationException("Field Id is empty");
if (!Id.IsGuid())
throw new ValidationException("The value in the field Id is not a unique identifier");
if (Type == TourType.None)
throw new ValidationException("Field Type is empty");
if (Count <= 0)
throw new ValidationException("Field Count is less than or equal to 0");
if ((Tours?.Count ?? 0) == 0)
throw new ValidationException("The sale must include tours");
}
}

View File

@@ -1,32 +0,0 @@
using MagicCarpetContracts.Exceptions;
using MagicCarpetContracts.Extensions;
using MagicCarpetContracts.Infrastructure;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetContracts.DataModels;
public class TourAgencyDataModel(string agencyId, string tourId, int count) : IValidation
{
public string AgencyId { get; private set; } = agencyId;
public string TourId { get; private set; } = tourId;
public int Count { get; private set; } = count;
public void Validate()
{
if (AgencyId.IsEmpty())
throw new ValidationException("Field AgencyId is empty");
if (!AgencyId.IsGuid())
throw new ValidationException("The value in the field AgencyId is not a unique identifier");
if (TourId.IsEmpty())
throw new ValidationException("Field TourId is empty");
if (!TourId.IsGuid())
throw new ValidationException("The value in the field TourId is not a unique identifier");
if (Count <= 0)
throw new ValidationException("Field Count is less than or equal to 0");
}
}

View File

@@ -11,12 +11,22 @@ namespace MagicCarpetContracts.DataModels;
public class TourHistoryDataModel(string tourId, double oldPrice) : IValidation
{
private readonly TourDataModel? _tour;
public string TourId { get; private set; } = tourId;
public double OldPrice { get; private set; } = oldPrice;
public DateTime ChangeDate { get; private set; } = DateTime.UtcNow;
public string TourName => _tour?.TourName ?? string.Empty;
public TourHistoryDataModel(string tourId, double oldPrice, DateTime changeDate, TourDataModel tour) : this(tourId, oldPrice)
{
ChangeDate = changeDate;
_tour = tour;
}
public void Validate()
{
if (TourId.IsEmpty())

View File

@@ -1,32 +0,0 @@
using MagicCarpetContracts.Exceptions;
using MagicCarpetContracts.Extensions;
using MagicCarpetContracts.Infrastructure;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetContracts.DataModels;
public class TourSuppliesDataModel(string suppliesId, string tourId, int count) : IValidation
{
public string SuppliesId { get; private set; } = suppliesId;
public string TourId { get; private set; } = tourId;
public int Count { get; private set; } = count;
public void Validate()
{
if (SuppliesId.IsEmpty())
throw new ValidationException("Field SuppliesId is empty");
if (!SuppliesId.IsGuid())
throw new ValidationException("The value in the field SuppliesId is not a unique identifier");
if (TourId.IsEmpty())
throw new ValidationException("Field TourId is empty");
if (!TourId.IsGuid())
throw new ValidationException("The value in the field BlandId is not a unique identifier");
if (Count <= 0)
throw new ValidationException("Field Count is less than or equal to 0");
}
}

View File

@@ -1,11 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetContracts.Exceptions;
public class InsufficientException(string message) : Exception(message)
{
}

View File

@@ -0,0 +1,47 @@
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetContracts.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 };
}

View File

@@ -6,4 +6,10 @@
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Http.Abstractions" Version="2.3.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Abstractions" Version="2.3.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Core" Version="2.3.0" />
</ItemGroup>
</Project>

View File

@@ -1,18 +0,0 @@
using MagicCarpetContracts.DataModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetContracts.StoragesContracts;
public interface IAgencyStorageContract
{
List<AgencyDataModel> GetList();
AgencyDataModel GetElementById(string id);
void AddElement(AgencyDataModel agencyDataModel);
void UpdElement(AgencyDataModel agencyDataModel);
void DelElement(string id);
bool CheckComponents(SaleDataModel saleDataModel);
}

View File

@@ -9,7 +9,7 @@ namespace MagicCarpetContracts.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);

View File

@@ -9,7 +9,7 @@ namespace MagicCarpetContracts.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);
}

View File

@@ -1,16 +0,0 @@
using MagicCarpetContracts.DataModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetContracts.StoragesContracts;
public interface ISuppliesStorageContract
{
List<SuppliesDataModel> GetList(DateTime? startDate = null);
SuppliesDataModel GetElementById(string id);
void AddElement(SuppliesDataModel suppliesDataModel);
void UpdElement(SuppliesDataModel suppliesDataModel);
}

View File

@@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetContracts.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; }
}

View File

@@ -0,0 +1,26 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetContracts.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; }
}

View File

@@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetContracts.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; }
}

View File

@@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetContracts.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; }
}

View File

@@ -4,13 +4,15 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetDatabase.Models;
namespace MagicCarpetContracts.ViewModels;
public class TourAgency
public class SaleTourViewModel
{
public required string AgencyId { get; set; }
public required string TourId { get; set; }
public required string TourName { get; set; }
public int Count { get; set; }
public Agency? Agencies { get; set; }
public Tour? Tours { get; set; }
public double Price { get; set; }
}

View File

@@ -0,0 +1,32 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetContracts.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<SaleTourViewModel> Tours { get; set; }
}

View File

@@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetContracts.ViewModels;
public class TourHistoryViewModel
{
public required string TourName { get; set; }
public double OldPrice { get; set; }
public DateTime ChangeDate { get; set; }
}

View File

@@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetContracts.ViewModels;
public class TourViewModel
{
public required string Id { get; set; }
public required string TourName { get; set; }
public required string TourType { get; set; }
public string? TourCountry { get; set; }
public double Price { get; set; }
}

View File

@@ -1,148 +0,0 @@
using AutoMapper;
using MagicCarpetContracts.DataModels;
using MagicCarpetContracts.Exceptions;
using MagicCarpetContracts.StoragesContracts;
using MagicCarpetDatabase.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetDatabase.Implementations;
public class AgencyStorageContract : IAgencyStorageContract
{
private readonly MagicCarpetDbContext _dbContext;
private readonly Mapper _mapper;
public AgencyStorageContract(MagicCarpetDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Agency, AgencyDataModel>()
.ConstructUsing(src => new AgencyDataModel(
src.Id,
src.Type,
src.Count,
_mapper.Map<List<TourAgencyDataModel>>(src.Tours)
));
cfg.CreateMap<AgencyDataModel, Agency>();
cfg.CreateMap<TourAgencyDataModel, TourAgency>().ReverseMap();
});
_mapper = new Mapper(config);
}
public List<AgencyDataModel> GetList()
{
try
{
return [.. _dbContext.Agencies.Select(x => _mapper.Map<AgencyDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public AgencyDataModel GetElementById(string id)
{
try
{
return _mapper.Map<AgencyDataModel>(GetAgencyById(id));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void AddElement(AgencyDataModel agencyDataModel)
{
try
{
_dbContext.Agencies.Add(_mapper.Map<Agency>(agencyDataModel));
_dbContext.SaveChanges();
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void UpdElement(AgencyDataModel agencyDataModel)
{
try
{
var element = GetAgencyById(agencyDataModel.Id) ?? throw new ElementNotFoundException(agencyDataModel.Id);
_dbContext.Agencies.Update(_mapper.Map(agencyDataModel, element));
_dbContext.SaveChanges();
}
catch (ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void DelElement(string id)
{
try
{
var element = GetAgencyById(id) ?? throw new ElementNotFoundException(id);
_dbContext.Agencies.Remove(element);
_dbContext.SaveChanges();
}
catch (ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public bool CheckComponents(SaleDataModel saleDataModel)
{
using (var transaction = _dbContext.Database.BeginTransaction())
{
foreach (SaleTourDataModel sale_tour in saleDataModel.Tours)
{
var tour = _dbContext.Tours.FirstOrDefault(x => x.Id == sale_tour.TourId);
var agency = _dbContext.Agencies.FirstOrDefault(x => x.Type == tour.TourType && x.Count >= sale_tour.Count);
if (agency == null)
{
transaction.Rollback();
return false;
}
if (agency.Count - sale_tour.Count == 0)
{
DelElement(agency.Id);
}
else
{
agency.Count -= sale_tour.Count;
}
}
transaction.Commit();
_dbContext.SaveChanges();
return true;
}
}
private Agency? GetAgencyById(string id) => _dbContext.Agencies.FirstOrDefault(x => x.Id == id);
}

View File

@@ -13,11 +13,11 @@ using System.Threading.Tasks;
namespace MagicCarpetDatabase.Implementations;
internal class ClientStorageContarct : IClientStorageContract
public class ClientStorageContract : IClientStorageContract
{
private readonly MagicCarpetDbContext _dbContext;
private readonly Mapper _mapper;
public ClientStorageContarct(MagicCarpetDbContext magicCarpetDbContext)
public ClientStorageContract(MagicCarpetDbContext magicCarpetDbContext)
{
_dbContext = magicCarpetDbContext;
var config = new MapperConfiguration(cfg =>

View File

@@ -11,7 +11,7 @@ using System.Threading.Tasks;
namespace MagicCarpetDatabase.Implementations;
internal class EmployeeStorageContract : IEmployeeStorageContract
public class EmployeeStorageContract : IEmployeeStorageContract
{
private readonly MagicCarpetDbContext _dbContext;
private readonly Mapper _mapper;
@@ -21,10 +21,14 @@ internal class EmployeeStorageContract : IEmployeeStorageContract
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.AddMaps(typeof(MagicCarpetDbContext).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);
}
public List<EmployeeDataModel> GetList(bool onlyActive = true, string? postId = null, DateTime? fromBirthDate = null, DateTime? toBirthDate = null, DateTime? fromEmploymentDate = null, DateTime? toEmploymentDate = null)
{
try
@@ -40,13 +44,13 @@ internal 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)
{
@@ -72,7 +76,7 @@ internal 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)
{
@@ -80,11 +84,12 @@ internal class EmployeeStorageContract : IEmployeeStorageContract
throw new StorageException(ex);
}
}
public EmployeeDataModel? GetElementByEmail(string email)
{
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)
{
@@ -152,5 +157,12 @@ internal 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));
}

View File

@@ -13,7 +13,7 @@ using System.Threading.Tasks;
namespace MagicCarpetDatabase.Implementations;
internal class PostStorageContract : IPostStorageContract
public class PostStorageContract : IPostStorageContract
{
private readonly MagicCarpetDbContext _dbContext;
private readonly Mapper _mapper;
@@ -34,16 +34,11 @@ internal 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)
{

View File

@@ -3,6 +3,7 @@ using MagicCarpetContracts.DataModels;
using MagicCarpetContracts.Exceptions;
using MagicCarpetContracts.StoragesContracts;
using MagicCarpetDatabase.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -11,7 +12,7 @@ using System.Threading.Tasks;
namespace MagicCarpetDatabase.Implementations;
internal class SalaryStorageContract : ISalaryStorageContract
public class SalaryStorageContract : ISalaryStorageContract
{
private readonly MagicCarpetDbContext _dbContext;
private readonly Mapper _mapper;
@@ -21,6 +22,7 @@ internal 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));
@@ -28,15 +30,17 @@ internal 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)

View File

@@ -12,7 +12,7 @@ using System.Threading.Tasks;
namespace MagicCarpetDatabase.Implementations;
internal class SaleStorageContract : ISaleStorageContract
public class SaleStorageContract : ISaleStorageContract
{
private readonly MagicCarpetDbContext _dbContext;
private readonly Mapper _mapper;
@@ -22,12 +22,18 @@ internal class SaleStorageContract : ISaleStorageContract
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Client, ClientDataModel>();
cfg.CreateMap<Tour, TourDataModel>();
cfg.CreateMap<Employee, EmployeeDataModel>();
cfg.CreateMap<SaleTour, SaleTourDataModel>();
cfg.CreateMap<SaleTourDataModel, SaleTour>();
cfg.CreateMap<SaleTourDataModel, SaleTour>()
.ForMember(x => x.Tour, x => x.Ignore());
cfg.CreateMap<Sale, SaleDataModel>();
cfg.CreateMap<SaleDataModel, Sale>()
.ForMember(x => x.IsCancel, x => x.MapFrom(src => false))
.ForMember(x => x.SaleTours, x => x.MapFrom(src => src.Tours));
.ForMember(x => x.SaleTours, x => x.MapFrom(src => src.Tours))
.ForMember(x => x.Employee, x => x.Ignore())
.ForMember(x => x.Client, x => x.Ignore());
});
_mapper = new Mapper(config);
}
@@ -36,23 +42,23 @@ internal class SaleStorageContract : ISaleStorageContract
{
try
{
var query = _dbContext.Sales.Include(x => x.SaleTours).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.SaleTours)!
.ThenInclude(d => d.Tour)
.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 (tourId is not null)
{
if (tourId != null)
query = query.Where(x => x.SaleTours!.Any(y => y.TourId == tourId));
}
var s = query.ToList();
return [.. query.Select(x => _mapper.Map<SaleDataModel>(x))];
}
catch (Exception ex)
@@ -113,5 +119,5 @@ internal class SaleStorageContract : ISaleStorageContract
}
}
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.SaleTours)!.ThenInclude(x => x.Tour).FirstOrDefault(x => x.Id == id);
}

View File

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

View File

@@ -7,14 +7,13 @@ using Microsoft.EntityFrameworkCore;
using Npgsql;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetDatabase.Implementations;
internal class TourStorageContract : ITourStorageContract
public class TourStorageContract : ITourStorageContract
{
private readonly MagicCarpetDbContext _dbContext;
private readonly Mapper _mapper;
@@ -26,10 +25,11 @@ internal class TourStorageContract : ITourStorageContract
{
cfg.CreateMap<Tour, TourDataModel>();
cfg.CreateMap<TourDataModel, Tour>();
cfg.CreateMap<TourHistory, TourHistoryDataModel>(); ;
cfg.CreateMap<TourHistory, TourHistoryDataModel>();
});
_mapper = new Mapper(config);
}
public List<TourDataModel> GetList()
{
try
@@ -47,7 +47,7 @@ internal class TourStorageContract : ITourStorageContract
{
try
{
return [.. _dbContext.TourHistories.Where(x => x.TourId == tourId).OrderByDescending(x => x.ChangeDate).Select(x => _mapper.Map<TourHistoryDataModel>(x))];
return [.. _dbContext.TourHistories.Include(x => x.Tour).Where(x => x.TourId == tourId).OrderByDescending(x => x.ChangeDate).Select(x => _mapper.Map<TourHistoryDataModel>(x))];
}
catch (Exception ex)
{
@@ -110,20 +110,35 @@ internal class TourStorageContract : ITourStorageContract
{
try
{
var element = GetTourById(tourDataModel.Id) ?? throw new ElementNotFoundException(tourDataModel.Id);
_dbContext.Tours.Update(_mapper.Map(tourDataModel, element));
_dbContext.SaveChanges();
}
catch (ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
var transaction = _dbContext.Database.BeginTransaction();
try
{
var element = GetTourById(tourDataModel.Id) ?? throw new ElementNotFoundException(tourDataModel.Id);
if (element.Price != tourDataModel.Price)
{
_dbContext.TourHistories.Add(new TourHistory() { TourId = element.Id, OldPrice = element.Price });
_dbContext.SaveChanges();
}
_dbContext.Tours.Update(_mapper.Map(tourDataModel, element));
_dbContext.SaveChanges();
transaction.Commit();
}
catch
{
transaction.Rollback();
throw;
}
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Tours_TourName" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("TourName", tourDataModel.TourName);
}
catch (Exception ex) when (ex is ElementDeletedException || ex is ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();

View File

@@ -15,9 +15,6 @@
<ItemGroup>
<ProjectReference Include="..\MagicCarpetContracts\MagicCarpetContracts.csproj" />
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="MagicCarpetTests" />
<InternalsVisibleTo Include="DynamicProxyGenAssembly2" />
</ItemGroup>
</Project>

View File

@@ -25,6 +25,11 @@ public class MagicCarpetDbContext(IConfigurationDatabase configurationDatabase)
modelBuilder.Entity<Client>().HasIndex(x => x.PhoneNumber).IsUnique();
modelBuilder.Entity<Sale>()
.HasOne(e => e.Client)
.WithMany(e => e.Sales)
.OnDelete(DeleteBehavior.SetNull);
modelBuilder.Entity<Tour>().HasIndex(x => x.TourName).IsUnique();
modelBuilder.Entity<Post>()
@@ -38,10 +43,6 @@ public class MagicCarpetDbContext(IConfigurationDatabase configurationDatabase)
.HasFilter($"\"{nameof(Post.IsActual)}\" = TRUE");
modelBuilder.Entity<SaleTour>().HasKey(x => new { x.SaleId, x.TourId });
modelBuilder.Entity<TourSupplies>().HasKey(x => new { x.SuppliesId, x.TourId });
modelBuilder.Entity<TourAgency>().HasKey(x => new { x.AgencyId, x.TourId });
}
public DbSet<Client> Clients { get; set; }
@@ -59,8 +60,4 @@ public class MagicCarpetDbContext(IConfigurationDatabase configurationDatabase)
public DbSet<SaleTour> SaleTours { get; set; }
public DbSet<Employee> Employees { get; set; }
public DbSet<Supplies> Supplieses { get; set; }
public DbSet<Agency> Agencies { get; set; }
public DbSet<TourSupplies> TourSupplieses { get; set; }
public DbSet<TourAgency> TourAgensies { get; set; }
}

View File

@@ -1,21 +0,0 @@
using AutoMapper;
using MagicCarpetContracts.DataModels;
using MagicCarpetContracts.Enums;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetDatabase.Models;
public class Agency
{
public required string Id { get; set; }
public required TourType Type { get; set; }
public required int Count { get; set; }
[ForeignKey("AgencyId")]
public List<TourAgency>? Tours { get; set; }
}

View File

@@ -22,11 +22,18 @@ public class Employee
public DateTime BirthDate { get; set; }
public DateTime EmploymentDate { get; set; }
public DateTime EmploymentDate { get; set; }
public bool IsDeleted { get; set; }
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;
}
}

View File

@@ -13,4 +13,10 @@ public class SaleTour
public required string TourId { get; set; }
public int Count { get; set; }
public double Price { get; set; }
public Sale? Sale { get; set; }
public Tour? Tour { get; set; }
}

View File

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

View File

@@ -1,6 +1,4 @@
using AutoMapper;
using MagicCarpetContracts.DataModels;
using MagicCarpetContracts.Enums;
using MagicCarpetContracts.Enums;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
@@ -11,7 +9,6 @@ using System.Threading.Tasks;
namespace MagicCarpetDatabase.Models;
[AutoMap(typeof(TourDataModel), ReverseMap = true)]
public class Tour
{
public required string Id { get; set; }
@@ -23,8 +20,4 @@ public class Tour
public List<SaleTour>? SaleTours { get; set; }
[ForeignKey("TourId")]
public List<TourHistory>? TourHistories { get; set; }
[ForeignKey("SuppliesesId")]
public List<TourSupplies>? TourSupplies { get; set; }
[ForeignKey("AgenciesId")]
public List<TourAgency>? TourAgency { get; set; }
}

View File

@@ -1,19 +0,0 @@
using AutoMapper;
using MagicCarpetContracts.DataModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetDatabase.Models;
[AutoMap(typeof(TourSuppliesDataModel), ReverseMap = true)]
public class TourSupplies
{
public required string SuppliesId { get; set; }
public required string TourId { get; set; }
public int Count { get; set; }
public Supplies? Supplies { get; set; }
public Tour? Tours { get; set; }
}

View File

@@ -11,6 +11,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MagicCarpetBusinessLogic",
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MagicCarpetDatabase", "MagicCarpetDatabase\MagicCarpetDatabase.csproj", "{C69B43B2-8680-42D7-A111-306E2E8225FE}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MagicCarpetWebApi", "MagicCarpetWebApi\MagicCarpetWebApi.csproj", "{EB1F990E-6604-4DE4-81A9-2D1D15E0240F}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@@ -33,6 +35,10 @@ Global
{C69B43B2-8680-42D7-A111-306E2E8225FE}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C69B43B2-8680-42D7-A111-306E2E8225FE}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C69B43B2-8680-42D7-A111-306E2E8225FE}.Release|Any CPU.Build.0 = Release|Any CPU
{EB1F990E-6604-4DE4-81A9-2D1D15E0240F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{EB1F990E-6604-4DE4-81A9-2D1D15E0240F}.Debug|Any CPU.Build.0 = Debug|Any CPU
{EB1F990E-6604-4DE4-81A9-2D1D15E0240F}.Release|Any CPU.ActiveCfg = Release|Any CPU
{EB1F990E-6604-4DE4-81A9-2D1D15E0240F}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE

View File

@@ -1,296 +0,0 @@
using MagicCarpetBusinessLogic.Implementations;
using MagicCarpetContracts.BusinessLogicContracts;
using MagicCarpetContracts.DataModels;
using MagicCarpetContracts.Enums;
using MagicCarpetContracts.Exceptions;
using MagicCarpetContracts.StoragesContracts;
using Microsoft.Extensions.Logging;
using Moq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetTests.BusinessLogicContractsTests;
[TestFixture]
internal class AgencyBusinessLogicContractTests
{
private IAgencyBusinessLogicContract _warehouseBusinessLogicContract;
private Mock<IAgencyStorageContract> _warehouseStorageContract;
[OneTimeSetUp]
public void OneTimeSetUp()
{
_warehouseStorageContract = new Mock<IAgencyStorageContract>();
_warehouseBusinessLogicContract = new AgencyBusinessLogicContract(_warehouseStorageContract.Object, new Mock<ILogger>().Object);
}
[TearDown]
public void TearDown()
{
_warehouseStorageContract.Reset();
}
public void GetAllSupplies_ReturnListOfRecords_Test()
{
// Arrange
var listOriginal = new List<AgencyDataModel>()
{
new(Guid.NewGuid().ToString(), TourType.Beach, 1, []),
new(Guid.NewGuid().ToString(), TourType.Beach, 1, []),
new(Guid.NewGuid().ToString(), TourType.Beach, 1, []),
};
_warehouseStorageContract.Setup(x => x.GetList()).Returns(listOriginal);
// Act
var list = _warehouseBusinessLogicContract.GetAllComponents();
// Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.EquivalentTo(listOriginal));
}
[Test]
public void GetAllSupplies_ReturnEmptyList_Test()
{
// Arrange
_warehouseStorageContract.Setup(x => x.GetList()).Returns([]);
// Act
var list = _warehouseBusinessLogicContract.GetAllComponents();
// Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
_warehouseStorageContract.Verify(x => x.GetList(), Times.Once);
}
[Test]
public void GetAllSupplies_ReturnNull_ThrowException_Test()
{
// Arrange
_warehouseStorageContract.Setup(x => x.GetList()).Returns((List<AgencyDataModel>)null);
// Act & Assert
Assert.That(() => _warehouseBusinessLogicContract.GetAllComponents(), Throws.TypeOf<NullListException>());
_warehouseStorageContract.Verify(x => x.GetList(), Times.Once);
}
[Test]
public void GetAllSupplies_StorageThrowError_ThrowException_Test()
{
// Arrange
_warehouseStorageContract.Setup(x => x.GetList()).Throws(new StorageException(new InvalidOperationException()));
// Act & Assert
Assert.That(() => _warehouseBusinessLogicContract.GetAllComponents(), Throws.TypeOf<StorageException>());
_warehouseStorageContract.Verify(x => x.GetList(), Times.Once);
}
[Test]
public void GetSuppliesByData_GetById_ReturnRecord_Test()
{
// Arrange
var id = Guid.NewGuid().ToString();
var record = new AgencyDataModel(id, TourType.Beach, 1, []);
_warehouseStorageContract.Setup(x => x.GetElementById(id)).Returns(record);
// Act
var element = _warehouseBusinessLogicContract.GetComponentByData(id);
// Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.Id, Is.EqualTo(id));
_warehouseStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetComponentsByData_EmptyData_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _warehouseBusinessLogicContract.GetComponentByData(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _warehouseBusinessLogicContract.GetComponentByData(string.Empty), Throws.TypeOf<ArgumentNullException>());
_warehouseStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetSuppliesByData_GetById_NotFoundRecord_ThrowException_Test()
{
// Arrange
_warehouseStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new ElementNotFoundException(""));
// Act & Assert
Assert.That(() => _warehouseBusinessLogicContract.GetComponentByData(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_warehouseStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetSuppliesByData_StorageThrowError_ThrowException_Test()
{
// Arrange
_warehouseStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
// Act & Assert
Assert.That(() => _warehouseBusinessLogicContract.GetComponentByData(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_warehouseStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void InsertSupplies_CorrectRecord_Test()
{
// Arrange
var record = new AgencyDataModel(Guid.NewGuid().ToString(), TourType.Beach, 1,
[new TourAgencyDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]);
_warehouseStorageContract.Setup(x => x.AddElement(It.IsAny<AgencyDataModel>()));
// Act
_warehouseBusinessLogicContract.InsertComponent(record);
// Assert
_warehouseStorageContract.Verify(x => x.AddElement(It.IsAny<AgencyDataModel>()), Times.Once);
}
[Test]
public void InsertSupplies_RecordWithExistsData_ThrowException_Test()
{
// Arrange
_warehouseStorageContract.Setup(x => x.AddElement(It.IsAny<AgencyDataModel>())).Throws(new ElementExistsException("Data", "Data"));
// Act & Assert
Assert.That(() => _warehouseBusinessLogicContract.InsertComponent(new(Guid.NewGuid().ToString(), TourType.Beach, 1,
[new TourAgencyDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<ElementExistsException>());
_warehouseStorageContract.Verify(x => x.AddElement(It.IsAny<AgencyDataModel>()), Times.Once);
}
[Test]
public void InsertSupplies_NullRecord_ThrowException_Test()
{
// Act & Assert
Assert.That(() => _warehouseBusinessLogicContract.InsertComponent(null), Throws.TypeOf<ArgumentNullException>());
_warehouseStorageContract.Verify(x => x.AddElement(It.IsAny<AgencyDataModel>()), Times.Never);
}
[Test]
public void InsertComponents_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _warehouseBusinessLogicContract.InsertComponent(new AgencyDataModel("id", TourType.Beach, 1, [])), Throws.TypeOf<ValidationException>());
_warehouseStorageContract.Verify(x => x.AddElement(It.IsAny<AgencyDataModel>()), Times.Never);
}
[Test]
public void InsertSupplies_StorageThrowError_ThrowException_Test()
{
// Arrange
_warehouseStorageContract.Setup(x => x.AddElement(It.IsAny<AgencyDataModel>())).Throws(new StorageException(new InvalidOperationException()));
// Act & Assert
Assert.That(() => _warehouseBusinessLogicContract.InsertComponent(new(Guid.NewGuid().ToString(), TourType.Beach, 1,
[new TourAgencyDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<StorageException>());
_warehouseStorageContract.Verify(x => x.AddElement(It.IsAny<AgencyDataModel>()), Times.Once);
}
[Test]
public void UpdateSupplies_CorrectRecord_Test()
{
// Arrange
var record = new AgencyDataModel(Guid.NewGuid().ToString(), TourType.Beach, 1,
[new TourAgencyDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]);
_warehouseStorageContract.Setup(x => x.UpdElement(It.IsAny<AgencyDataModel>()));
// Act
_warehouseBusinessLogicContract.UpdateComponent(record);
// Assert
_warehouseStorageContract.Verify(x => x.UpdElement(It.IsAny<AgencyDataModel>()), Times.Once);
}
[Test]
public void UpdateSupplies_RecordWithIncorrectData_ThrowException_Test()
{
// Arrange
_warehouseStorageContract.Setup(x => x.UpdElement(It.IsAny<AgencyDataModel>())).Throws(new ElementNotFoundException(""));
// Act & Assert
Assert.That(() => _warehouseBusinessLogicContract.UpdateComponent(new(Guid.NewGuid().ToString(), TourType.Beach, 1,
[new TourAgencyDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<ElementNotFoundException>());
_warehouseStorageContract.Verify(x => x.UpdElement(It.IsAny<AgencyDataModel>()), Times.Once);
}
[Test]
public void UpdateSupplies_RecordWithExistsData_ThrowException_Test()
{
// Arrange
_warehouseStorageContract.Setup(x => x.UpdElement(It.IsAny<AgencyDataModel>())).Throws(new ElementExistsException("Data", "Data"));
// Act & Assert
Assert.That(() => _warehouseBusinessLogicContract.UpdateComponent(new(Guid.NewGuid().ToString(), TourType.Beach, 1,
[new TourAgencyDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<ElementExistsException>());
_warehouseStorageContract.Verify(x => x.UpdElement(It.IsAny<AgencyDataModel>()), Times.Once);
}
[Test]
public void UpdateSupplies_NullRecord_ThrowException_Test()
{
// Act & Assert
Assert.That(() => _warehouseBusinessLogicContract.UpdateComponent(null), Throws.TypeOf<ArgumentNullException>());
_warehouseStorageContract.Verify(x => x.UpdElement(It.IsAny<AgencyDataModel>()), Times.Never);
}
[Test]
public void UpdateComponents_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _warehouseBusinessLogicContract.UpdateComponent(new AgencyDataModel(Guid.NewGuid().ToString(), TourType.Beach, 1, [])), Throws.TypeOf<ValidationException>());
_warehouseStorageContract.Verify(x => x.UpdElement(It.IsAny<AgencyDataModel>()), Times.Never);
}
[Test]
public void UpdateSupplies_StorageThrowError_ThrowException_Test()
{
// Arrange
_warehouseStorageContract.Setup(x => x.UpdElement(It.IsAny<AgencyDataModel>())).Throws(new StorageException(new InvalidOperationException()));
// Act & Assert
Assert.That(() => _warehouseBusinessLogicContract.UpdateComponent(new(Guid.NewGuid().ToString(), TourType.Beach, 1,
[new TourAgencyDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<StorageException>());
_warehouseStorageContract.Verify(x => x.UpdElement(It.IsAny<AgencyDataModel>()), Times.Once);
}
[Test]
public void DeleteComponents_CorrectRecord_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
var flag = false;
_warehouseStorageContract.Setup(x => x.DelElement(It.Is((string x) => x == id))).Callback(() => { flag = true; });
//Act
_warehouseBusinessLogicContract.DeleteComponent(id);
//Assert
_warehouseStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once); Assert.That(flag);
}
[Test]
public void DeleteComponents_RecordWithIncorrectId_ThrowException_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
_warehouseStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new ElementNotFoundException(id));
//Act&Assert
Assert.That(() => _warehouseBusinessLogicContract.DeleteComponent(Guid.NewGuid().ToString()),
Throws.TypeOf<ElementNotFoundException>());
_warehouseStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
}
[Test]
public void DeleteComponents_IdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _warehouseBusinessLogicContract.DeleteComponent(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _warehouseBusinessLogicContract.DeleteComponent(string.Empty), Throws.TypeOf<ArgumentNullException>());
_warehouseStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Never);
}
[Test]
public void DeleteComponents_IdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _warehouseBusinessLogicContract.DeleteComponent("id"),
Throws.TypeOf<ValidationException>());
_warehouseStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Never);
}
[Test]
public void DeleteComponents_StorageThrowError_ThrowException_Test()
{
//Arrange
_warehouseStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _warehouseBusinessLogicContract.DeleteComponent(Guid.NewGuid().ToString()),
Throws.TypeOf<StorageException>());
_warehouseStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
}
}

View File

@@ -38,61 +38,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]
@@ -102,8 +94,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
@@ -167,7 +159,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);
@@ -182,7 +174,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);
@@ -238,12 +230,11 @@ internal class PostBusinessLogicContractTests
{
//Arrange
var flag = false;
var record = new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Manager, 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);
@@ -258,7 +249,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.Manager, 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);
}
@@ -274,7 +265,7 @@ internal class PostBusinessLogicContractTests
public void InsertPost_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.InsertPost(new PostDataModel("id", "name", PostType.Manager, 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);
}
@@ -284,7 +275,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.Manager, 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);
}
@@ -293,12 +284,11 @@ internal class PostBusinessLogicContractTests
{
//Arrange
var flag = false;
var record = new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Manager, 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);
@@ -313,7 +303,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.Manager, 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);
}
@@ -323,7 +313,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.Manager, 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);
}
@@ -339,7 +329,7 @@ internal class PostBusinessLogicContractTests
public void UpdatePost_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.UpdatePost(new PostDataModel("id", "name", PostType.Manager, 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);
}
@@ -349,7 +339,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.Manager, 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);
}

View File

@@ -164,7 +164,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);
}
@@ -191,12 +191,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 SaleTourDataModel(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;
@@ -213,7 +213,7 @@ internal class SalaryBusinessLogicContractTests
}
[Test]
public void CalculateSalaryByMounth_WithSeveralWorkers_Test()
public void CalculateSalaryByMounth_WithSeveralEmployees_Test()
{
//Arrange
var employee1Id = Guid.NewGuid().ToString();
@@ -225,13 +225,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
@@ -241,7 +241,7 @@ internal class SalaryBusinessLogicContractTests
}
[Test]
public void CalculateSalaryByMounth_WithoutSalesByWorker_Test()
public void CalculateSalaryByMounth_WithoutSalesByEmployee_Test()
{
//Arrange
var postSalary = 2000.0;
@@ -249,7 +249,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;
@@ -271,7 +271,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
@@ -284,22 +284,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>());
}
@@ -312,7 +312,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
@@ -325,7 +325,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?>()))
@@ -335,14 +335,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

View File

@@ -18,22 +18,18 @@ internal class SaleBusinessLogicContractTests
{
private SaleBusinessLogicContract _saleBusinessLogicContract;
private Mock<ISaleStorageContract> _saleStorageContract;
private Mock<IAgencyStorageContract> _agencyStorageContract;
[OneTimeSetUp]
public void OneTimeSetUp()
{
_saleStorageContract = new Mock<ISaleStorageContract>();
_agencyStorageContract = new Mock<IAgencyStorageContract>();
_saleBusinessLogicContract = new SaleBusinessLogicContract(_saleStorageContract.Object,
_agencyStorageContract.Object, new Mock<ILogger>().Object);
_saleBusinessLogicContract = new SaleBusinessLogicContract(_saleStorageContract.Object, new Mock<ILogger>().Object);
}
[TearDown]
public void TearDown()
{
_saleStorageContract.Reset();
_agencyStorageContract.Reset();
}
[Test]
@@ -43,10 +39,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 SaleTourDataModel(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 SaleTourDataModel(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
@@ -107,10 +103,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 SaleTourDataModel(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 SaleTourDataModel(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
@@ -188,10 +184,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 SaleTourDataModel(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 SaleTourDataModel(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
@@ -269,10 +265,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 SaleTourDataModel(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 SaleTourDataModel(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
@@ -347,8 +343,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 SaleTourDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]);
var record = new SaleDataModel(id, Guid.NewGuid().ToString(), null, DiscountType.None, false,
[new SaleTourDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5, 1.2)]);
_saleStorageContract.Setup(x => x.GetElementById(id)).Returns(record);
//Act
var element = _saleBusinessLogicContract.GetSaleByData(id);
@@ -398,9 +394,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 SaleTourDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]);
_agencyStorageContract.Setup(x => x.CheckComponents(It.IsAny<SaleDataModel>())).Returns(true);
var record = new SaleDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), DiscountType.None,
false, [new SaleTourDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5, 1.2)]);
_saleStorageContract.Setup(x => x.AddElement(It.IsAny<SaleDataModel>()))
.Callback((SaleDataModel x) =>
{
@@ -414,7 +409,6 @@ internal class SaleBusinessLogicContractTests
//Act
_saleBusinessLogicContract.InsertSale(record);
//Assert
_agencyStorageContract.Verify(x => x.CheckComponents(It.IsAny<SaleDataModel>()), Times.Once);
_saleStorageContract.Verify(x => x.AddElement(It.IsAny<SaleDataModel>()), Times.Once);
Assert.That(flag);
}
@@ -423,13 +417,11 @@ internal class SaleBusinessLogicContractTests
public void InsertSale_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_agencyStorageContract.Setup(x => x.CheckComponents(It.IsAny<SaleDataModel>())).Returns(true);
_saleStorageContract.Setup(x => x.AddElement(It.IsAny<SaleDataModel>())).Throws(new ElementExistsException("Data", "Data"));
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.InsertSale(new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(),
Guid.NewGuid().ToString(), 10, DiscountType.None, 10, false, [new SaleTourDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<ElementExistsException>());
Guid.NewGuid().ToString(), DiscountType.None, false, [new SaleTourDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5, 1.2)])), Throws.TypeOf<ElementExistsException>());
_saleStorageContract.Verify(x => x.AddElement(It.IsAny<SaleDataModel>()), Times.Once);
_agencyStorageContract.Verify(x => x.CheckComponents(It.IsAny<SaleDataModel>()), Times.Once);
}
[Test]
@@ -444,7 +436,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);
}
@@ -452,27 +444,13 @@ internal class SaleBusinessLogicContractTests
public void InsertSale_StorageThrowError_ThrowException_Test()
{
//Arrange
_agencyStorageContract.Setup(x => x.CheckComponents(It.IsAny<SaleDataModel>())).Returns(true);
_saleStorageContract.Setup(x => x.AddElement(It.IsAny<SaleDataModel>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.InsertSale(new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(),
Guid.NewGuid().ToString(), 10, DiscountType.None, 10, false, [new SaleTourDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<StorageException>());
_agencyStorageContract.Verify(x => x.CheckComponents(It.IsAny<SaleDataModel>()), Times.Once);
Guid.NewGuid().ToString(), DiscountType.None, false, [new SaleTourDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5, 1.2)])), Throws.TypeOf<StorageException>());
_saleStorageContract.Verify(x => x.AddElement(It.IsAny<SaleDataModel>()), Times.Once);
}
[Test]
public void InsertSale_InsufficientError_ThrowException_Test()
{
//Arrange
_agencyStorageContract.Setup(x => x.CheckComponents(It.IsAny<SaleDataModel>())).Returns(false);
Assert.That(() => _saleBusinessLogicContract.InsertSale(new SaleDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(),
Guid.NewGuid().ToString(), 10, DiscountType.None, 10, false,
[new SaleTourDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<InsufficientException>());
//Act&Assert
_agencyStorageContract.Verify(x => x.CheckComponents(It.IsAny<SaleDataModel>()), Times.Once);
}
[Test]
public void CancelSale_CorrectRecord_Test()
{

View File

@@ -1,242 +0,0 @@
using MagicCarpetBusinessLogic.Implementations;
using MagicCarpetContracts.DataModels;
using MagicCarpetContracts.Enums;
using MagicCarpetContracts.Exceptions;
using MagicCarpetContracts.StoragesContracts;
using Microsoft.Extensions.Logging;
using Moq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetTests.BusinessLogicContractsTests;
[TestFixture]
internal class SuppliesBusinessLogicContractTests
{
private SuppliesBusinessLogicContract _suppliesBusinessLogicContract;
private Mock<ISuppliesStorageContract> _suppliesStorageContract;
[OneTimeSetUp]
public void OneTimeSetUp()
{
_suppliesStorageContract = new Mock<ISuppliesStorageContract>();
_suppliesBusinessLogicContract = new SuppliesBusinessLogicContract(_suppliesStorageContract.Object, new Mock<ILogger>().Object);
}
[TearDown]
public void TearDown()
{
_suppliesStorageContract.Reset();
}
[Test]
public void GetAllSupplies_ReturnListOfRecords_Test()
{
// Arrange
var listOriginal = new List<SuppliesDataModel>()
{
new(Guid.NewGuid().ToString(), TourType.Beach, DateTime.Now, 1, []),
new(Guid.NewGuid().ToString(), TourType.Beach, DateTime.Now, 1, []),
new(Guid.NewGuid().ToString(), TourType.Beach, DateTime.Now, 1, []),
};
_suppliesStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>())).Returns(listOriginal);
// Act
var list = _suppliesBusinessLogicContract.GetAllComponents();
// Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.EquivalentTo(listOriginal));
}
[Test]
public void GetAllSupplies_ReturnEmptyList_Test()
{
// Arrange
_suppliesStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>())).Returns([]);
// Act
var list = _suppliesBusinessLogicContract.GetAllComponents();
// Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
_suppliesStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>()), Times.Once);
}
[Test]
public void GetAllSupplies_ReturnNull_ThrowException_Test()
{
// Arrange
_suppliesStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>())).Returns((List<SuppliesDataModel>)null);
// Act & Assert
Assert.That(() => _suppliesBusinessLogicContract.GetAllComponents(), Throws.TypeOf<NullListException>());
_suppliesStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>()), Times.Once);
}
[Test]
public void GetAllSupplies_StorageThrowError_ThrowException_Test()
{
// Arrange
_suppliesStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>())).Throws(new StorageException(new InvalidOperationException()));
// Act & Assert
Assert.That(() => _suppliesBusinessLogicContract.GetAllComponents(), Throws.TypeOf<StorageException>());
_suppliesStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>()), Times.Once);
}
[Test]
public void GetSuppliesByData_GetById_ReturnRecord_Test()
{
// Arrange
var id = Guid.NewGuid().ToString();
var record = new SuppliesDataModel(id,TourType.Beach, DateTime.Now, 1, []);
_suppliesStorageContract.Setup(x => x.GetElementById(id)).Returns(record);
// Act
var element = _suppliesBusinessLogicContract.GetComponentByData(id);
// Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.Id, Is.EqualTo(id));
_suppliesStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetComponentsByData_EmptyData_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _suppliesBusinessLogicContract.GetComponentByData(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _suppliesBusinessLogicContract.GetComponentByData(string.Empty), Throws.TypeOf<ArgumentNullException>());
_suppliesStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetSuppliesByData_GetById_NotFoundRecord_ThrowException_Test()
{
// Arrange
_suppliesStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new ElementNotFoundException(""));
// Act & Assert
Assert.That(() => _suppliesBusinessLogicContract.GetComponentByData(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_suppliesStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetSuppliesByData_StorageThrowError_ThrowException_Test()
{
// Arrange
_suppliesStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
// Act & Assert
Assert.That(() => _suppliesBusinessLogicContract.GetComponentByData(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_suppliesStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void InsertSupplies_CorrectRecord_Test()
{
// Arrange
var record = new SuppliesDataModel(Guid.NewGuid().ToString(), TourType.Beach, DateTime.Now, 1,
[new TourSuppliesDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]);
_suppliesStorageContract.Setup(x => x.AddElement(It.IsAny<SuppliesDataModel>()));
// Act
_suppliesBusinessLogicContract.InsertComponent(record);
// Assert
_suppliesStorageContract.Verify(x => x.AddElement(It.IsAny<SuppliesDataModel>()), Times.Once);
}
[Test]
public void InsertSupplies_RecordWithExistsData_ThrowException_Test()
{
// Arrange
_suppliesStorageContract.Setup(x => x.AddElement(It.IsAny<SuppliesDataModel>())).Throws(new ElementExistsException("Data", "Data"));
// Act & Assert
Assert.That(() => _suppliesBusinessLogicContract.InsertComponent(new(Guid.NewGuid().ToString(), TourType.Beach, DateTime.Now, 1,
[new TourSuppliesDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<ElementExistsException>());
_suppliesStorageContract.Verify(x => x.AddElement(It.IsAny<SuppliesDataModel>()), Times.Once);
}
[Test]
public void InsertSupplies_NullRecord_ThrowException_Test()
{
// Act & Assert
Assert.That(() => _suppliesBusinessLogicContract.InsertComponent(null), Throws.TypeOf<ArgumentNullException>());
_suppliesStorageContract.Verify(x => x.AddElement(It.IsAny<SuppliesDataModel>()), Times.Never);
}
[Test]
public void InsertComponents_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _suppliesBusinessLogicContract.InsertComponent(new SuppliesDataModel("id", TourType.Beach, DateTime.UtcNow, 1, [])), Throws.TypeOf<ValidationException>());
_suppliesStorageContract.Verify(x => x.AddElement(It.IsAny<SuppliesDataModel>()), Times.Never);
}
[Test]
public void InsertSupplies_StorageThrowError_ThrowException_Test()
{
// Arrange
_suppliesStorageContract.Setup(x => x.AddElement(It.IsAny<SuppliesDataModel>())).Throws(new StorageException(new InvalidOperationException()));
// Act & Assert
Assert.That(() => _suppliesBusinessLogicContract.InsertComponent(new(Guid.NewGuid().ToString(), TourType.Beach, DateTime.Now, 1,
[new TourSuppliesDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<StorageException>());
_suppliesStorageContract.Verify(x => x.AddElement(It.IsAny<SuppliesDataModel>()), Times.Once);
}
[Test]
public void UpdateSupplies_CorrectRecord_Test()
{
// Arrange
var record = new SuppliesDataModel(Guid.NewGuid().ToString(), TourType.Beach, DateTime.Now, 1,
[new TourSuppliesDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]);
_suppliesStorageContract.Setup(x => x.UpdElement(It.IsAny<SuppliesDataModel>()));
// Act
_suppliesBusinessLogicContract.UpdateComponent(record);
// Assert
_suppliesStorageContract.Verify(x => x.UpdElement(It.IsAny<SuppliesDataModel>()), Times.Once);
}
[Test]
public void UpdateSupplies_RecordWithIncorrectData_ThrowException_Test()
{
// Arrange
_suppliesStorageContract.Setup(x => x.UpdElement(It.IsAny<SuppliesDataModel>())).Throws(new ElementNotFoundException(""));
// Act & Assert
Assert.That(() => _suppliesBusinessLogicContract.UpdateComponent(new(Guid.NewGuid().ToString(), TourType.Beach, DateTime.Now, 1,
[new TourSuppliesDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<ElementNotFoundException>());
_suppliesStorageContract.Verify(x => x.UpdElement(It.IsAny<SuppliesDataModel>()), Times.Once);
}
[Test]
public void UpdateSupplies_RecordWithExistsData_ThrowException_Test()
{
// Arrange
_suppliesStorageContract.Setup(x => x.UpdElement(It.IsAny<SuppliesDataModel>())).Throws(new ElementExistsException("Data", "Data"));
// Act & Assert
Assert.That(() => _suppliesBusinessLogicContract.UpdateComponent(new(Guid.NewGuid().ToString(), TourType.Beach, DateTime.Now, 1,
[new TourSuppliesDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<ElementExistsException>());
_suppliesStorageContract.Verify(x => x.UpdElement(It.IsAny<SuppliesDataModel>()), Times.Once);
}
[Test]
public void UpdateSupplies_NullRecord_ThrowException_Test()
{
// Act & Assert
Assert.That(() => _suppliesBusinessLogicContract.UpdateComponent(null), Throws.TypeOf<ArgumentNullException>());
_suppliesStorageContract.Verify(x => x.UpdElement(It.IsAny<SuppliesDataModel>()), Times.Never);
}
[Test]
public void UpdateComponents_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _suppliesBusinessLogicContract.UpdateComponent(new SuppliesDataModel(Guid.NewGuid().ToString(), TourType.Beach, DateTime.Now, 1, [])), Throws.TypeOf<ValidationException>());
_suppliesStorageContract.Verify(x => x.UpdElement(It.IsAny<SuppliesDataModel>()), Times.Never);
}
[Test]
public void UpdateSupplies_StorageThrowError_ThrowException_Test()
{
// Arrange
_suppliesStorageContract.Setup(x => x.UpdElement(It.IsAny<SuppliesDataModel>())).Throws(new StorageException(new InvalidOperationException()));
// Act & Assert
Assert.That(() => _suppliesBusinessLogicContract.UpdateComponent(new(Guid.NewGuid().ToString(), TourType.Beach, DateTime.Now, 1,
[new TourSuppliesDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<StorageException>());
_suppliesStorageContract.Verify(x => x.UpdElement(It.IsAny<SuppliesDataModel>()), Times.Once);
}
}

View File

@@ -3,7 +3,6 @@ using MagicCarpetContracts.DataModels;
using MagicCarpetContracts.Enums;
using MagicCarpetContracts.Exceptions;
using MagicCarpetContracts.StoragesContracts;
using MagicCarpetTests.DataModelTests;
using Microsoft.Extensions.Logging;
using Moq;
using System;
@@ -155,7 +154,7 @@ internal class TourBusinessLogicContractTests
{
//Arrange
var id = Guid.NewGuid().ToString();
var record = new TourDataModel(id, "name", "country", 10, TourType.Ski);
var record = new TourDataModel(id, "name","country", 10, TourType.Ski);
_tourStorageContract.Setup(x => x.GetElementById(id)).Returns(record);
//Act
var element = _tourBusinessLogicContract.GetTourByData(id);
@@ -184,7 +183,7 @@ internal class TourBusinessLogicContractTests
{
//Arrange
var country = "country";
var record = new TourDataModel(Guid.NewGuid().ToString(), "name", country, 10, TourType.Ski);
var record = new TourDataModel(Guid.NewGuid().ToString(), "name", country, 10, TourType.Ski);
_tourStorageContract.Setup(x => x.GetElementByName(country)).Returns(record);
//Act
var element = _tourBusinessLogicContract.GetTourByData(country);
@@ -289,18 +288,10 @@ internal class TourBusinessLogicContractTests
public void InsertTour_StorageThrowError_ThrowException_Test()
{
//Arrange
Assert.That(() => _tourBusinessLogicContract.InsertTour(new TourDataModel(Guid.NewGuid().ToString(), "name","country", 10, TourType.Ski)), Throws.TypeOf<InsufficientException>());
_tourStorageContract.Setup(x => x.AddElement(It.IsAny<TourDataModel>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
_tourStorageContract.Verify(x => x.UpdElement(It.IsAny<TourDataModel>()), Times.Never);
}
[Test]
public void InsertFurniture_InsufficientError_ThrowException_Test()
{
//Arrange
Assert.That(() => _tourBusinessLogicContract.InsertTour(new TourDataModel(Guid.NewGuid().ToString(), "name", "country", 10, TourType.Ski)),Throws.TypeOf<InsufficientException>());
//Act&Assert
_tourStorageContract.Verify(x => x.UpdElement(It.IsAny<TourDataModel>()), Times.Never);
Assert.That(() => _tourBusinessLogicContract.InsertTour(new(Guid.NewGuid().ToString(), "name", "country", 10, TourType.Ski)), Throws.TypeOf<StorageException>());
_tourStorageContract.Verify(x => x.AddElement(It.IsAny<TourDataModel>()), Times.Once);
}
[Test]
@@ -338,7 +329,7 @@ internal class TourBusinessLogicContractTests
//Arrange
_tourStorageContract.Setup(x => x.UpdElement(It.IsAny<TourDataModel>())).Throws(new ElementExistsException("Data", "Data"));
//Act&Assert
Assert.That(() => _tourBusinessLogicContract.UpdateTour(new(Guid.NewGuid().ToString(), "name", "country", 10, TourType.Ski)), Throws.TypeOf <ElementExistsException>());
Assert.That(() => _tourBusinessLogicContract.UpdateTour(new(Guid.NewGuid().ToString(), "name", "country", 10, TourType.Ski)), Throws.TypeOf<ElementExistsException>());
_tourStorageContract.Verify(x => x.UpdElement(It.IsAny<TourDataModel>()), Times.Once);
}

View File

@@ -1,79 +0,0 @@
using MagicCarpetContracts.DataModels;
using MagicCarpetContracts.Enums;
using MagicCarpetContracts.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetTests.DataModelTests;
[TestFixture]
internal class AgencyDataModelTests
{
[Test]
public void IdIsNullOrEmptyTest()
{
var model = CreateDataModel(null, TourType.Beach, 1, CreateSubDataModel());
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
model = CreateDataModel(string.Empty, TourType.Beach, 1, CreateSubDataModel());
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void IdIsNotGuidTest()
{
var model = CreateDataModel("id", TourType.Beach, 1, CreateSubDataModel());
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void TypeIsNoneTest()
{
var model = CreateDataModel(Guid.NewGuid().ToString(), TourType.None, 1, CreateSubDataModel());
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void CountIsLessOrZeroTest()
{
var model = CreateDataModel(Guid.NewGuid().ToString(), TourType.None, 0, CreateSubDataModel());
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
model = CreateDataModel(Guid.NewGuid().ToString(), TourType.None, -1, CreateSubDataModel());
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void ToursIsNullOrEmptyTest()
{
var sale = CreateDataModel(Guid.NewGuid().ToString(), TourType.Beach, 1, null);
Assert.That(() => sale.Validate(), Throws.TypeOf<ValidationException>());
sale = CreateDataModel(Guid.NewGuid().ToString(), TourType.Beach, 1, []);
Assert.That(() => sale.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void AllFieldsIsCorrectTest()
{
var id = Guid.NewGuid().ToString();
var type = TourType.Beach;
var count = 1;
var tours = CreateSubDataModel();
var model = CreateDataModel(id, type, count, tours);
Assert.DoesNotThrow(() => model.Validate());
Assert.Multiple(() =>
{
Assert.That(model.Id, Is.EqualTo(id));
Assert.That(model.Type, Is.EqualTo(type));
Assert.That(model.Count, Is.EqualTo(count));
Assert.That(model.Tours, Is.EqualTo(tours));
});
}
private static AgencyDataModel CreateDataModel(string? id, TourType type, int count, List<TourAgencyDataModel> tours)
=> new AgencyDataModel(id, type, count, tours);
private static List<TourAgencyDataModel> CreateSubDataModel()
=> [new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 1)];
}

View File

@@ -14,41 +14,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>());
}
@@ -56,13 +56,10 @@ internal class PostDataModelTests
public void AllFieldsIsCorrectTest()
{
var postId = Guid.NewGuid().ToString();
var postPostId = Guid.NewGuid().ToString();
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(() =>
{
@@ -70,11 +67,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);
}

View File

@@ -15,89 +15,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 ToursIsNullOrEmptyTest()
{
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 tours = new List<SaleTourDataModel>()
{
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 = tours.Sum(x => x.Price * x.Count);
var saleNone = CreateDataModel(saleId, employeeId, clientId, DiscountType.None, isCancel, tours);
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, tours);
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, tours);
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, tours);
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, tours);
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 tours = CreateSubDataModel();
var sale = CreateDataModel(saleId, employeeId, clientId, sum, discountType, discount, isCancel, tours);
var sale = CreateDataModel(saleId, employeeId, clientId, discountType, isCancel, tours);
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.Tours, Is.EquivalentTo(tours));
});
}
private static SaleDataModel CreateDataModel(string? id, string? employeeId, string? clientId, double sum, DiscountType discountType,
double discount, bool isCancel, List<SaleTourDataModel>? tours) =>
new(id, employeeId, clientId, sum, discountType, discount, isCancel, tours);
private static SaleDataModel CreateDataModel(string? id, string? employeeId, string? clientId, DiscountType discountType, bool isCancel, List<SaleTourDataModel>? tours) =>
new(id, employeeId, clientId, discountType, isCancel, tours);
private static List<SaleTourDataModel> CreateSubDataModel()
=> [new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 1)];
=> [new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 1, 1.1)];
}

View File

@@ -14,41 +14,50 @@ internal class SaleTourDataModelTests
[Test]
public void SaleIdIsNullOrEmptyTest()
{
var saleTour = CreateDataModel(null, Guid.NewGuid().ToString(), 10);
var saleTour = CreateDataModel(null, Guid.NewGuid().ToString(), 10, 1.1);
Assert.That(() => saleTour.Validate(), Throws.TypeOf<ValidationException>());
saleTour = CreateDataModel(string.Empty, Guid.NewGuid().ToString(), 10);
saleTour = CreateDataModel(string.Empty, Guid.NewGuid().ToString(), 10, 1.1);
Assert.That(() => saleTour.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void SaleIdIsNotGuidTest()
{
var saleTour = CreateDataModel("saleId", Guid.NewGuid().ToString(), 10);
var saleTour = CreateDataModel("saleId", Guid.NewGuid().ToString(), 10, 1.1);
Assert.That(() => saleTour.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void CocktailIdIsNullOrEmptyTest()
public void TourIdIsNullOrEmptyTest()
{
var saleTour = CreateDataModel(Guid.NewGuid().ToString(), null, 10);
var saleTour = CreateDataModel(Guid.NewGuid().ToString(), null, 10, 1.1);
Assert.That(() => saleTour.Validate(), Throws.TypeOf<ValidationException>());
saleTour = CreateDataModel(string.Empty, Guid.NewGuid().ToString(), 10);
saleTour = CreateDataModel(string.Empty, Guid.NewGuid().ToString(), 10, 1.1);
Assert.That(() => saleTour.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void ProductIdIsNotGuidTest()
public void TourIdIsNotGuidTest()
{
var saleTour = CreateDataModel(Guid.NewGuid().ToString(), "productId", 10);
var saleTour = CreateDataModel(Guid.NewGuid().ToString(), "tourId", 10, 1.1);
Assert.That(() => saleTour.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void CountIsLessOrZeroTest()
{
var saleTour = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 0);
var saleTour = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 0, 1.1);
Assert.That(() => saleTour.Validate(), Throws.TypeOf<ValidationException>());
saleTour = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), -10);
saleTour = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), -10, 1.1);
Assert.That(() => saleTour.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void PriceIsLessOrZeroTest()
{
var saleTour = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 1, 0);
Assert.That(() => saleTour.Validate(), Throws.TypeOf<ValidationException>());
saleTour = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 1, -10);
Assert.That(() => saleTour.Validate(), Throws.TypeOf<ValidationException>());
}
@@ -58,16 +67,18 @@ internal class SaleTourDataModelTests
var saleId = Guid.NewGuid().ToString();
var tourId = Guid.NewGuid().ToString();
var count = 10;
var saleCocktail = CreateDataModel(saleId, tourId, count);
Assert.That(() => saleCocktail.Validate(), Throws.Nothing);
var price = 1.2;
var saleTour = CreateDataModel(saleId, tourId, count, price);
Assert.That(() => saleTour.Validate(), Throws.Nothing);
Assert.Multiple(() =>
{
Assert.That(saleCocktail.SaleId, Is.EqualTo(saleId));
Assert.That(saleCocktail.TourId, Is.EqualTo(tourId));
Assert.That(saleCocktail.Count, Is.EqualTo(count));
Assert.That(saleTour.SaleId, Is.EqualTo(saleId));
Assert.That(saleTour.TourId, Is.EqualTo(tourId));
Assert.That(saleTour.Count, Is.EqualTo(count));
Assert.That(saleTour.Price, Is.EqualTo(price));
});
}
private static SaleTourDataModel CreateDataModel(string? saleId, string? tourId, int count) =>
new(saleId, tourId, count);
private static SaleTourDataModel CreateDataModel(string? saleId, string? tourId, int count, double price) =>
new(saleId, tourId, count, price);
}

View File

@@ -1,80 +0,0 @@
using MagicCarpetContracts.DataModels;
using MagicCarpetContracts.Enums;
using MagicCarpetContracts.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetTests.DataModelTests;
[TestFixture]
internal class SuppliesDataModelTests
{
[Test]
public void IdIsNullOrEmptyTest()
{
var model = CreateDataModel(null, TourType.Beach, DateTime.Now, 1, CreateSubDataModel());
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
model = CreateDataModel(string.Empty, TourType.Beach, DateTime.Now, 1, CreateSubDataModel());
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void IdIsNotGuidTest()
{
var model = CreateDataModel("id", TourType.Beach, DateTime.Now, 1, CreateSubDataModel());
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void TypeIsNoneTest()
{
var model = CreateDataModel(Guid.NewGuid().ToString(), TourType.None, DateTime.Now, 1, CreateSubDataModel());
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void CountIsLessOrZeroTest()
{
var model = CreateDataModel(Guid.NewGuid().ToString(), TourType.None, DateTime.Now, 0, CreateSubDataModel());
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
model = CreateDataModel(Guid.NewGuid().ToString(), TourType.None, DateTime.Now, -1, CreateSubDataModel());
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void ToursIsNullOrEmptyTest()
{
var sale = CreateDataModel(Guid.NewGuid().ToString(), TourType.Beach, DateTime.Now, 1, null);
Assert.That(() => sale.Validate(), Throws.TypeOf<ValidationException>());
sale = CreateDataModel(Guid.NewGuid().ToString(), TourType.Beach, DateTime.Now, 1, []);
Assert.That(() => sale.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void AllFieldsIsCorrectTest()
{
var id = Guid.NewGuid().ToString();
var type = TourType.Beach;
var date = DateTime.Now;
var count = 1;
var tours = CreateSubDataModel();
var model = CreateDataModel(id, type, date, count, tours);
Assert.DoesNotThrow(() => model.Validate());
Assert.Multiple(() =>
{
Assert.That(model.Id, Is.EqualTo(id));
Assert.That(model.Type, Is.EqualTo(type));
Assert.That(model.ProductuionDate, Is.EqualTo(date));
Assert.That(model.Count, Is.EqualTo(count));
Assert.That(model.Tours, Is.EqualTo(tours));
});
}
private static SuppliesDataModel CreateDataModel(string? id, TourType type, DateTime date, int count, List<TourSuppliesDataModel> tours)
=> new(id, type, date, count, tours);
private static List<TourSuppliesDataModel> CreateSubDataModel()
=> [new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 1)];
}

View File

@@ -1,75 +0,0 @@
using MagicCarpetContracts.DataModels;
using MagicCarpetContracts.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetTests.DataModelTests;
[TestFixture]
internal class TourAgencyDataModelTests
{
[Test]
public void AgencyIdIsNullOrEmptyTest()
{
var model = CreateDataModel(null, Guid.NewGuid().ToString(), 1);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
model = CreateDataModel(string.Empty, Guid.NewGuid().ToString(), 1);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void AgencyIdIsNotGuidTest()
{
var model = CreateDataModel("id", Guid.NewGuid().ToString(), 1);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void TourIdIsNullOrEmptyTest()
{
var model = CreateDataModel(Guid.NewGuid().ToString(), null, 1);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
model = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, 1);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void TourIdIsNotGuidTest()
{
var model = CreateDataModel(Guid.NewGuid().ToString(), "id", 1);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void CountIsLessOrZeroTest()
{
var model = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 0);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
model = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), -1);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void AllFieldsIsCorrectTest()
{
var agencyId = Guid.NewGuid().ToString();
var tourId = Guid.NewGuid().ToString();
var count = 1;
var model = CreateDataModel(agencyId, tourId, count);
Assert.That(() => model.Validate(), Throws.Nothing);
Assert.Multiple(() =>
{
Assert.That(model.AgencyId, Is.EqualTo(agencyId));
Assert.That(model.TourId, Is.EqualTo(tourId));
Assert.That(model.Count, Is.EqualTo(count));
});
}
private static TourAgencyDataModel CreateDataModel(string? agencyId, string? tourId, int count)
=> new(agencyId, tourId, count);
}

View File

@@ -3,7 +3,6 @@ using MagicCarpetContracts.Enums;
using MagicCarpetContracts.Exceptions;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
@@ -15,17 +14,17 @@ internal class TourDataModelTests
[Test]
public void IdIsNullOrEmptyTest()
{
var tour = CreateDataModel(null, "name", "country", 10.5, TourType.Beach);
Assert.That(() => tour.Validate(), Throws.TypeOf<ValidationException>());
tour = CreateDataModel(string.Empty, "name", "country", 10.5, TourType.Beach);
Assert.That(() => tour.Validate(), Throws.TypeOf<ValidationException>());
var cocktail = CreateDataModel(null, "name", "country", 10.5, TourType.Beach);
Assert.That(() => cocktail.Validate(), Throws.TypeOf<ValidationException>());
cocktail = CreateDataModel(string.Empty, "name", "country", 10.5, TourType.Beach);
Assert.That(() => cocktail.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void IdIsNotGuidTest()
{
var tour = CreateDataModel("id", "name", "country", 10.5, TourType.Beach);
Assert.That(() => tour.Validate(), Throws.TypeOf<ValidationException>());
var cocktail = CreateDataModel("id", "name", "country", 10.5, TourType.Beach);
Assert.That(() => cocktail.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
@@ -47,17 +46,17 @@ internal class TourDataModelTests
[Test]
public void PriceIsLessOrZeroTest()
{
var tour = CreateDataModel(Guid.NewGuid().ToString(), null, null, 0, TourType.Beach);
Assert.That(() => tour.Validate(), Throws.TypeOf<ValidationException>());
tour = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, string.Empty, -10.5, TourType.Beach);
Assert.That(() => tour.Validate(), Throws.TypeOf<ValidationException>());
var cocktail = CreateDataModel(Guid.NewGuid().ToString(), null, null, 0, TourType.Beach);
Assert.That(() => cocktail.Validate(), Throws.TypeOf<ValidationException>());
cocktail = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, string.Empty, -10.5, TourType.Beach);
Assert.That(() => cocktail.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void TourTypeIsNoneTest()
{
var tour = CreateDataModel(Guid.NewGuid().ToString(), null, null, 0, TourType.Beach);
Assert.That(() => tour.Validate(), Throws.TypeOf<ValidationException>());
var cocktail = CreateDataModel(Guid.NewGuid().ToString(), null, null, 0, TourType.Beach);
Assert.That(() => cocktail.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
@@ -68,8 +67,6 @@ internal class TourDataModelTests
var tourCountry = "country";
var price = 10.5;
var tourType = TourType.Ski;
var supplies = CreateSuppliesDataModel();
var agency = CreateAgencyDataModel();
var tour = CreateDataModel(tourId, tourName, tourCountry, price, tourType);
Assert.That(() => tour.Validate(), Throws.Nothing);
Assert.Multiple(() =>
@@ -82,11 +79,6 @@ internal class TourDataModelTests
});
}
private static TourDataModel CreateDataModel(string? id, string? tourName, string? countryName, double price, TourType tourType) =>
private static TourDataModel CreateDataModel(string? id, string? tourName, string? countryName,double price, TourType tourType) =>
new(id, tourName, countryName,price, tourType);
private static List<TourSuppliesDataModel> CreateSuppliesDataModel()
=> [new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 1)];
private static List<TourAgencyDataModel> CreateAgencyDataModel()
=> [new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 1)];
}

View File

@@ -1,75 +0,0 @@
using MagicCarpetContracts.DataModels;
using MagicCarpetContracts.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetTests.DataModelTests;
[TestFixture]
internal class TourSuppliesDataModelTests
{
[Test]
public void SuppliesIdIsNullOrEmptyTest()
{
var model = CreateDataModel(null, Guid.NewGuid().ToString(), 1);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
model = CreateDataModel(string.Empty, Guid.NewGuid().ToString(), 1);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void SuppliesIdIsNotGuidTest()
{
var model = CreateDataModel("id", Guid.NewGuid().ToString(), 1);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void TourIdIsNullOrEmptyTest()
{
var model = CreateDataModel(Guid.NewGuid().ToString(), null, 1);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
model = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, 1);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void TourIdIsNotGuidTest()
{
var model = CreateDataModel(Guid.NewGuid().ToString(), "id", 1);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void CountIsLessOrZeroTest()
{
var model = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 0);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
model = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), -1);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void AllFieldsIsCorrectTest()
{
var suppliesId = Guid.NewGuid().ToString();
var tourId = Guid.NewGuid().ToString();
var count = 1;
var model = CreateDataModel(suppliesId, tourId, count);
Assert.That(() => model.Validate(), Throws.Nothing);
Assert.Multiple(() =>
{
Assert.That(model.SuppliesId, Is.EqualTo(suppliesId));
Assert.That(model.TourId, Is.EqualTo(tourId));
Assert.That(model.Count, Is.EqualTo(count));
});
}
private static TourSuppliesDataModel CreateDataModel(string? suppliesId, string? tourId, int count)
=> new(suppliesId, tourId, count);
}

View File

@@ -0,0 +1,36 @@
using MagicCarpetContracts.Infrastructure;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetTests.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);
}
}

View File

@@ -0,0 +1,107 @@
using MagicCarpetContracts.Enums;
using MagicCarpetDatabase;
using MagicCarpetDatabase.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetTests.Infrastructure;
internal static class MagicCarpetDbContextExtensions
{
public static Client InsertClientToDatabaseAndReturn(this MagicCarpetDbContext 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 MagicCarpetDbContext 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 Tour InsertTourToDatabaseAndReturn(this MagicCarpetDbContext dbContext, string? id = null, string tourName = "test", string tourCountry = "country", TourType tourType = TourType.Beach, double price = 1)
{
var tour = new Tour() { Id = id ?? Guid.NewGuid().ToString(), TourName = tourName, TourCountry = tourCountry, TourType = tourType, Price = price };
dbContext.Tours.Add(tour);
dbContext.SaveChanges();
return tour;
}
public static TourHistory InsertTourHistoryToDatabaseAndReturn(this MagicCarpetDbContext dbContext, string tourId, double price = 10, DateTime? changeDate = null)
{
var tourHistory = new TourHistory() { Id = Guid.NewGuid().ToString(), TourId = tourId, OldPrice = price, ChangeDate = changeDate ?? DateTime.UtcNow };
dbContext.TourHistories.Add(tourHistory);
dbContext.SaveChanges();
return tourHistory;
}
public static Salary InsertSalaryToDatabaseAndReturn(this MagicCarpetDbContext 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 MagicCarpetDbContext 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)>? tours = null)
{
var sale = new Sale() { EmployeeId = employeeId, ClientId = clientId, SaleDate = saleDate ?? DateTime.UtcNow, Sum = sum, DiscountType = discountType, Discount = discount, IsCancel = isCancel, SaleTours = [] };
if (tours is not null)
{
foreach (var elem in tours)
{
sale.SaleTours.Add(new SaleTour { TourId = elem.Item1, SaleId = sale.Id, Count = elem.Item2, Price = elem.Item3 });
}
}
dbContext.Sales.Add(sale);
dbContext.SaveChanges();
return sale;
}
public static Employee InsertEmployeeToDatabaseAndReturn(this MagicCarpetDbContext 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 MagicCarpetDbContext dbContext, string id) => dbContext.Clients.FirstOrDefault(x => x.Id == id);
public static Post? GetPostFromDatabaseByPostId(this MagicCarpetDbContext dbContext, string id) => dbContext.Posts.FirstOrDefault(x => x.PostId == id && x.IsActual);
public static Post[] GetPostsFromDatabaseByPostId(this MagicCarpetDbContext dbContext, string id) => [.. dbContext.Posts.Where(x => x.PostId == id).OrderByDescending(x => x.ChangeDate)];
public static Tour? GetTourFromDatabaseById(this MagicCarpetDbContext dbContext, string id) => dbContext.Tours.FirstOrDefault(x => x.Id == id);
public static Salary[] GetSalariesFromDatabaseByEmployeeId(this MagicCarpetDbContext dbContext, string id) => [.. dbContext.Salaries.Where(x => x.EmployeeId == id)];
public static Sale? GetSaleFromDatabaseById(this MagicCarpetDbContext dbContext, string id) => dbContext.Sales.Include(x => x.SaleTours).FirstOrDefault(x => x.Id == id);
public static Sale[] GetSalesByClientId(this MagicCarpetDbContext dbContext, string? clientId) => [.. dbContext.Sales.Include(x => x.SaleTours).Where(x => x.ClientId == clientId)];
public static Employee? GetEmployeeFromDatabaseById(this MagicCarpetDbContext dbContext, string id) => dbContext.Employees.FirstOrDefault(x => x.Id == id);
public static void RemoveClientsFromDatabase(this MagicCarpetDbContext dbContext) => dbContext.ExecuteSqlRaw("TRUNCATE \"Clients\" CASCADE;");
public static void RemovePostsFromDatabase(this MagicCarpetDbContext dbContext) => dbContext.ExecuteSqlRaw("TRUNCATE \"Posts\" CASCADE;");
public static void RemoveToursFromDatabase(this MagicCarpetDbContext dbContext) => dbContext.ExecuteSqlRaw("TRUNCATE \"Tours\" CASCADE;");
public static void RemoveSalariesFromDatabase(this MagicCarpetDbContext dbContext) => dbContext.ExecuteSqlRaw("TRUNCATE \"Salaries\" CASCADE;");
public static void RemoveSalesFromDatabase(this MagicCarpetDbContext dbContext) => dbContext.ExecuteSqlRaw("TRUNCATE \"Sales\" CASCADE;");
public static void RemoveEmployeesFromDatabase(this MagicCarpetDbContext dbContext) => dbContext.ExecuteSqlRaw("TRUNCATE \"Employees\" CASCADE;");
private static void ExecuteSqlRaw(this MagicCarpetDbContext dbContext, string command) => dbContext.Database.ExecuteSqlRaw(command);
}

View File

@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<TargetFramework>net9.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
@@ -9,20 +9,30 @@
<IsTestProject>true</IsTestProject>
</PropertyGroup>
<ItemGroup>
<Content Include="appsettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<ExcludeFromSingleFile>true</ExcludeFromSingleFile>
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
</Content>
</ItemGroup>
<ItemGroup>
<PackageReference Include="coverlet.collector" Version="6.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="9.0.2" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="9.0.3" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.8.0" />
<PackageReference Include="Moq" Version="4.20.72" />
<PackageReference Include="NUnit" Version="3.14.0" />
<PackageReference Include="NUnit.Analyzers" Version="3.9.0" />
<PackageReference Include="NUnit3TestAdapter" Version="4.5.0" />
<PackageReference Include="Serilog" Version="4.2.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\MagicCarpetBusinessLogic\MagicCarpetBusinessLogic.csproj" />
<ProjectReference Include="..\MagicCarpetContracts\MagicCarpetContracts.csproj" />
<ProjectReference Include="..\MagicCarpetDatabase\MagicCarpetDatabase.csproj" />
<ProjectReference Include="..\MagicCarpetWebApi\MagicCarpetWebApi.csproj" />
</ItemGroup>
<ItemGroup>

View File

@@ -1,215 +0,0 @@
using MagicCarpetContracts.Exceptions;
using MagicCarpetDatabase.Implementations;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MagicCarpetDatabase.Models;
using MagicCarpetContracts.Enums;
using Microsoft.EntityFrameworkCore;
using MagicCarpetContracts.DataModels;
namespace MagicCarpetTests.StoragesContractsTests;
[TestFixture]
internal class AgencyStorageContractTests : BaseStorageContractTest
{
private AgencyStorageContract _agencyStorageContract;
private Tour _tour;
[SetUp]
public void SetUp()
{
_agencyStorageContract = new AgencyStorageContract(MagicCarpetDbContext);
_tour = InsertTourToDatabaseAndReturn(Guid.NewGuid().ToString(), "name", TourType.Sightseeing);
}
[TearDown]
public void TearDown()
{
MagicCarpetDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Agencies\" CASCADE;");
MagicCarpetDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Tours\" CASCADE;");
}
[Test]
public void Try_GetList_WhenHaveRecords_Test()
{
var agency = InsertAgencyToDatabaseAndReturn(Guid.NewGuid().ToString(), TourType.Sightseeing, 5);
InsertAgencyToDatabaseAndReturn(Guid.NewGuid().ToString(), TourType.Sightseeing, 5);
InsertAgencyToDatabaseAndReturn(Guid.NewGuid().ToString(), TourType.Sightseeing, 5);
var list = _agencyStorageContract.GetList();
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(3));
AssertElement(list.First(), agency);
}
[Test]
public void Try_GetList_WhenNoRecords_Test()
{
var list = _agencyStorageContract.GetList();
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.Empty);
}
[Test]
public void Try_GetElementById_WhenHaveRecord_Test()
{
var agency = InsertAgencyToDatabaseAndReturn(Guid.NewGuid().ToString(), TourType.Sightseeing, 5);
var result = _agencyStorageContract.GetElementById(agency.Id);
AssertElement(result, agency);
}
[Test]
public void Try_GetElementById_WhenNoRecord_Test()
{
Assert.That(() => _agencyStorageContract.GetElementById(Guid.NewGuid().ToString()), Is.Null);
}
[Test]
public void Try_AddElement_WhenValidData_Test()
{
var agency = CreateModel(Guid.NewGuid().ToString(), TourType.Sightseeing, 5, [_tour.Id]);
_agencyStorageContract.AddElement(agency);
var result = GetAgencyFromDatabaseById(agency.Id);
AssertElement(result, agency);
}
[Test]
public void Try_AddElement_WhenHaveRecordWithSameId_Test()
{
var agency = CreateModel(Guid.NewGuid().ToString(), TourType.Sightseeing, 5, [_tour.Id]);
InsertAgencyToDatabaseAndReturn(agency.Id, TourType.Sightseeing, 5, [(_tour.Id, 3)]);
Assert.That(() => _agencyStorageContract.AddElement(agency), Throws.TypeOf<StorageException>());
}
[Test]
public void Try_AddElement_WhenNoHaveTour_Test()
{
var agency = CreateModel(Guid.NewGuid().ToString(), TourType.Sightseeing, 0, [_tour.Id]);
InsertAgencyToDatabaseAndReturn(agency.Id, TourType.Sightseeing, 5, [(_tour.Id, 3)]);
Assert.That(() => _agencyStorageContract.AddElement(agency), Throws.TypeOf<StorageException>());
}
[Test]
public void Try_UpdElement_WhenValidData_Test()
{
var agency = CreateModel(Guid.NewGuid().ToString(), TourType.Sightseeing, 5, [_tour.Id]);
InsertAgencyToDatabaseAndReturn(agency.Id, TourType.Ski, 10, null);
_agencyStorageContract.UpdElement(agency);
var result = GetAgencyFromDatabaseById(agency.Id);
AssertElement(result, agency);
}
[Test]
public void Try_UpdElement_WhenNoRecordWithThisId_Test()
{
var agency = CreateModel(Guid.NewGuid().ToString(), TourType.Sightseeing, 5, [_tour.Id]);
Assert.That(() => _agencyStorageContract.UpdElement(agency), Throws.TypeOf<ElementNotFoundException>());
}
[Test]
public void Try_DelElement_WhenRecordExists_Test()
{
var agency = InsertAgencyToDatabaseAndReturn(Guid.NewGuid().ToString(), TourType.Sightseeing, 5);
_agencyStorageContract.DelElement(agency.Id);
var result = GetAgencyFromDatabaseById(agency.Id);
Assert.That(result, Is.Null);
}
[Test]
public void Try_DelElement_WhenRecordDoesNotExist_ThrowsElementNotFoundException()
{
Assert.That(() => _agencyStorageContract.DelElement(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
}
private Tour InsertTourToDatabaseAndReturn(string id, string name, TourType type)
{
var tour = new Tour { Id = id, TourName = name, TourType = type };
MagicCarpetDbContext.Tours.Add(tour);
MagicCarpetDbContext.SaveChanges();
return tour;
}
private Agency InsertAgencyToDatabaseAndReturn(string id, TourType type, int count, List<(string, int)>? tours = null)
{
var agency = new Agency { Id = id, Type = type, Count = count, Tours = [] };
if (tours is not null)
{
foreach (var elem in tours)
{
agency.Tours.Add(new TourAgency { AgencyId = agency.Id, TourId = elem.Item1, Count = elem.Item2 });
}
}
MagicCarpetDbContext.Agencies.Add(agency);
MagicCarpetDbContext.SaveChanges();
return agency;
}
private static void AssertElement(AgencyDataModel? actual, Agency expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.Id, Is.EqualTo(expected.Id));
Assert.That(actual.Type, Is.EqualTo(expected.Type));
Assert.That(actual.Count, Is.EqualTo(expected.Count));
});
if (expected.Tours is not null)
{
Assert.That(actual.Tours, Is.Not.Null);
Assert.That(actual.Tours, Has.Count.EqualTo(expected.Tours.Count));
for (int i = 0; i < actual.Tours.Count; ++i)
{
Assert.Multiple(() =>
{
Assert.That(actual.Tours[i].TourId, Is.EqualTo(expected.Tours[i].TourId));
Assert.That(actual.Tours[i].Count, Is.EqualTo(expected.Tours[i].Count));
});
}
}
else
{
Assert.That(actual.Tours, Is.Null);
}
}
private static void AssertElement(Agency? actual, AgencyDataModel expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.Id, Is.EqualTo(expected.Id));
Assert.That(actual.Type, Is.EqualTo(expected.Type));
Assert.That(actual.Count, Is.EqualTo(expected.Count));
});
if (expected.Tours is not null)
{
Assert.That(actual.Tours, Is.Not.Null);
Assert.That(actual.Tours, Has.Count.EqualTo(expected.Tours.Count));
for (int i = 0; i < actual.Tours.Count; ++i)
{
Assert.Multiple(() =>
{
Assert.That(actual.Tours[i].TourId, Is.EqualTo(expected.Tours[i].TourId));
Assert.That(actual.Tours[i].Count, Is.EqualTo(expected.Tours[i].Count));
});
}
}
else
{
Assert.That(actual.Tours, Is.Null);
}
}
private static AgencyDataModel CreateModel(string id, TourType type, int count, List<string> toursIds)
{
var tours = toursIds.Select(x => new TourAgencyDataModel(id, x, 1)).ToList();
return new(id, type, count, tours);
}
private Agency? GetAgencyFromDatabaseById(string id)
{
return MagicCarpetDbContext.Agencies.FirstOrDefault(x => x.Id == id);
}
}

View File

@@ -6,7 +6,7 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetTests.StoragesContractsTests;
namespace MagicCarpetTests.StoragesContracts;
internal abstract class BaseStorageContractTest
{

View File

@@ -1,6 +1,7 @@
using MagicCarpetContracts.DataModels;
using MagicCarpetContracts.Enums;
using MagicCarpetContracts.Exceptions;
using MagicCarpetContracts.StoragesContracts;
using MagicCarpetDatabase.Implementations;
using MagicCarpetDatabase.Models;
using Microsoft.EntityFrameworkCore;
@@ -10,18 +11,15 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetTests.StoragesContractsTests;
namespace MagicCarpetTests.StoragesContracts;
[TestFixture]
internal class ClientStorageContractTests : BaseStorageContractTest
{
private ClientStorageContarct _clientStorageContract;
private IClientStorageContract _clientStorageContract;
[SetUp]
public void SetUp()
{
_clientStorageContract = new ClientStorageContarct(MagicCarpetDbContext);
}
public void SetUp() => _clientStorageContract = new ClientStorageContract(MagicCarpetDbContext);
[TearDown]
public void TearDown()

View File

@@ -2,6 +2,7 @@
using MagicCarpetContracts.Exceptions;
using MagicCarpetDatabase.Implementations;
using MagicCarpetDatabase.Models;
using MagicCarpetTests.Infrastructure;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
@@ -9,7 +10,7 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetTests.StoragesContractsTests;
namespace MagicCarpetTests.StoragesContracts;
[TestFixture]
class EmployeeStorageContractTests : BaseStorageContractTest
@@ -25,19 +26,19 @@ class EmployeeStorageContractTests : BaseStorageContractTest
[TearDown]
public void TearDown()
{
MagicCarpetDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Employees\"CASCADE; ");
MagicCarpetDbContext.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 = MagicCarpetDbContext.InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 1", "abc@gmail.com");
MagicCarpetDbContext.InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 2", "abc@gmail.com");
MagicCarpetDbContext.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]
@@ -52,9 +53,9 @@ 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");
MagicCarpetDbContext.InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 1", "abc@gmail.com", postId);
MagicCarpetDbContext.InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 2", "abc@gmail.com", postId);
MagicCarpetDbContext.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));
@@ -64,10 +65,10 @@ 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));
MagicCarpetDbContext.InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 1", "abc@gmail.com", birthDate: DateTime.UtcNow.AddYears(-25));
MagicCarpetDbContext.InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 2", "abc@gmail.com", birthDate: DateTime.UtcNow.AddYears(-21));
MagicCarpetDbContext.InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 3", "abc@gmail.com", birthDate: DateTime.UtcNow.AddYears(-20));
MagicCarpetDbContext.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));
@@ -76,10 +77,10 @@ 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));
MagicCarpetDbContext.InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 1", "abc@gmail.com", employmentDate: DateTime.UtcNow.AddDays(-2));
MagicCarpetDbContext.InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 2", "abc@gmail.com", employmentDate: DateTime.UtcNow.AddDays(-1));
MagicCarpetDbContext.InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 3", "abc@gmail.com", employmentDate: DateTime.UtcNow.AddDays(1));
MagicCarpetDbContext.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));
@@ -89,12 +90,11 @@ 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));
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));
MagicCarpetDbContext.InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 1", "abc@gmail.com", postId, birthDate: DateTime.UtcNow.AddYears(-25), employmentDate: DateTime.UtcNow.AddDays(-2));
MagicCarpetDbContext.InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 2", "abc@gmail.com", postId, birthDate: DateTime.UtcNow.AddYears(-22), employmentDate: DateTime.UtcNow.AddDays(-1));
MagicCarpetDbContext.InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 3", "abc@gmail.com", postId, birthDate: DateTime.UtcNow.AddYears(-21), employmentDate: DateTime.UtcNow.AddDays(-1));
MagicCarpetDbContext.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));
}
@@ -102,7 +102,7 @@ class EmployeeStorageContractTests : BaseStorageContractTest
[Test]
public void Try_GetElementById_WhenHaveRecord_Test()
{
var employee = InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString());
var employee = MagicCarpetDbContext.InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString());
AssertElement(_employeeStorageContract.GetElementById(employee.Id), employee);
}
@@ -115,7 +115,7 @@ class EmployeeStorageContractTests : BaseStorageContractTest
[Test]
public void Try_GetElementByFIO_WhenHaveRecord_Test()
{
var employee = InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString());
var employee = MagicCarpetDbContext.InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString());
AssertElement(_employeeStorageContract.GetElementByFIO(employee.FIO), employee);
}
@@ -130,14 +130,14 @@ class EmployeeStorageContractTests : BaseStorageContractTest
{
var employee = CreateModel(Guid.NewGuid().ToString());
_employeeStorageContract.AddElement(employee);
AssertElement(GetEmployeeFromDatabase(employee.Id), employee);
AssertElement(MagicCarpetDbContext.GetEmployeeFromDatabaseById(employee.Id), employee);
}
[Test]
public void Try_AddElement_WhenHaveRecordWithSameId_Test()
{
var employee = CreateModel(Guid.NewGuid().ToString());
InsertEmployeeToDatabaseAndReturn(employee.Id);
MagicCarpetDbContext.InsertEmployeeToDatabaseAndReturn(employee.Id);
Assert.That(() => _employeeStorageContract.AddElement(employee), Throws.TypeOf<ElementExistsException>());
}
@@ -145,9 +145,9 @@ class EmployeeStorageContractTests : BaseStorageContractTest
public void Try_UpdElement_Test()
{
var employee = CreateModel(Guid.NewGuid().ToString(), "New Fio");
InsertEmployeeToDatabaseAndReturn(employee.Id);
MagicCarpetDbContext.InsertEmployeeToDatabaseAndReturn(employee.Id);
_employeeStorageContract.UpdElement(employee);
AssertElement(GetEmployeeFromDatabase(employee.Id), employee);
AssertElement(MagicCarpetDbContext.GetEmployeeFromDatabaseById(employee.Id), employee);
}
[Test]
@@ -160,16 +160,16 @@ class EmployeeStorageContractTests : BaseStorageContractTest
public void Try_UpdElement_WhenNoRecordWasDeleted_Test()
{
var employee = CreateModel(Guid.NewGuid().ToString());
InsertEmployeeToDatabaseAndReturn(employee.Id, isDeleted: true);
MagicCarpetDbContext.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 = MagicCarpetDbContext.InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString());
_employeeStorageContract.DelElement(employee.Id);
var element = GetEmployeeFromDatabase(employee.Id);
var element = MagicCarpetDbContext.GetEmployeeFromDatabaseById(employee.Id);
Assert.That(element, Is.Not.Null);
Assert.That(element.IsDeleted);
}
@@ -184,18 +184,10 @@ class EmployeeStorageContractTests : BaseStorageContractTest
public void Try_DelElement_WhenNoRecordWasDeleted_Test()
{
var employee = CreateModel(Guid.NewGuid().ToString());
InsertEmployeeToDatabaseAndReturn(employee.Id, isDeleted: true);
MagicCarpetDbContext.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 };
MagicCarpetDbContext.Employees.Add(employee);
MagicCarpetDbContext.SaveChanges();
return employee;
}
private static void AssertElement(EmployeeDataModel? actual, Employee expected)
{
Assert.That(actual, Is.Not.Null);
@@ -212,9 +204,7 @@ 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) => MagicCarpetDbContext.Employees.FirstOrDefault(x => x.Id == id);
new(id, fio, email, postId ?? Guid.NewGuid().ToString(), birthDate ?? DateTime.UtcNow.AddYears(-20), employmentDate ?? DateTime.UtcNow, isDeleted);
private static void AssertElement(Employee? actual, EmployeeDataModel expected)
{

View File

@@ -1,6 +1,7 @@
using MagicCarpetContracts.DataModels;
using MagicCarpetDatabase.Implementations;
using MagicCarpetDatabase.Models;
using MagicCarpetTests.Infrastructure;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
@@ -8,7 +9,7 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetTests.StoragesContractsTests;
namespace MagicCarpetTests.StoragesContracts;
[TestFixture]
internal class SalaryStorageContractTests : BaseStorageContractTest
@@ -20,26 +21,26 @@ internal class SalaryStorageContractTests : BaseStorageContractTest
public void SetUp()
{
_salaryStorageContract = new SalaryStorageContract(MagicCarpetDbContext);
_employee = InsertEmployeeToDatabaseAndReturn();
_employee = MagicCarpetDbContext.InsertEmployeeToDatabaseAndReturn();
}
[TearDown]
public void TearDown()
{
MagicCarpetDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Salaries\" CASCADE;");
MagicCarpetDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Employees\" CASCADE;");
MagicCarpetDbContext.RemoveSalariesFromDatabase();
MagicCarpetDbContext.RemoveEmployeesFromDatabase();
}
[Test]
public void Try_GetList_WhenHaveRecords_Test()
{
var salary = InsertSalaryToDatabaseAndReturn(_employee.Id, employeeSalary: 100);
InsertSalaryToDatabaseAndReturn(_employee.Id);
InsertSalaryToDatabaseAndReturn(_employee.Id);
var salary = MagicCarpetDbContext.InsertSalaryToDatabaseAndReturn(_employee.Id, employeeSalary: 100);
MagicCarpetDbContext.InsertSalaryToDatabaseAndReturn(_employee.Id);
MagicCarpetDbContext.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]
@@ -53,12 +54,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));
MagicCarpetDbContext.InsertSalaryToDatabaseAndReturn(_employee.Id, salaryDate: DateTime.UtcNow.AddDays(-2));
MagicCarpetDbContext.InsertSalaryToDatabaseAndReturn(_employee.Id, salaryDate: DateTime.UtcNow.AddDays(-1).AddMinutes(-5));
MagicCarpetDbContext.InsertSalaryToDatabaseAndReturn(_employee.Id, salaryDate: DateTime.UtcNow.AddDays(-1).AddMinutes(5));
MagicCarpetDbContext.InsertSalaryToDatabaseAndReturn(_employee.Id, salaryDate: DateTime.UtcNow.AddDays(1).AddMinutes(-5));
MagicCarpetDbContext.InsertSalaryToDatabaseAndReturn(_employee.Id, salaryDate: DateTime.UtcNow.AddDays(1).AddMinutes(5));
MagicCarpetDbContext.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(() =>
@@ -70,10 +71,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 = MagicCarpetDbContext.InsertEmployeeToDatabaseAndReturn("name 2");
MagicCarpetDbContext.InsertSalaryToDatabaseAndReturn(_employee.Id);
MagicCarpetDbContext.InsertSalaryToDatabaseAndReturn(_employee.Id);
MagicCarpetDbContext.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(() =>
@@ -86,13 +87,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 = MagicCarpetDbContext.InsertEmployeeToDatabaseAndReturn(fio: "name 2");
MagicCarpetDbContext.InsertSalaryToDatabaseAndReturn(_employee.Id, salaryDate: DateTime.UtcNow.AddDays(-2));
MagicCarpetDbContext.InsertSalaryToDatabaseAndReturn(_employee.Id, salaryDate: DateTime.UtcNow.AddDays(-1).AddMinutes(5));
MagicCarpetDbContext.InsertSalaryToDatabaseAndReturn(employee.Id, salaryDate: DateTime.UtcNow.AddDays(-1).AddMinutes(5));
MagicCarpetDbContext.InsertSalaryToDatabaseAndReturn(_employee.Id, salaryDate: DateTime.UtcNow.AddDays(1).AddMinutes(-5));
MagicCarpetDbContext.InsertSalaryToDatabaseAndReturn(employee.Id, salaryDate: DateTime.UtcNow.AddDays(1).AddMinutes(-5));
MagicCarpetDbContext.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(() =>
@@ -107,23 +108,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 };
MagicCarpetDbContext.Employees.Add(employee);
MagicCarpetDbContext.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 };
MagicCarpetDbContext.Salaries.Add(salary);
MagicCarpetDbContext.SaveChanges();
return salary;
AssertElement(MagicCarpetDbContext.GetSalariesFromDatabaseByEmployeeId(_employee.Id).First(), salary);
}
private static void AssertElement(SalaryDataModel? actual, Salary expected)
@@ -139,8 +124,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) => MagicCarpetDbContext.Salaries.FirstOrDefault(x => x.EmployeeId == id);
private static void AssertElement(Salary? actual, SalaryDataModel expected)
{
Assert.That(actual, Is.Not.Null);

View File

@@ -1,8 +1,9 @@
using MagicCarpetContracts.DataModels;
 using MagicCarpetContracts.DataModels;
using MagicCarpetContracts.Enums;
using MagicCarpetContracts.Exceptions;
using MagicCarpetDatabase.Implementations;
using MagicCarpetDatabase.Models;
using MagicCarpetTests.Infrastructure;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
@@ -11,12 +12,12 @@ using System.Text;
using System.Threading.Tasks;
using static NUnit.Framework.Internal.OSPlatform;
namespace MagicCarpetTests.StoragesContractsTests;
namespace MagicCarpetTests.StoragesContracts;
[TestFixture]
internal class SaleStorageContractTests : BaseStorageContractTest
{
private SaleStorageContract _saleStorageContract;
private SaleStorageContract _saletStorageContract;
private Client _client;
private Employee _employee;
private Tour _tour;
@@ -24,28 +25,28 @@ internal class SaleStorageContractTests : BaseStorageContractTest
[SetUp]
public void SetUp()
{
_saleStorageContract = new SaleStorageContract(MagicCarpetDbContext);
_client = InsertClientToDatabaseAndReturn();
_employee = InsertEmployeeToDatabaseAndReturn();
_tour = InsertTourToDatabaseAndReturn();
_saletStorageContract = new SaleStorageContract(MagicCarpetDbContext);
_client = MagicCarpetDbContext.InsertClientToDatabaseAndReturn();
_employee = MagicCarpetDbContext.InsertEmployeeToDatabaseAndReturn();
_tour = MagicCarpetDbContext.InsertTourToDatabaseAndReturn();
}
[TearDown]
public void TearDown()
{
MagicCarpetDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Sales\" CASCADE;");
MagicCarpetDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Clients\" CASCADE;");
MagicCarpetDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Employees\" CASCADE;");
MagicCarpetDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Tours\" CASCADE;");
MagicCarpetDbContext.RemoveSalesFromDatabase();
MagicCarpetDbContext.RemoveEmployeesFromDatabase();
MagicCarpetDbContext.RemoveClientsFromDatabase();
MagicCarpetDbContext.RemoveToursFromDatabase();
}
[Test]
public void Try_GetList_WhenHaveRecords_Test()
{
var sale = InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, tours: [(_tour.Id, 1)]);
InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, tours: [(_tour.Id, 5)]);
InsertSaleToDatabaseAndReturn(_employee.Id, null, tours: [(_tour.Id, 10)]);
var list = _saleStorageContract.GetList();
var sale = MagicCarpetDbContext.InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, tours: [(_tour.Id, 1, 1.2)]);
MagicCarpetDbContext.InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, tours: [(_tour.Id, 5, 1.2)]);
MagicCarpetDbContext.InsertSaleToDatabaseAndReturn(_employee.Id, null, tours: [(_tour.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);
@@ -54,7 +55,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);
}
@@ -62,11 +63,11 @@ internal class SaleStorageContractTests : BaseStorageContractTest
[Test]
public void Try_GetList_ByPeriod_Test()
{
InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(-3), tours: [(_tour.Id, 1)]);
InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(3), tours: [(_tour.Id, 1)]);
InsertSaleToDatabaseAndReturn(_employee.Id, null, saleDate: DateTime.UtcNow.AddDays(1).AddMinutes(-3), tours: [(_tour.Id, 1)]);
InsertSaleToDatabaseAndReturn(_employee.Id, null, saleDate: DateTime.UtcNow.AddDays(1).AddMinutes(3), tours: [(_tour.Id, 1)]);
var list = _saleStorageContract.GetList(startDate: DateTime.UtcNow.AddDays(-1), endDate: DateTime.UtcNow.AddDays(1));
MagicCarpetDbContext.InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(-3), tours: [(_tour.Id, 1, 1.2)]);
MagicCarpetDbContext.InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(3), tours: [(_tour.Id, 1, 1.2)]);
MagicCarpetDbContext.InsertSaleToDatabaseAndReturn(_employee.Id, null, saleDate: DateTime.UtcNow.AddDays(1).AddMinutes(-3), tours: [(_tour.Id, 1, 1.2)]);
MagicCarpetDbContext.InsertSaleToDatabaseAndReturn(_employee.Id, null, saleDate: DateTime.UtcNow.AddDays(1).AddMinutes(3), tours: [(_tour.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));
}
@@ -74,11 +75,11 @@ internal class SaleStorageContractTests : BaseStorageContractTest
[Test]
public void Try_GetList_ByEmployeeId_Test()
{
var employee = InsertEmployeeToDatabaseAndReturn("Other employee");
InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, tours: [(_tour.Id, 1)]);
InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, tours: [(_tour.Id, 1)]);
InsertSaleToDatabaseAndReturn(employee.Id, null, tours: [(_tour.Id, 1)]);
var list = _saleStorageContract.GetList(employeeId: _employee.Id);
var employee = MagicCarpetDbContext.InsertEmployeeToDatabaseAndReturn(fio: "Other employee");
MagicCarpetDbContext.InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, tours: [(_tour.Id, 1, 1.2)]);
MagicCarpetDbContext.InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, tours: [(_tour.Id, 1, 1.2)]);
MagicCarpetDbContext.InsertSaleToDatabaseAndReturn(employee.Id, null, tours: [(_tour.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));
@@ -87,12 +88,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, tours: [(_tour.Id, 1)]);
InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, tours: [(_tour.Id, 1)]);
InsertSaleToDatabaseAndReturn(_employee.Id, client.Id, tours: [(_tour.Id, 1)]);
InsertSaleToDatabaseAndReturn(_employee.Id, null, tours: [(_tour.Id, 1)]);
var list = _saleStorageContract.GetList(clientId: _client.Id);
var client = MagicCarpetDbContext.InsertClientToDatabaseAndReturn(fio: "Other fio", phoneNumber: "+8-888-888-88-88");
MagicCarpetDbContext.InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, tours: [(_tour.Id, 1, 1.2)]);
MagicCarpetDbContext.InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, tours: [(_tour.Id, 1, 1.2)]);
MagicCarpetDbContext.InsertSaleToDatabaseAndReturn(_employee.Id, client.Id, tours: [(_tour.Id, 1, 1.2)]);
MagicCarpetDbContext.InsertSaleToDatabaseAndReturn(_employee.Id, null, tours: [(_tour.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));
@@ -101,31 +102,31 @@ internal class SaleStorageContractTests : BaseStorageContractTest
[Test]
public void Try_GetList_ByTourId_Test()
{
var tour = InsertTourToDatabaseAndReturn("Other name");
InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, tours: [(_tour.Id, 5)]);
InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, tours: [(_tour.Id, 1), (tour.Id, 4)]);
InsertSaleToDatabaseAndReturn(_employee.Id, null, tours: [(tour.Id, 1)]);
InsertSaleToDatabaseAndReturn(_employee.Id, null, tours: [(tour.Id, 1), (_tour.Id, 1)]);
var list = _saleStorageContract.GetList(tourId: _tour.Id);
var tour = MagicCarpetDbContext.InsertTourToDatabaseAndReturn(tourName: "Other name");
MagicCarpetDbContext.InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, tours: [(_tour.Id, 5, 1.2)]);
MagicCarpetDbContext.InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, tours: [(_tour.Id, 1, 1.2), (tour.Id, 4, 1.2)]);
MagicCarpetDbContext.InsertSaleToDatabaseAndReturn(_employee.Id, null, tours: [(tour.Id, 1, 1.2)]);
MagicCarpetDbContext.InsertSaleToDatabaseAndReturn(_employee.Id, null, tours: [(tour.Id, 1, 1.2), (_tour.Id, 1, 1.2)]);
var list = _saletStorageContract.GetList(tourId: _tour.Id);
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(3));
Assert.That(list.All(x => x.Tours.Any(y => y.TourId == _tour.Id)));
Assert.That(list.All(x => x.Tours!.Any(y => y.TourId == _tour.Id)));
}
[Test]
public void Try_GetList_ByAllParameters_Test()
{
var employee = InsertEmployeeToDatabaseAndReturn("Other employee");
var client = InsertClientToDatabaseAndReturn("Other fio", "+8-888-888-88-88");
var tour = InsertTourToDatabaseAndReturn("Other name");
InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(-3), tours: [(_tour.Id, 1)]);
InsertSaleToDatabaseAndReturn(employee.Id, null, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(3), tours: [(_tour.Id, 1)]);
InsertSaleToDatabaseAndReturn(employee.Id, _client.Id, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(3), tours: [(_tour.Id, 1)]);
InsertSaleToDatabaseAndReturn(employee.Id, _client.Id, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(3), tours: [(tour.Id, 1)]);
InsertSaleToDatabaseAndReturn(_employee.Id, client.Id, saleDate: DateTime.UtcNow.AddDays(1).AddMinutes(-3), tours: [(_tour.Id, 1)]);
InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, saleDate: DateTime.UtcNow.AddDays(1).AddMinutes(-3), tours: [(tour.Id, 1)]);
InsertSaleToDatabaseAndReturn(employee.Id, null, saleDate: DateTime.UtcNow.AddDays(1).AddMinutes(-3), tours: [(_tour.Id, 1)]);
var list = _saleStorageContract.GetList(startDate: DateTime.UtcNow.AddDays(-1), endDate: DateTime.UtcNow.AddDays(1), employeeId: _employee.Id, clientId: _client.Id, tourId: tour.Id);
var employee = MagicCarpetDbContext.InsertEmployeeToDatabaseAndReturn(fio: "Other employee");
var client = MagicCarpetDbContext.InsertClientToDatabaseAndReturn(fio: "Other fio", phoneNumber: "+8-888-888-88-88");
var tour = MagicCarpetDbContext.InsertTourToDatabaseAndReturn(tourName: "Other name");
MagicCarpetDbContext.InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(-3), tours: [(_tour.Id, 1, 1.2)]);
MagicCarpetDbContext.InsertSaleToDatabaseAndReturn(employee.Id, null, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(3), tours: [(_tour.Id, 1, 1.2)]);
MagicCarpetDbContext.InsertSaleToDatabaseAndReturn(employee.Id, _client.Id, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(3), tours: [(_tour.Id, 1, 1.2)]);
MagicCarpetDbContext.InsertSaleToDatabaseAndReturn(employee.Id, _client.Id, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(3), tours: [(tour.Id, 1, 1.2)]);
MagicCarpetDbContext.InsertSaleToDatabaseAndReturn(_employee.Id, client.Id, saleDate: DateTime.UtcNow.AddDays(1).AddMinutes(-3), tours: [(_tour.Id, 1, 1.2)]);
MagicCarpetDbContext.InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, saleDate: DateTime.UtcNow.AddDays(1).AddMinutes(-3), tours: [(tour.Id, 1, 1.2)]);
MagicCarpetDbContext.InsertSaleToDatabaseAndReturn(employee.Id, null, saleDate: DateTime.UtcNow.AddDays(1).AddMinutes(-3), tours: [(_tour.Id, 1, 1.2)]);
var list = _saletStorageContract.GetList(startDate: DateTime.UtcNow.AddDays(-1), endDate: DateTime.UtcNow.AddDays(1), employeeId: _employee.Id, clientId: _client.Id, tourId: tour.Id);
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(1));
}
@@ -133,46 +134,46 @@ internal class SaleStorageContractTests : BaseStorageContractTest
[Test]
public void Try_GetElementById_WhenHaveRecord_Test()
{
var sale = InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, tours: [(_tour.Id, 1)]);
AssertElement(_saleStorageContract.GetElementById(sale.Id), sale);
var sale = MagicCarpetDbContext.InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, tours: [(_tour.Id, 1, 1.2)]);
AssertElement(_saletStorageContract.GetElementById(sale.Id), sale);
}
[Test]
public void Try_GetElementById_WhenNoRecord_Test()
{
InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, tours: [(_tour.Id, 1)]);
Assert.That(() => _saleStorageContract.GetElementById(Guid.NewGuid().ToString()), Is.Null);
MagicCarpetDbContext.InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, tours: [(_tour.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, tours: [(_tour.Id, 1)], isCancel: true);
AssertElement(_saleStorageContract.GetElementById(sale.Id), sale);
var sale = MagicCarpetDbContext.InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, tours: [(_tour.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, [_tour.Id]);
_saleStorageContract.AddElement(sale);
AssertElement(GetSaleFromDatabaseById(sale.Id), sale);
var sale = CreateModel(Guid.NewGuid().ToString(), _employee.Id, _client.Id, DiscountType.RegularCustomer, false, [_tour.Id]);
_saletStorageContract.AddElement(sale);
AssertElement(MagicCarpetDbContext.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, [_tour.Id]);
Assert.That(() => _saleStorageContract.AddElement(sale), Throws.Nothing);
AssertElement(GetSaleFromDatabaseById(sale.Id), CreateModel(sale.Id, _employee.Id, _client.Id, 1, DiscountType.RegularCustomer, 1, false, [_tour.Id]));
var sale = CreateModel(Guid.NewGuid().ToString(), _employee.Id, _client.Id, DiscountType.RegularCustomer, true, [_tour.Id]);
Assert.That(() => _saletStorageContract.AddElement(sale), Throws.Nothing);
AssertElement(MagicCarpetDbContext.GetSaleFromDatabaseById(sale.Id), CreateModel(sale.Id, _employee.Id, _client.Id, DiscountType.RegularCustomer, false, [_tour.Id]));
}
[Test]
public void Try_DelElement_Test()
{
var sale = InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, tours: [(_tour.Id, 1)], isCancel: false);
_saleStorageContract.DelElement(sale.Id);
var element = GetSaleFromDatabaseById(sale.Id);
var sale = MagicCarpetDbContext.InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, tours: [(_tour.Id, 1, 1.2)], isCancel: false);
_saletStorageContract.DelElement(sale.Id);
var element = MagicCarpetDbContext.GetSaleFromDatabaseById(sale.Id);
Assert.Multiple(() =>
{
Assert.That(element, Is.Not.Null);
@@ -183,53 +184,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, tours: [(_tour.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 };
MagicCarpetDbContext.Clients.Add(client);
MagicCarpetDbContext.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() };
MagicCarpetDbContext.Employees.Add(employee);
MagicCarpetDbContext.SaveChanges();
return employee;
}
private Tour InsertTourToDatabaseAndReturn(string tourName = "test", TourType tourType = TourType.Sightseeing, double price = 1)
{
var tour = new Tour() { Id = Guid.NewGuid().ToString(), TourName = tourName, TourType = tourType, Price = price };
MagicCarpetDbContext.Tours.Add(tour);
MagicCarpetDbContext.SaveChanges();
return tour;
}
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)>? tours = null)
{
var sale = new Sale() { EmployeeId = employeeId, ClientId = clientId, SaleDate = saleDate ?? DateTime.UtcNow, Sum = sum, DiscountType = discountType, Discount = discount, IsCancel = isCancel, SaleTours = [] };
if (tours is not null)
{
foreach (var elem in tours)
{
sale.SaleTours.Add(new SaleTour { TourId = elem.Item1, SaleId = sale.Id, Count = elem.Item2 });
}
}
MagicCarpetDbContext.Sales.Add(sale);
MagicCarpetDbContext.SaveChanges();
return sale;
var sale = MagicCarpetDbContext.InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, tours: [(_tour.Id, 1, 1.2)], isCancel: true);
Assert.That(() => _saletStorageContract.DelElement(sale.Id), Throws.TypeOf<ElementDeletedException>());
}
private static void AssertElement(SaleDataModel? actual, Sale expected)
@@ -264,14 +226,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> tourIds)
private static SaleDataModel CreateModel(string id, string employeeId, string? clientId, DiscountType discountType, bool isCancel, List<string> tourIds)
{
var tours = tourIds.Select(x => new SaleTourDataModel(id, x, 1)).ToList();
return new(id, employeeId, clientId, sum, discountType, discount, isCancel, tours);
var tours = tourIds.Select(x => new SaleTourDataModel(id, x, 1, 1.1)).ToList();
return new(id, employeeId, clientId, discountType, isCancel, tours);
}
private Sale? GetSaleFromDatabaseById(string id) => MagicCarpetDbContext.Sales.Include(x => x.SaleTours).FirstOrDefault(x => x.Id == id);
private static void AssertElement(Sale? actual, SaleDataModel expected)
{
Assert.That(actual, Is.Not.Null);
@@ -295,6 +255,7 @@ internal class SaleStorageContractTests : BaseStorageContractTest
{
Assert.That(actual.SaleTours[i].TourId, Is.EqualTo(expected.Tours[i].TourId));
Assert.That(actual.SaleTours[i].Count, Is.EqualTo(expected.Tours[i].Count));
Assert.That(actual.SaleTours[i].Price, Is.EqualTo(expected.Tours[i].Price));
});
}
}

View File

@@ -1,191 +0,0 @@
using MagicCarpetContracts.DataModels;
using MagicCarpetContracts.Enums;
using MagicCarpetContracts.Exceptions;
using MagicCarpetDatabase.Implementations;
using MagicCarpetDatabase.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetTests.StoragesContractsTests;
[TestFixture]
internal class SuppliesStorageContractTests : BaseStorageContractTest
{
private SuppliesStorageContract _suppliesStorageContract;
private Tour _tour;
[SetUp]
public void SetUp()
{
_suppliesStorageContract = new SuppliesStorageContract(MagicCarpetDbContext);
_tour = InsertTourToDatabaseAndReturn();
}
[TearDown]
public void TearDown()
{
MagicCarpetDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Supplieses\" CASCADE;");
MagicCarpetDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Tours\" CASCADE;");
}
[Test]
public void Try_GetList_WhenHaveRecords_Test()
{
var supply = InsertSupplyToDatabaseAndReturn(Guid.NewGuid().ToString(), TourType.Ski, 5);
InsertSupplyToDatabaseAndReturn(Guid.NewGuid().ToString(), TourType.Ski, 5);
InsertSupplyToDatabaseAndReturn(Guid.NewGuid().ToString(), TourType.Ski, 5);
var list = _suppliesStorageContract.GetList();
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(3));
AssertElement(list.First(), supply);
}
[Test]
public void Try_GetList_WhenNoRecords_Test()
{
var list = _suppliesStorageContract.GetList();
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.Empty);
}
[Test]
public void Try_GetElementById_WhenHaveRecord_Test()
{
var supply = InsertSupplyToDatabaseAndReturn(Guid.NewGuid().ToString(), TourType.Ski, 5);
AssertElement(_suppliesStorageContract.GetElementById(supply.Id), supply);
}
[Test]
public void Try_GetElementById_WhenNoRecord_Test()
{
Assert.That(() => _suppliesStorageContract.GetElementById(Guid.NewGuid().ToString()), Is.Null);
}
[Test]
public void Try_AddElement_Test()
{
var supply = CreateModel(Guid.NewGuid().ToString(), TourType.Ski, 5, [_tour.Id]);
_suppliesStorageContract.AddElement(supply);
AssertElement(GetSupplyFromDatabaseById(supply.Id), supply);
}
[Test]
public void Try_AddElement_WhenHaveRecordWithSameId_Test()
{
var supply = CreateModel(Guid.NewGuid().ToString(), TourType.Ski, 5, [_tour.Id]);
InsertSupplyToDatabaseAndReturn(supply.Id, TourType.Ski, 5, [(_tour.Id, 3)]);
Assert.That(() => _suppliesStorageContract.AddElement(supply), Throws.TypeOf<StorageException>());
}
[Test]
public void Try_UpdElement_Test()
{
var supply = CreateModel(Guid.NewGuid().ToString(), TourType.Ski, 5, [_tour.Id]);
InsertSupplyToDatabaseAndReturn(supply.Id, TourType.Ski, 5, null);
_suppliesStorageContract.UpdElement(supply);
AssertElement(GetSupplyFromDatabaseById(supply.Id), supply);
}
[Test]
public void Try_UpdElement_WhenNoRecordWithThisId_Test()
{
Assert.That(() => _suppliesStorageContract.UpdElement(CreateModel(Guid.NewGuid().ToString(), TourType.Ski, 5, [_tour.Id])), Throws.TypeOf<ElementNotFoundException>());
}
private Tour InsertTourToDatabaseAndReturn()
{
var tour = new Tour { Id = Guid.NewGuid().ToString(), TourName = "Test Tour", TourType = TourType.Ski };
MagicCarpetDbContext.Tours.Add(tour);
MagicCarpetDbContext.SaveChanges();
return tour;
}
private Supplies InsertSupplyToDatabaseAndReturn(string id, TourType type, int count, List<(string, int)>? tours = null)
{
var supply = new Supplies { Id = id, Type = type, ProductuionDate = DateTime.UtcNow, Count = count, Tours = [] };
if (tours is not null)
{
foreach (var elem in tours)
{
supply.Tours.Add(new TourSupplies { SuppliesId = supply.Id, TourId = elem.Item1, Count = elem.Item2 });
}
}
MagicCarpetDbContext.Supplieses.Add(supply);
MagicCarpetDbContext.SaveChanges();
return supply;
}
private static void AssertElement(SuppliesDataModel? actual, Supplies expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.Id, Is.EqualTo(expected.Id));
Assert.That(actual.Type, Is.EqualTo(expected.Type));
Assert.That(actual.ProductuionDate, Is.EqualTo(expected.ProductuionDate));
Assert.That(actual.Count, Is.EqualTo(expected.Count));
});
if (expected.Tours is not null)
{
Assert.That(actual.Tours, Is.Not.Null);
Assert.That(actual.Tours, Has.Count.EqualTo(expected.Tours.Count));
for (int i = 0; i < actual.Tours.Count; ++i)
{
Assert.Multiple(() =>
{
Assert.That(actual.Tours[i].TourId, Is.EqualTo(expected.Tours[i].TourId));
Assert.That(actual.Tours[i].Count, Is.EqualTo(expected.Tours[i].Count));
});
}
}
else
{
Assert.That(actual.Tours, Is.Null);
}
}
private static void AssertElement(Supplies? actual, SuppliesDataModel expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.Id, Is.EqualTo(expected.Id));
Assert.That(actual.Type, Is.EqualTo(expected.Type));
Assert.That(actual.ProductuionDate, Is.EqualTo(expected.ProductuionDate));
Assert.That(actual.Count, Is.EqualTo(expected.Count));
});
if (expected.Tours is not null)
{
Assert.That(actual.Tours, Is.Not.Null);
Assert.That(actual.Tours, Has.Count.EqualTo(expected.Tours.Count));
for (int i = 0; i < actual.Tours.Count; ++i)
{
Assert.Multiple(() =>
{
Assert.That(actual.Tours[i].TourId, Is.EqualTo(expected.Tours[i].TourId));
Assert.That(actual.Tours[i].Count, Is.EqualTo(expected.Tours[i].Count));
});
}
}
else
{
Assert.That(actual.Tours, Is.Null);
}
}
private static SuppliesDataModel CreateModel(string id, TourType type, int count, List<string> toursIds)
{
var tours = toursIds.Select(x => new TourSuppliesDataModel(id, x, 1)).ToList();
return new(id, type, DateTime.UtcNow, count, tours);
}
private Supplies? GetSupplyFromDatabaseById(string id)
{
return MagicCarpetDbContext.Supplieses.FirstOrDefault(x => x.Id == id);
}
}

View File

@@ -3,6 +3,7 @@ using MagicCarpetContracts.Enums;
using MagicCarpetContracts.Exceptions;
using MagicCarpetDatabase.Implementations;
using MagicCarpetDatabase.Models;
using MagicCarpetTests.Infrastructure;
using Microsoft.EntityFrameworkCore;
using Moq;
using System;
@@ -12,7 +13,7 @@ using System.Text;
using System.Threading.Tasks;
using static NUnit.Framework.Internal.OSPlatform;
namespace MagicCarpetTests.StoragesContractsTests;
namespace MagicCarpetTests.StoragesContracts;
[TestFixture]
internal class TourStorageContractTests : BaseStorageContractTest
@@ -28,15 +29,15 @@ internal class TourStorageContractTests : BaseStorageContractTest
[TearDown]
public void TearDown()
{
MagicCarpetDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Tours\" CASCADE;");
MagicCarpetDbContext.RemoveToursFromDatabase();
}
[Test]
public void Try_GetList_WhenHaveRecords_Test()
{
var tour = InsertTourToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 1");
InsertTourToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 2");
InsertTourToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 3");
var tour = MagicCarpetDbContext.InsertTourToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 1");
MagicCarpetDbContext.InsertTourToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 2");
MagicCarpetDbContext.InsertTourToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 3");
var list = _tourStorageContract.GetList();
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(3));
@@ -54,10 +55,10 @@ internal class TourStorageContractTests : BaseStorageContractTest
[Test]
public void Try_GetHistoryByTourId_WhenHaveRecords_Test()
{
var tour = InsertTourToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 1");
InsertTourHistoryToDatabaseAndReturn(tour.Id, 20, DateTime.UtcNow.AddDays(-1));
InsertTourHistoryToDatabaseAndReturn(tour.Id, 30, DateTime.UtcNow.AddMinutes(-10));
InsertTourHistoryToDatabaseAndReturn(tour.Id, 40, DateTime.UtcNow.AddDays(1));
var tour = MagicCarpetDbContext.InsertTourToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 1");
MagicCarpetDbContext.InsertTourHistoryToDatabaseAndReturn(tour.Id, 20, DateTime.UtcNow.AddDays(-1));
MagicCarpetDbContext.InsertTourHistoryToDatabaseAndReturn(tour.Id, 30, DateTime.UtcNow.AddMinutes(-10));
MagicCarpetDbContext.InsertTourHistoryToDatabaseAndReturn(tour.Id, 40, DateTime.UtcNow.AddDays(1));
var list = _tourStorageContract.GetHistoryByTourId(tour.Id);
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(3));
@@ -66,10 +67,10 @@ internal class TourStorageContractTests : BaseStorageContractTest
[Test]
public void Try_GetHistoryByTourId_WhenNoRecords_Test()
{
var tour = InsertTourToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 1");
InsertTourHistoryToDatabaseAndReturn(tour.Id, 20, DateTime.UtcNow.AddDays(-1));
InsertTourHistoryToDatabaseAndReturn(tour.Id, 30, DateTime.UtcNow.AddMinutes(-10));
InsertTourHistoryToDatabaseAndReturn(tour.Id, 40, DateTime.UtcNow.AddDays(1));
var tour = MagicCarpetDbContext.InsertTourToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 1");
MagicCarpetDbContext.InsertTourHistoryToDatabaseAndReturn(tour.Id, 20, DateTime.UtcNow.AddDays(-1));
MagicCarpetDbContext.InsertTourHistoryToDatabaseAndReturn(tour.Id, 30, DateTime.UtcNow.AddMinutes(-10));
MagicCarpetDbContext.InsertTourHistoryToDatabaseAndReturn(tour.Id, 40, DateTime.UtcNow.AddDays(1));
var list = _tourStorageContract.GetHistoryByTourId(Guid.NewGuid().ToString());
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
@@ -78,28 +79,28 @@ internal class TourStorageContractTests : BaseStorageContractTest
[Test]
public void Try_GetElementById_WhenHaveRecord_Test()
{
var tour = InsertTourToDatabaseAndReturn(Guid.NewGuid().ToString());
var tour = MagicCarpetDbContext.InsertTourToDatabaseAndReturn(Guid.NewGuid().ToString());
AssertElement(_tourStorageContract.GetElementById(tour.Id), tour);
}
[Test]
public void Try_GetElementById_WhenNoRecord_Test()
{
InsertTourToDatabaseAndReturn(Guid.NewGuid().ToString());
MagicCarpetDbContext.InsertTourToDatabaseAndReturn(Guid.NewGuid().ToString());
Assert.That(() => _tourStorageContract.GetElementById(Guid.NewGuid().ToString()), Is.Null);
}
[Test]
public void Try_GetElementByName_WhenHaveRecord_Test()
{
var tour = InsertTourToDatabaseAndReturn(Guid.NewGuid().ToString());
var tour = MagicCarpetDbContext.InsertTourToDatabaseAndReturn(Guid.NewGuid().ToString());
AssertElement(_tourStorageContract.GetElementByName(tour.TourName), tour);
}
[Test]
public void Try_GetElementByName_WhenNoRecord_Test()
{
InsertTourToDatabaseAndReturn(Guid.NewGuid().ToString());
MagicCarpetDbContext.InsertTourToDatabaseAndReturn(Guid.NewGuid().ToString());
Assert.That(() => _tourStorageContract.GetElementByName("name"), Is.Null);
}
@@ -108,14 +109,14 @@ internal class TourStorageContractTests : BaseStorageContractTest
{
var tour = CreateModel(Guid.NewGuid().ToString());
_tourStorageContract.AddElement(tour);
AssertElement(GetTourFromDatabaseById(tour.Id), tour);
AssertElement(MagicCarpetDbContext.GetTourFromDatabaseById(tour.Id), tour);
}
[Test]
public void Try_AddElement_WhenHaveRecordWithSameId_Test()
{
var tour = CreateModel(Guid.NewGuid().ToString());
InsertTourToDatabaseAndReturn(tour.Id, tourName: "name unique");
MagicCarpetDbContext.InsertTourToDatabaseAndReturn(tour.Id, tourName: "name unique");
Assert.That(() => _tourStorageContract.AddElement(tour), Throws.TypeOf<ElementExistsException>());
}
@@ -123,17 +124,17 @@ internal class TourStorageContractTests : BaseStorageContractTest
public void Try_AddElement_WhenHaveRecordWithSameName_Test()
{
var tour = CreateModel(Guid.NewGuid().ToString(), "name unique");
InsertTourToDatabaseAndReturn(Guid.NewGuid().ToString(), tourName: tour.TourName);
MagicCarpetDbContext.InsertTourToDatabaseAndReturn(Guid.NewGuid().ToString(), tourName: tour.TourName);
Assert.That(() => _tourStorageContract.AddElement(tour), Throws.TypeOf<ElementExistsException>());
}
[Test]
public void Try_UpdElement_Test()
{
var tour = CreateModel(Guid.NewGuid().ToString(), "new name", "country");
InsertTourToDatabaseAndReturn(tour.Id);
var tour = CreateModel(Guid.NewGuid().ToString(), "new name", tourType: TourType.Beach);
MagicCarpetDbContext.InsertTourToDatabaseAndReturn(tour.Id);
_tourStorageContract.UpdElement(tour);
AssertElement(GetTourFromDatabaseById(tour.Id), tour);
AssertElement(MagicCarpetDbContext.GetTourFromDatabaseById(tour.Id), tour);
}
[Test]
@@ -146,17 +147,17 @@ internal class TourStorageContractTests : BaseStorageContractTest
public void Try_UpdElement_WhenHaveRecordWithSameName_Test()
{
var tour = CreateModel(Guid.NewGuid().ToString(), "name unique");
InsertTourToDatabaseAndReturn(tour.Id, tourName: "name");
InsertTourToDatabaseAndReturn(Guid.NewGuid().ToString(), tourName: tour.TourName);
MagicCarpetDbContext.InsertTourToDatabaseAndReturn(tour.Id, tourName: "name");
MagicCarpetDbContext.InsertTourToDatabaseAndReturn(tourName: tour.TourName);
Assert.That(() => _tourStorageContract.UpdElement(tour), Throws.TypeOf<ElementExistsException>());
}
[Test]
public void Try_DelElement_Test()
{
var tour = InsertTourToDatabaseAndReturn(Guid.NewGuid().ToString());
var tour = MagicCarpetDbContext.InsertTourToDatabaseAndReturn(Guid.NewGuid().ToString());
_tourStorageContract.DelElement(tour.Id);
var element = GetTourFromDatabaseById(tour.Id);
var element = MagicCarpetDbContext.GetTourFromDatabaseById(tour.Id);
Assert.That(element, Is.Null);
}
@@ -165,23 +166,6 @@ internal class TourStorageContractTests : BaseStorageContractTest
{
Assert.That(() => _tourStorageContract.DelElement(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
}
private Tour InsertTourToDatabaseAndReturn(string id, string tourName = "test", string tourCountry = "country", TourType tourType = TourType.Beach, double price = 1)
{
var tour = new Tour() { Id = id, TourName = tourName, TourCountry = tourCountry, TourType = tourType, Price = price };
MagicCarpetDbContext.Tours.Add(tour);
MagicCarpetDbContext.SaveChanges();
return tour;
}
private TourHistory InsertTourHistoryToDatabaseAndReturn(string tourId, double price, DateTime changeDate)
{
var tourHistory = new TourHistory() { Id = Guid.NewGuid().ToString(), TourId = tourId, OldPrice = price, ChangeDate = changeDate };
MagicCarpetDbContext.TourHistories.Add(tourHistory);
MagicCarpetDbContext.SaveChanges();
return tourHistory;
}
private static void AssertElement(TourDataModel? actual, Tour expected)
{
Assert.That(actual, Is.Not.Null);
@@ -195,10 +179,8 @@ internal class TourStorageContractTests : BaseStorageContractTest
});
}
private static TourDataModel CreateModel(string id, string tourName = "test", string tourCountry = "country", TourType type = TourType.Beach, double price = 1)
=> new(id, tourName, tourCountry, price, type);
private Tour? GetTourFromDatabaseById(string id) => MagicCarpetDbContext.Tours.FirstOrDefault(x => x.Id == id);
private static TourDataModel CreateModel(string id, string tourName = "test", string tourCountry = "country", TourType tourType = TourType.Ski, double price = 1)
=> new(id, tourName,tourCountry, price, tourType);
private static void AssertElement(Tour? actual, TourDataModel expected)
{

View File

@@ -0,0 +1,72 @@
using MagicCarpetDatabase;
using MagicCarpetTests.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;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
namespace MagicCarpetTests.WebApiControllersTests;
internal class BaseWebApiControllerTest
{
private WebApplicationFactory<Program> _webApplication;
protected HttpClient HttpClient { get; private set; }
protected MagicCarpetDbContext MagicCarpetDbContext { 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}");
MagicCarpetDbContext = _webApplication.Services.GetRequiredService<MagicCarpetDbContext>();
MagicCarpetDbContext.Database.EnsureDeleted();
MagicCarpetDbContext.Database.EnsureCreated();
}
[OneTimeTearDown]
public void OneTimeTearDown()
{
MagicCarpetDbContext?.Database.EnsureDeleted();
MagicCarpetDbContext?.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");
}

View File

@@ -0,0 +1,375 @@
using MagicCarpetContracts.BindingModels;
using MagicCarpetContracts.ViewModels;
using MagicCarpetDatabase.Models;
using MagicCarpetTests.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetTests.WebApiControllersTests;
[TestFixture]
internal class ClientControllerTests : BaseWebApiControllerTest
{
[TearDown]
public void TearDown()
{
MagicCarpetDbContext.RemoveSalesFromDatabase();
MagicCarpetDbContext.RemoveEmployeesFromDatabase();
MagicCarpetDbContext.RemoveClientsFromDatabase();
}
[Test]
public async Task GetList_WhenHaveRecords_ShouldSuccess_Test()
{
//Arrange
var client = MagicCarpetDbContext.InsertClientToDatabaseAndReturn(phoneNumber: "+5-555-555-55-55");
MagicCarpetDbContext.InsertClientToDatabaseAndReturn(phoneNumber: "+6-666-666-66-66");
MagicCarpetDbContext.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 = MagicCarpetDbContext.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
MagicCarpetDbContext.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 = MagicCarpetDbContext.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
MagicCarpetDbContext.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 = MagicCarpetDbContext.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
MagicCarpetDbContext.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
MagicCarpetDbContext.InsertClientToDatabaseAndReturn();
var clientModel = CreateBindingModel();
//Act
var response = await HttpClient.PostAsync($"/api/clients", MakeContent(clientModel));
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
AssertElement(MagicCarpetDbContext.GetClientFromDatabase(clientModel.Id!), clientModel);
}
[Test]
public async Task Post_WhenHaveRecordWithSameId_ShouldBadRequest_Test()
{
//Arrange
var clientModel = CreateBindingModel();
MagicCarpetDbContext.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();
MagicCarpetDbContext.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");
MagicCarpetDbContext.InsertClientToDatabaseAndReturn(clientModel.Id);
//Act
var response = await HttpClient.PutAsync($"/api/clients", MakeContent(clientModel));
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
MagicCarpetDbContext.ChangeTracker.Clear();
AssertElement(MagicCarpetDbContext.GetClientFromDatabase(clientModel.Id!), clientModel);
}
[Test]
public async Task Put_WhenNoFoundRecord_ShouldBadRequest_Test()
{
//Arrange
var clientModel = CreateBindingModel(fio: "new fio");
MagicCarpetDbContext.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");
MagicCarpetDbContext.InsertClientToDatabaseAndReturn(clientModel.Id);
MagicCarpetDbContext.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();
MagicCarpetDbContext.InsertClientToDatabaseAndReturn(clientId);
//Act
var response = await HttpClient.DeleteAsync($"/api/clients/{clientId}");
//Assert
Assert.Multiple(() =>
{
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
Assert.That(MagicCarpetDbContext.GetClientFromDatabase(clientId), Is.Null);
});
}
[Test]
public async Task Delete_WhenHaveSalesByThisClient_ShouldSuccess_Test()
{
//Arrange
var client = MagicCarpetDbContext.InsertClientToDatabaseAndReturn();
var employee = MagicCarpetDbContext.InsertEmployeeToDatabaseAndReturn();
MagicCarpetDbContext.InsertSaleToDatabaseAndReturn(employee.Id, client.Id);
MagicCarpetDbContext.InsertSaleToDatabaseAndReturn(employee.Id, client.Id);
var salesBeforeDelete = MagicCarpetDbContext.GetSalesByClientId(client.Id);
//Act
var response = await HttpClient.DeleteAsync($"/api/clients/{client.Id}");
//Assert
MagicCarpetDbContext.ChangeTracker.Clear();
var element = MagicCarpetDbContext.GetClientFromDatabase(client.Id);
var salesAfterDelete = MagicCarpetDbContext.GetSalesByClientId(client.Id);
var salesNoClients = MagicCarpetDbContext.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
MagicCarpetDbContext.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));
});
}
}

View File

@@ -0,0 +1,556 @@
using MagicCarpetContracts.BindingModels;
using MagicCarpetContracts.ViewModels;
using MagicCarpetDatabase.Models;
using MagicCarpetTests.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetTests.WebApiControllersTests;
[TestFixture]
internal class EmployeeControllerTests : BaseWebApiControllerTest
{
private Post _post;
[SetUp]
public void SetUp()
{
_post = MagicCarpetDbContext.InsertPostToDatabaseAndReturn();
}
[TearDown]
public void TearDown()
{
MagicCarpetDbContext.RemovePostsFromDatabase();
MagicCarpetDbContext.RemoveEmployeesFromDatabase();
}
[Test]
public async Task GetList_WhenHaveRecords_ShouldSuccess_Test()
{
//Arrange
var employee = MagicCarpetDbContext.InsertEmployeeToDatabaseAndReturn(fio: "fio 1", postId: _post.PostId)
.AddPost(_post);
MagicCarpetDbContext.InsertEmployeeToDatabaseAndReturn(fio: "fio 2", postId: _post.PostId);
MagicCarpetDbContext.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
MagicCarpetDbContext.InsertEmployeeToDatabaseAndReturn(fio: "fio 1", postId: _post.PostId, isDeleted: true);
MagicCarpetDbContext.InsertEmployeeToDatabaseAndReturn(fio: "fio 2", postId: _post.PostId, isDeleted: false);
MagicCarpetDbContext.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
MagicCarpetDbContext.InsertEmployeeToDatabaseAndReturn(fio: "fio 1", postId: _post.PostId, isDeleted: true);
MagicCarpetDbContext.InsertEmployeeToDatabaseAndReturn(fio: "fio 2", postId: _post.PostId, isDeleted: true);
MagicCarpetDbContext.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
MagicCarpetDbContext.InsertEmployeeToDatabaseAndReturn(fio: "fio 1", postId: _post.PostId);
MagicCarpetDbContext.InsertEmployeeToDatabaseAndReturn(fio: "fio 2", postId: _post.PostId);
MagicCarpetDbContext.InsertEmployeeToDatabaseAndReturn(fio: "fio 3", postId: _post.PostId, isDeleted: true);
MagicCarpetDbContext.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
MagicCarpetDbContext.InsertEmployeeToDatabaseAndReturn(fio: "fio 1", postId: _post.PostId);
MagicCarpetDbContext.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
MagicCarpetDbContext.InsertEmployeeToDatabaseAndReturn(fio: "fio 1", birthDate: DateTime.UtcNow.AddYears(-25));
MagicCarpetDbContext.InsertEmployeeToDatabaseAndReturn(fio: "fio 2", birthDate: DateTime.UtcNow.AddYears(-21));
MagicCarpetDbContext.InsertEmployeeToDatabaseAndReturn(fio: "fio 3", birthDate: DateTime.UtcNow.AddYears(-20), isDeleted: true);
MagicCarpetDbContext.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
MagicCarpetDbContext.InsertEmployeeToDatabaseAndReturn(fio: "fio 1", employmentDate: DateTime.UtcNow.AddDays(-2));
MagicCarpetDbContext.InsertEmployeeToDatabaseAndReturn(fio: "fio 2", employmentDate: DateTime.UtcNow.AddDays(-1));
MagicCarpetDbContext.InsertEmployeeToDatabaseAndReturn(fio: "fio 3", employmentDate: DateTime.UtcNow.AddDays(1), isDeleted: true);
MagicCarpetDbContext.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 = MagicCarpetDbContext.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
MagicCarpetDbContext.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 = MagicCarpetDbContext.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 = MagicCarpetDbContext.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
MagicCarpetDbContext.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 = MagicCarpetDbContext.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 = MagicCarpetDbContext.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
MagicCarpetDbContext.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 = MagicCarpetDbContext.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
MagicCarpetDbContext.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(MagicCarpetDbContext.GetEmployeeFromDatabaseById(employeeModel.Id!), employeeModel);
}
[Test]
public async Task Post_WhenHaveRecordWithSameId_ShouldBadRequest_Test()
{
//Arrange
var employeeModel = CreateModel(_post.Id);
MagicCarpetDbContext.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);
MagicCarpetDbContext.InsertEmployeeToDatabaseAndReturn(employeeModel.Id);
//Act
var response = await HttpClient.PutAsync($"/api/employees/changeinfo", MakeContent(employeeModel));
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
MagicCarpetDbContext.ChangeTracker.Clear();
AssertElement(MagicCarpetDbContext.GetEmployeeFromDatabaseById(employeeModel.Id!), employeeModel);
}
[Test]
public async Task Put_WhenNoFoundRecord_ShouldBadRequest_Test()
{
//Arrange
var employeeModel = CreateModel(_post.Id, fio: "new fio");
MagicCarpetDbContext.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");
MagicCarpetDbContext.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();
MagicCarpetDbContext.InsertEmployeeToDatabaseAndReturn(employeeId);
//Act
var response = await HttpClient.DeleteAsync($"/api/employees/delete/{employeeId}");
MagicCarpetDbContext.ChangeTracker.Clear();
//Assert
Assert.Multiple(() =>
{
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
Assert.That(MagicCarpetDbContext.GetEmployeeFromDatabaseById(employeeId)!.IsDeleted);
});
}
[Test]
public async Task Delete_WhenNoFoundRecord_ShouldBadRequest_Test()
{
//Arrange
MagicCarpetDbContext.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 = MagicCarpetDbContext.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);
});
}
}

Some files were not shown because too many files have changed in this diff Show More