Compare commits
13 Commits
Task_2_Bui
...
Task_4_Api
| Author | SHA1 | Date | |
|---|---|---|---|
| afe3a18866 | |||
| f3449dee3c | |||
| 0ff65a7faa | |||
| e40e9edd5d | |||
| efef7afd91 | |||
| 5c978beafa | |||
| 1b3e780fb7 | |||
| 72547eeb41 | |||
| 9ed1d7b442 | |||
| ba060a7e21 | |||
| 3b5ffb40e1 | |||
| 9ebecdc818 | |||
| 4a82378f01 |
@@ -8,6 +8,7 @@
|
||||
|
||||
<ItemGroup>
|
||||
<InternalsVisibleTo Include="CatHasPawsTests" />
|
||||
<InternalsVisibleTo Include="CatHasPawsWebApi" />
|
||||
<InternalsVisibleTo Include="DynamicProxyGenAssembly2" />
|
||||
</ItemGroup>
|
||||
|
||||
|
||||
@@ -13,10 +13,10 @@ internal class PostBusinessLogicContract(IPostStorageContract postStorageContrac
|
||||
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)
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
using CatHasPawsContratcs.AdapterContracts.OperationResponses;
|
||||
using CatHasPawsContratcs.BindingModels;
|
||||
|
||||
namespace CatHasPawsContratcs.AdapterContracts;
|
||||
|
||||
public interface IBuyerAdapter
|
||||
{
|
||||
BuyerOperationResponse GetList();
|
||||
|
||||
BuyerOperationResponse GetElement(string data);
|
||||
|
||||
BuyerOperationResponse RegisterBuyer(BuyerBindingModel buyerModel);
|
||||
|
||||
BuyerOperationResponse ChangeBuyerInfo(BuyerBindingModel buyerModel);
|
||||
|
||||
BuyerOperationResponse RemoveBuyer(string id);
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
using CatHasPawsContratcs.AdapterContracts.OperationResponses;
|
||||
using CatHasPawsContratcs.BindingModels;
|
||||
|
||||
namespace CatHasPawsContratcs.AdapterContracts;
|
||||
|
||||
public interface IManufacturerAdapter
|
||||
{
|
||||
ManufacturerOperationResponse GetList();
|
||||
|
||||
ManufacturerOperationResponse GetElement(string data);
|
||||
|
||||
ManufacturerOperationResponse RegisterManufacturer(ManufacturerBindingModel manufacturerModel);
|
||||
|
||||
ManufacturerOperationResponse ChangeManufacturerInfo(ManufacturerBindingModel manufacturerModel);
|
||||
|
||||
ManufacturerOperationResponse RemoveManufacturer(string id);
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
using CatHasPawsContratcs.AdapterContracts.OperationResponses;
|
||||
using CatHasPawsContratcs.BindingModels;
|
||||
|
||||
namespace CatHasPawsContratcs.AdapterContracts;
|
||||
|
||||
public interface IPostAdapter
|
||||
{
|
||||
PostOperationResponse GetList();
|
||||
|
||||
PostOperationResponse GetHistory(string id);
|
||||
|
||||
PostOperationResponse GetElement(string data);
|
||||
|
||||
PostOperationResponse RegisterPost(PostBindingModel postModel);
|
||||
|
||||
PostOperationResponse ChangePostInfo(PostBindingModel postModel);
|
||||
|
||||
PostOperationResponse RemovePost(string id);
|
||||
|
||||
PostOperationResponse RestorePost(string id);
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
using CatHasPawsContratcs.AdapterContracts.OperationResponses;
|
||||
using CatHasPawsContratcs.BindingModels;
|
||||
|
||||
namespace CatHasPawsContratcs.AdapterContracts;
|
||||
|
||||
public interface IProductAdapter
|
||||
{
|
||||
ProductOperationResponse GetList(bool includeDeleted);
|
||||
|
||||
ProductOperationResponse GetManufacturerList(string id, bool includeDeleted);
|
||||
|
||||
ProductOperationResponse GetHistory(string id);
|
||||
|
||||
ProductOperationResponse GetElement(string data);
|
||||
|
||||
ProductOperationResponse RegisterProduct(ProductBindingModel productModel);
|
||||
|
||||
ProductOperationResponse ChangeProductInfo(ProductBindingModel productModel);
|
||||
|
||||
ProductOperationResponse RemoveProduct(string id);
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
using CatHasPawsContratcs.AdapterContracts.OperationResponses;
|
||||
using CatHasPawsContratcs.BindingModels;
|
||||
|
||||
namespace CatHasPawsContratcs.AdapterContracts;
|
||||
|
||||
public interface ISaleAdapter
|
||||
{
|
||||
SaleOperationResponse GetList(DateTime fromDate, DateTime toDate);
|
||||
|
||||
SaleOperationResponse GetWorkerList(string id, DateTime fromDate, DateTime toDate);
|
||||
|
||||
SaleOperationResponse GetBuyerList(string id, DateTime fromDate, DateTime toDate);
|
||||
|
||||
SaleOperationResponse GetProductList(string id, DateTime fromDate, DateTime toDate);
|
||||
|
||||
SaleOperationResponse GetElement(string id);
|
||||
|
||||
SaleOperationResponse MakeSale(SaleBindingModel saleModel);
|
||||
|
||||
SaleOperationResponse CancelSale(string id);
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
using CatHasPawsContratcs.AdapterContracts.OperationResponses;
|
||||
using CatHasPawsContratcs.BindingModels;
|
||||
|
||||
namespace CatHasPawsContratcs.AdapterContracts;
|
||||
|
||||
public interface IWorkerAdapter
|
||||
{
|
||||
WorkerOperationResponse GetList(bool includeDeleted);
|
||||
|
||||
WorkerOperationResponse GetPostList(string id, bool includeDeleted);
|
||||
|
||||
WorkerOperationResponse GetListByBirthDate(DateTime fromDate, DateTime toDate, bool includeDeleted);
|
||||
|
||||
WorkerOperationResponse GetListByEmploymentDate(DateTime fromDate, DateTime toDate, bool includeDeleted);
|
||||
|
||||
WorkerOperationResponse GetElement(string data);
|
||||
|
||||
WorkerOperationResponse RegisterWorker(WorkerBindingModel workerModel);
|
||||
|
||||
WorkerOperationResponse ChangeWorkerInfo(WorkerBindingModel workerModel);
|
||||
|
||||
WorkerOperationResponse RemoveWorker(string id);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
using CatHasPawsContratcs.Infrastructure;
|
||||
using CatHasPawsContratcs.ViewModels;
|
||||
|
||||
namespace CatHasPawsContratcs.AdapterContracts.OperationResponses;
|
||||
|
||||
public class BuyerOperationResponse : OperationResponse
|
||||
{
|
||||
public static BuyerOperationResponse OK(List<BuyerViewModel> data) => OK<BuyerOperationResponse, List<BuyerViewModel>>(data);
|
||||
|
||||
public static BuyerOperationResponse OK(BuyerViewModel data) => OK<BuyerOperationResponse, BuyerViewModel>(data);
|
||||
|
||||
public static BuyerOperationResponse NoContent() => NoContent<BuyerOperationResponse>();
|
||||
|
||||
public static BuyerOperationResponse BadRequest(string message) => BadRequest<BuyerOperationResponse>(message);
|
||||
|
||||
public static BuyerOperationResponse NotFound(string message) => NotFound<BuyerOperationResponse>(message);
|
||||
|
||||
public static BuyerOperationResponse InternalServerError(string message) => InternalServerError<BuyerOperationResponse>(message);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
using CatHasPawsContratcs.Infrastructure;
|
||||
using CatHasPawsContratcs.ViewModels;
|
||||
|
||||
namespace CatHasPawsContratcs.AdapterContracts.OperationResponses;
|
||||
|
||||
public class ManufacturerOperationResponse : OperationResponse
|
||||
{
|
||||
public static ManufacturerOperationResponse OK(List<ManufacturerViewModel> data) => OK<ManufacturerOperationResponse, List<ManufacturerViewModel>>(data);
|
||||
|
||||
public static ManufacturerOperationResponse OK(ManufacturerViewModel data) => OK<ManufacturerOperationResponse, ManufacturerViewModel>(data);
|
||||
|
||||
public static ManufacturerOperationResponse NoContent() => NoContent<ManufacturerOperationResponse>();
|
||||
|
||||
public static ManufacturerOperationResponse NotFound(string message) => NotFound<ManufacturerOperationResponse>(message);
|
||||
|
||||
public static ManufacturerOperationResponse BadRequest(string message) => BadRequest<ManufacturerOperationResponse>(message);
|
||||
|
||||
public static ManufacturerOperationResponse InternalServerError(string message) => InternalServerError<ManufacturerOperationResponse>(message);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
using CatHasPawsContratcs.Infrastructure;
|
||||
using CatHasPawsContratcs.ViewModels;
|
||||
|
||||
namespace CatHasPawsContratcs.AdapterContracts.OperationResponses;
|
||||
|
||||
public class PostOperationResponse : OperationResponse
|
||||
{
|
||||
public static PostOperationResponse OK(List<PostViewModel> data) => OK<PostOperationResponse, List<PostViewModel>>(data);
|
||||
|
||||
public static PostOperationResponse OK(PostViewModel data) => OK<PostOperationResponse, PostViewModel>(data);
|
||||
|
||||
public static PostOperationResponse NoContent() => NoContent<PostOperationResponse>();
|
||||
|
||||
public static PostOperationResponse NotFound(string message) => NotFound<PostOperationResponse>(message);
|
||||
|
||||
public static PostOperationResponse BadRequest(string message) => BadRequest<PostOperationResponse>(message);
|
||||
|
||||
public static PostOperationResponse InternalServerError(string message) => InternalServerError<PostOperationResponse>(message);
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
using CatHasPawsContratcs.Infrastructure;
|
||||
using CatHasPawsContratcs.ViewModels;
|
||||
|
||||
namespace CatHasPawsContratcs.AdapterContracts.OperationResponses;
|
||||
|
||||
public class ProductOperationResponse : OperationResponse
|
||||
{
|
||||
public static ProductOperationResponse OK(List<ProductViewModel> data) => OK<ProductOperationResponse, List<ProductViewModel>>(data);
|
||||
|
||||
public static ProductOperationResponse OK(List<ProductHistoryViewModel> data) => OK<ProductOperationResponse, List<ProductHistoryViewModel>>(data);
|
||||
|
||||
public static ProductOperationResponse OK(ProductViewModel data) => OK<ProductOperationResponse, ProductViewModel>(data);
|
||||
|
||||
public static ProductOperationResponse NoContent() => NoContent<ProductOperationResponse>();
|
||||
|
||||
public static ProductOperationResponse NotFound(string message) => NotFound<ProductOperationResponse>(message);
|
||||
|
||||
public static ProductOperationResponse BadRequest(string message) => BadRequest<ProductOperationResponse>(message);
|
||||
|
||||
public static ProductOperationResponse InternalServerError(string message) => InternalServerError<ProductOperationResponse>(message);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
using CatHasPawsContratcs.Infrastructure;
|
||||
using CatHasPawsContratcs.ViewModels;
|
||||
|
||||
namespace CatHasPawsContratcs.AdapterContracts.OperationResponses;
|
||||
|
||||
public class SaleOperationResponse : OperationResponse
|
||||
{
|
||||
public static SaleOperationResponse OK(List<SaleViewModel> data) => OK<SaleOperationResponse, List<SaleViewModel>>(data);
|
||||
|
||||
public static SaleOperationResponse OK(SaleViewModel data) => OK<SaleOperationResponse, SaleViewModel>(data);
|
||||
|
||||
public static SaleOperationResponse NoContent() => NoContent<SaleOperationResponse>();
|
||||
|
||||
public static SaleOperationResponse NotFound(string message) => NotFound<SaleOperationResponse>(message);
|
||||
|
||||
public static SaleOperationResponse BadRequest(string message) => BadRequest<SaleOperationResponse>(message);
|
||||
|
||||
public static SaleOperationResponse InternalServerError(string message) => InternalServerError<SaleOperationResponse>(message);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
using CatHasPawsContratcs.Infrastructure;
|
||||
using CatHasPawsContratcs.ViewModels;
|
||||
|
||||
namespace CatHasPawsContratcs.AdapterContracts.OperationResponses;
|
||||
|
||||
public class WorkerOperationResponse : OperationResponse
|
||||
{
|
||||
public static WorkerOperationResponse OK(List<WorkerViewModel> data) => OK<WorkerOperationResponse, List<WorkerViewModel>>(data);
|
||||
|
||||
public static WorkerOperationResponse OK(WorkerViewModel data) => OK<WorkerOperationResponse, WorkerViewModel>(data);
|
||||
|
||||
public static WorkerOperationResponse NoContent() => NoContent<WorkerOperationResponse>();
|
||||
|
||||
public static WorkerOperationResponse NotFound(string message) => NotFound<WorkerOperationResponse>(message);
|
||||
|
||||
public static WorkerOperationResponse BadRequest(string message) => BadRequest<WorkerOperationResponse>(message);
|
||||
|
||||
public static WorkerOperationResponse InternalServerError(string message) => InternalServerError<WorkerOperationResponse>(message);
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
namespace CatHasPawsContratcs.BindingModels;
|
||||
|
||||
public class BuyerBindingModel
|
||||
{
|
||||
public string? Id { get; set; }
|
||||
|
||||
public string? FIO { get; set; }
|
||||
|
||||
public string? PhoneNumber { get; set; }
|
||||
|
||||
public double DiscountSize { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
namespace CatHasPawsContratcs.BindingModels;
|
||||
|
||||
public class ManufacturerBindingModel
|
||||
{
|
||||
public string? Id { get; set; }
|
||||
|
||||
public string? ManufacturerName { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
namespace CatHasPawsContratcs.BindingModels;
|
||||
|
||||
public class PostBindingModel
|
||||
{
|
||||
public string? Id { get; set; }
|
||||
|
||||
public string? PostId => Id;
|
||||
|
||||
public string? PostName { get; set; }
|
||||
|
||||
public string? PostType { get; set; }
|
||||
|
||||
public double Salary { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
namespace CatHasPawsContratcs.BindingModels;
|
||||
|
||||
public class ProductBindingModel
|
||||
{
|
||||
public string? Id { get; set; }
|
||||
|
||||
public string? ProductName { get; set; }
|
||||
|
||||
public string? ProductType { get; set; }
|
||||
|
||||
public string? ManufacturerId { get; set; }
|
||||
|
||||
public double Price { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
namespace CatHasPawsContratcs.BindingModels;
|
||||
|
||||
public class SaleBindingModel
|
||||
{
|
||||
public string? Id { get; set; }
|
||||
|
||||
public string? WorkerId { get; set; }
|
||||
|
||||
public string? BuyerId { get; set; }
|
||||
|
||||
public int DiscountType { get; set; }
|
||||
|
||||
public List<SaleProductBindingModel>? Products { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
namespace CatHasPawsContratcs.BindingModels;
|
||||
|
||||
public class SaleProductBindingModel
|
||||
{
|
||||
public string? SaleId { get; set; }
|
||||
|
||||
public string? ProductId { get; set; }
|
||||
|
||||
public int Count { get; set; }
|
||||
|
||||
public double Price { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
namespace CatHasPawsContratcs.BindingModels;
|
||||
|
||||
public class WorkerBindingModel
|
||||
{
|
||||
public string? Id { get; set; }
|
||||
|
||||
public string? FIO { get; set; }
|
||||
|
||||
public string? PostId { get; set; }
|
||||
|
||||
public DateTime BirthDate { get; set; }
|
||||
|
||||
public DateTime EmploymentDate { get; set; }
|
||||
}
|
||||
@@ -4,7 +4,7 @@ namespace CatHasPawsContratcs.BusinessLogicsContracts;
|
||||
|
||||
public interface IPostBusinessLogicContract
|
||||
{
|
||||
List<PostDataModel> GetAllPosts(bool onlyActive);
|
||||
List<PostDataModel> GetAllPosts();
|
||||
|
||||
List<PostDataModel> GetAllDataOfPost(string postId);
|
||||
|
||||
|
||||
@@ -6,4 +6,9 @@
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.AspNetCore.Mvc.Abstractions" Version="2.3.0" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Mvc.Core" Version="2.3.0" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
||||
@@ -14,6 +14,8 @@ public class ManufacturerDataModel(string id, string manufacturerName, string? p
|
||||
|
||||
public string? PrevPrevManufacturerName { get; private set; } = prevPrevManufacturerName;
|
||||
|
||||
public ManufacturerDataModel(string id, string manufacturerName) : this(id, manufacturerName, null, null) { }
|
||||
|
||||
public void Validate()
|
||||
{
|
||||
if (Id.IsEmpty())
|
||||
|
||||
@@ -5,9 +5,9 @@ using CatHasPawsContratcs.Infrastructure;
|
||||
|
||||
namespace CatHasPawsContratcs.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;
|
||||
|
||||
@@ -15,10 +15,6 @@ public class PostDataModel(string id, string postName, PostType postType, double
|
||||
|
||||
public double Salary { get; private set; } = salary;
|
||||
|
||||
public bool IsActual { get; private set; } = isActual;
|
||||
|
||||
public DateTime ChangeDate { get; private set; } = changeDate;
|
||||
|
||||
public void Validate()
|
||||
{
|
||||
if (Id.IsEmpty())
|
||||
|
||||
@@ -7,6 +7,8 @@ namespace CatHasPawsContratcs.DataModels;
|
||||
|
||||
public class ProductDataModel(string id, string productName, ProductType productType, string manufacturerId, double price, bool isDeleted) : IValidation
|
||||
{
|
||||
private readonly ManufacturerDataModel? _manufacturer;
|
||||
|
||||
public string Id { get; private set; } = id;
|
||||
|
||||
public string ProductName { get; private set; } = productName;
|
||||
@@ -19,6 +21,15 @@ public class ProductDataModel(string id, string productName, ProductType product
|
||||
|
||||
public bool IsDeleted { get; private set; } = isDeleted;
|
||||
|
||||
public string ManufacturerName => _manufacturer?.ManufacturerName ?? string.Empty;
|
||||
|
||||
public ProductDataModel(string id, string productName, ProductType productType, string manufacturerId, double price, bool isDeleted, ManufacturerDataModel manufacturer) : this(id, productName, productType, manufacturerId, price, isDeleted)
|
||||
{
|
||||
_manufacturer = manufacturer;
|
||||
}
|
||||
|
||||
public ProductDataModel(string id, string productName, ProductType productType, string manufacturerId, double price) : this(id, productName, productType, manufacturerId, price, false) { }
|
||||
|
||||
public void Validate()
|
||||
{
|
||||
if (Id.IsEmpty())
|
||||
|
||||
@@ -6,12 +6,22 @@ namespace CatHasPawsContratcs.DataModels;
|
||||
|
||||
public class ProductHistoryDataModel(string productId, double oldPrice) : IValidation
|
||||
{
|
||||
private readonly ProductDataModel? _product;
|
||||
|
||||
public string ProductId { get; private set; } = productId;
|
||||
|
||||
public double OldPrice { get; private set; } = oldPrice;
|
||||
|
||||
public DateTime ChangeDate { get; private set; } = DateTime.UtcNow;
|
||||
|
||||
public string ProductName => _product?.ProductName ?? string.Empty;
|
||||
|
||||
public ProductHistoryDataModel(string productId, double oldPrice, DateTime changeDate, ProductDataModel product) : this(productId, oldPrice)
|
||||
{
|
||||
ChangeDate = changeDate;
|
||||
_product = product;
|
||||
}
|
||||
|
||||
public void Validate()
|
||||
{
|
||||
if (ProductId.IsEmpty())
|
||||
|
||||
@@ -5,25 +5,76 @@ using CatHasPawsContratcs.Infrastructure;
|
||||
|
||||
namespace CatHasPawsContratcs.DataModels;
|
||||
|
||||
public class SaleDataModel(string id, string workerId, string? buyerId, double sum, DiscountType discountType, double discount, bool isCancel, List<SaleProductDataModel> products) : IValidation
|
||||
public class SaleDataModel : IValidation
|
||||
{
|
||||
public string Id { get; private set; } = id;
|
||||
private readonly BuyerDataModel? _buyer;
|
||||
|
||||
public string WorkerId { get; private set; } = workerId;
|
||||
private readonly WorkerDataModel? _worker;
|
||||
|
||||
public string? BuyerId { get; private set; } = buyerId;
|
||||
public string Id { get; private set; }
|
||||
|
||||
public string WorkerId { get; private set; }
|
||||
|
||||
public string? BuyerId { get; private set; }
|
||||
|
||||
public DateTime SaleDate { get; private set; } = DateTime.UtcNow;
|
||||
|
||||
public double Sum { get; private set; } = sum;
|
||||
public double Sum { get; private set; }
|
||||
|
||||
public DiscountType DiscountType { get; private set; } = discountType;
|
||||
public DiscountType DiscountType { get; private set; }
|
||||
|
||||
public double Discount { get; private set; } = discount;
|
||||
public double Discount { get; private set; }
|
||||
|
||||
public bool IsCancel { get; private set; } = isCancel;
|
||||
public bool IsCancel { get; private set; }
|
||||
|
||||
public List<SaleProductDataModel> Products { get; private set; } = products;
|
||||
public List<SaleProductDataModel>? Products { get; private set; }
|
||||
|
||||
public string BuyerFIO => _buyer?.FIO ?? string.Empty;
|
||||
|
||||
public string WorkerFIO => _worker?.FIO ?? string.Empty;
|
||||
|
||||
public SaleDataModel(string id, string workerId, string? buyerId, DiscountType discountType, bool isCancel, List<SaleProductDataModel> saleProducts)
|
||||
{
|
||||
Id = id;
|
||||
WorkerId = workerId;
|
||||
BuyerId = buyerId;
|
||||
DiscountType = discountType;
|
||||
IsCancel = isCancel;
|
||||
Products = saleProducts;
|
||||
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 = Products?.Sum(x => x.Price * x.Count) ?? 0;
|
||||
Discount = Sum * percent;
|
||||
}
|
||||
|
||||
public SaleDataModel(string id, string workerId, string? buyerId, double sum, DiscountType discountType, double discount, bool isCancel, List<SaleProductDataModel> saleProducts, WorkerDataModel worker, BuyerDataModel? buyer) : this(id, workerId, buyerId, discountType, isCancel, saleProducts)
|
||||
{
|
||||
Sum = sum;
|
||||
Discount = discount;
|
||||
_worker = worker;
|
||||
_buyer = buyer;
|
||||
}
|
||||
|
||||
public SaleDataModel(string id, string workerId, string? buyerId, int discountType, List<SaleProductDataModel> products) : this(id, workerId, buyerId, (DiscountType)discountType, false, products) { }
|
||||
|
||||
public void Validate()
|
||||
{
|
||||
|
||||
@@ -4,14 +4,25 @@ using CatHasPawsContratcs.Infrastructure;
|
||||
|
||||
namespace CatHasPawsContratcs.DataModels;
|
||||
|
||||
public class SaleProductDataModel(string saleId, string productId, int count) : IValidation
|
||||
public class SaleProductDataModel(string saleId, string productId, int count, double price) : IValidation
|
||||
{
|
||||
private readonly ProductDataModel? _product;
|
||||
|
||||
public string SaleId { get; private set; } = saleId;
|
||||
|
||||
public string ProductId { get; private set; } = productId;
|
||||
|
||||
public int Count { get; private set; } = count;
|
||||
|
||||
public double Price { get; private set; } = price;
|
||||
|
||||
public string ProductName => _product?.ProductName ?? string.Empty;
|
||||
|
||||
public SaleProductDataModel(string saleId, string productId, int count, double price, ProductDataModel product) : this(saleId, productId, count, price)
|
||||
{
|
||||
_product = product;
|
||||
}
|
||||
|
||||
public void Validate()
|
||||
{
|
||||
if (SaleId.IsEmpty())
|
||||
@@ -28,5 +39,8 @@ public class SaleProductDataModel(string saleId, string productId, int count) :
|
||||
|
||||
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");
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,8 @@ namespace CatHasPawsContratcs.DataModels;
|
||||
|
||||
public class WorkerDataModel(string id, string fio, 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;
|
||||
@@ -18,6 +20,15 @@ public class WorkerDataModel(string id, string fio, string postId, DateTime birt
|
||||
|
||||
public bool IsDeleted { get; private set; } = isDeleted;
|
||||
|
||||
public string PostName => _post?.PostName ?? string.Empty;
|
||||
|
||||
public WorkerDataModel(string id, string fio, string postId, DateTime birthDate, DateTime employmentDate, bool isDeleted, PostDataModel post) : this(id, fio, postId, birthDate, employmentDate, isDeleted)
|
||||
{
|
||||
_post = post;
|
||||
}
|
||||
|
||||
public WorkerDataModel(string id, string fio, string postId, DateTime birthDate, DateTime employmentDate) : this(id, fio, postId, birthDate, employmentDate, false) { }
|
||||
|
||||
public void Validate()
|
||||
{
|
||||
if (Id.IsEmpty())
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
namespace CatHasPawsContratcs.Exceptions;
|
||||
|
||||
public class ElementDeletedException : Exception
|
||||
{
|
||||
public ElementDeletedException(string id) : base($"Cannot modify a deleted item (id: {id})") { }
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
namespace CatHasPawsContratcs.Infrastructure;
|
||||
|
||||
public interface IConfigurationDatabase
|
||||
{
|
||||
string ConnectionString { get; }
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using System.Net;
|
||||
|
||||
namespace CatHasPawsContratcs.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 };
|
||||
}
|
||||
@@ -4,7 +4,7 @@ namespace CatHasPawsContratcs.StoragesContracts;
|
||||
|
||||
public interface IPostStorageContract
|
||||
{
|
||||
List<PostDataModel> GetList(bool onlyActual = true);
|
||||
List<PostDataModel> GetList();
|
||||
|
||||
List<PostDataModel> GetPostWithHistory(string postId);
|
||||
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
namespace CatHasPawsContratcs.ViewModels;
|
||||
|
||||
public class BuyerViewModel
|
||||
{
|
||||
public required string Id { get; set; }
|
||||
|
||||
public required string FIO { get; set; }
|
||||
|
||||
public required string PhoneNumber { get; set; }
|
||||
|
||||
public double DiscountSize { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
namespace CatHasPawsContratcs.ViewModels;
|
||||
|
||||
public class ManufacturerViewModel
|
||||
{
|
||||
public required string Id { get; set; }
|
||||
|
||||
public required string ManufacturerName { get; set; }
|
||||
|
||||
public string? PrevManufacturerName { get; set; }
|
||||
|
||||
public string? PrevPrevManufacturerName { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
namespace CatHasPawsContratcs.ViewModels;
|
||||
|
||||
public class PostViewModel
|
||||
{
|
||||
public required string Id { get; set; }
|
||||
|
||||
public required string PostName { get; set; }
|
||||
|
||||
public required string PostType { get; set; }
|
||||
|
||||
public double Salary { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
namespace CatHasPawsContratcs.ViewModels;
|
||||
|
||||
public class ProductHistoryViewModel
|
||||
{
|
||||
public required string ProductName { get; set; }
|
||||
|
||||
public double OldPrice { get; set; }
|
||||
|
||||
public DateTime ChangeDate { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
namespace CatHasPawsContratcs.ViewModels;
|
||||
|
||||
public class ProductViewModel
|
||||
{
|
||||
public required string Id { get; set; }
|
||||
|
||||
public required string ProductName { get; set; }
|
||||
|
||||
public required string ManufacturerId { get; set; }
|
||||
|
||||
public required string ManufacturerName { get; set; }
|
||||
|
||||
public required string ProductType { get; set; }
|
||||
|
||||
public double Price { get; set; }
|
||||
|
||||
public bool IsDeleted { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
namespace CatHasPawsContratcs.ViewModels;
|
||||
|
||||
public class SaleProductViewModel
|
||||
{
|
||||
public required string ProductId { get; set; }
|
||||
|
||||
public required string ProductName { get; set; }
|
||||
|
||||
public int Count { get; set; }
|
||||
|
||||
public double Price { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
namespace CatHasPawsContratcs.ViewModels;
|
||||
|
||||
public class SaleViewModel
|
||||
{
|
||||
public required string Id { get; set; }
|
||||
|
||||
public required string WorkerId { get; set; }
|
||||
|
||||
public required string WorkerFIO { get; set; }
|
||||
|
||||
public string? BuyerId { get; set; }
|
||||
|
||||
public string? BuyerFIO { 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<SaleProductViewModel> Products { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
namespace CatHasPawsContratcs.ViewModels;
|
||||
|
||||
public class WorkerViewModel
|
||||
{
|
||||
public required string Id { get; set; }
|
||||
|
||||
public required string FIO { get; set; }
|
||||
|
||||
public required string PostId { get; set; }
|
||||
|
||||
public required string PostName { get; set; }
|
||||
|
||||
public bool IsDeleted { get; set; }
|
||||
|
||||
public DateTime BirthDate { get; set; }
|
||||
|
||||
public DateTime EmploymentDate { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net9.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="AutoMapper" Version="14.0.0" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="9.0.2" />
|
||||
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="9.0.3" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\CatHasPawsContratcs\CatHasPawsContratcs.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<InternalsVisibleTo Include="CatHasPawsTests" />
|
||||
<InternalsVisibleTo Include="CatHasPawsWebApi" />
|
||||
<InternalsVisibleTo Include="DynamicProxyGenAssembly2" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,78 @@
|
||||
using CatHasPawsContratcs.Infrastructure;
|
||||
using CatHasPawsDatabase.Models;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace CatHasPawsDatabase;
|
||||
|
||||
internal class CatHasPawsDbContext : DbContext
|
||||
{
|
||||
private readonly IConfigurationDatabase? _configurationDatabase;
|
||||
|
||||
public CatHasPawsDbContext(IConfigurationDatabase configurationDatabase)
|
||||
{
|
||||
_configurationDatabase = configurationDatabase;
|
||||
AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true);
|
||||
AppContext.SetSwitch("Npgsql.DisableDateTimeInfinityConversions", true);
|
||||
}
|
||||
|
||||
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
|
||||
{
|
||||
optionsBuilder.UseNpgsql(_configurationDatabase?.ConnectionString, o => o.SetPostgresVersion(12, 2));
|
||||
base.OnConfiguring(optionsBuilder);
|
||||
}
|
||||
|
||||
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
||||
{
|
||||
base.OnModelCreating(modelBuilder);
|
||||
|
||||
modelBuilder.Entity<Buyer>().HasIndex(x => x.PhoneNumber).IsUnique();
|
||||
|
||||
modelBuilder.Entity<Sale>()
|
||||
.HasOne(e => e.Buyer)
|
||||
.WithMany(e => e.Sales)
|
||||
.OnDelete(DeleteBehavior.SetNull);
|
||||
|
||||
modelBuilder.Entity<Manufacturer>().HasIndex(x => x.ManufacturerName).IsUnique();
|
||||
|
||||
modelBuilder.Entity<Post>()
|
||||
.HasIndex(e => new { e.PostName, e.IsActual })
|
||||
.IsUnique()
|
||||
.HasFilter($"\"{nameof(Post.IsActual)}\" = TRUE");
|
||||
|
||||
modelBuilder.Entity<Post>()
|
||||
.HasIndex(e => new { e.PostId, e.IsActual })
|
||||
.IsUnique()
|
||||
.HasFilter($"\"{nameof(Post.IsActual)}\" = TRUE");
|
||||
|
||||
modelBuilder.Entity<Product>()
|
||||
.HasIndex(x => new { x.ProductName, x.IsDeleted })
|
||||
.IsUnique()
|
||||
.HasFilter($"\"{nameof(Product.IsDeleted)}\" = FALSE");
|
||||
|
||||
modelBuilder
|
||||
.Entity<Product>()
|
||||
.HasOne(e => e.Manufacturer)
|
||||
.WithMany(e => e.Products)
|
||||
.OnDelete(DeleteBehavior.Restrict);
|
||||
|
||||
modelBuilder.Entity<SaleProduct>().HasKey(x => new { x.SaleId, x.ProductId });
|
||||
}
|
||||
|
||||
public DbSet<Buyer> Buyers { get; set; }
|
||||
|
||||
public DbSet<Manufacturer> Manufacturers { get; set; }
|
||||
|
||||
public DbSet<Post> Posts { get; set; }
|
||||
|
||||
public DbSet<Product> Products { get; set; }
|
||||
|
||||
public DbSet<ProductHistory> ProductHistories { get; set; }
|
||||
|
||||
public DbSet<Salary> Salaries { get; set; }
|
||||
|
||||
public DbSet<Sale> Sales { get; set; }
|
||||
|
||||
public DbSet<SaleProduct> SaleProducts { get; set; }
|
||||
|
||||
public DbSet<Worker> Workers { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
using AutoMapper;
|
||||
using CatHasPawsContratcs.DataModels;
|
||||
using CatHasPawsContratcs.Exceptions;
|
||||
using CatHasPawsContratcs.StoragesContracts;
|
||||
using CatHasPawsDatabase.Models;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Npgsql;
|
||||
|
||||
namespace CatHasPawsDatabase.Implementations;
|
||||
|
||||
internal class BuyerStorageContract : IBuyerStorageContract
|
||||
{
|
||||
private readonly CatHasPawsDbContext _dbContext;
|
||||
private readonly Mapper _mapper;
|
||||
|
||||
public BuyerStorageContract(CatHasPawsDbContext catHasPawsDbContext)
|
||||
{
|
||||
_dbContext = catHasPawsDbContext;
|
||||
var config = new MapperConfiguration(cfg =>
|
||||
{
|
||||
cfg.CreateMap<Buyer, BuyerDataModel>();
|
||||
cfg.CreateMap<BuyerDataModel, Buyer>();
|
||||
});
|
||||
_mapper = new Mapper(config);
|
||||
}
|
||||
|
||||
public List<BuyerDataModel> GetList()
|
||||
{
|
||||
try
|
||||
{
|
||||
return [.. _dbContext.Buyers.Select(x => _mapper.Map<BuyerDataModel>(x))];
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public BuyerDataModel? GetElementById(string id)
|
||||
{
|
||||
try
|
||||
{
|
||||
return _mapper.Map<BuyerDataModel>(GetBuyerById(id));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public BuyerDataModel? GetElementByFIO(string fio)
|
||||
{
|
||||
try
|
||||
{
|
||||
return _mapper.Map<BuyerDataModel>(_dbContext.Buyers.FirstOrDefault(x => x.FIO == fio));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public BuyerDataModel? GetElementByPhoneNumber(string phoneNumber)
|
||||
{
|
||||
try
|
||||
{
|
||||
return _mapper.Map<BuyerDataModel>(_dbContext.Buyers.FirstOrDefault(x => x.PhoneNumber == phoneNumber));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public void AddElement(BuyerDataModel buyerDataModel)
|
||||
{
|
||||
try
|
||||
{
|
||||
_dbContext.Buyers.Add(_mapper.Map<Buyer>(buyerDataModel));
|
||||
_dbContext.SaveChanges();
|
||||
}
|
||||
catch (InvalidOperationException ex) when (ex.TargetSite?.Name == "ThrowIdentityConflict")
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new ElementExistsException("Id", buyerDataModel.Id);
|
||||
}
|
||||
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Buyers_PhoneNumber" })
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new ElementExistsException("PhoneNumber", buyerDataModel.PhoneNumber);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public void UpdElement(BuyerDataModel buyerDataModel)
|
||||
{
|
||||
try
|
||||
{
|
||||
var element = GetBuyerById(buyerDataModel.Id) ?? throw new ElementNotFoundException(buyerDataModel.Id);
|
||||
_dbContext.Buyers.Update(_mapper.Map(buyerDataModel, element));
|
||||
_dbContext.SaveChanges();
|
||||
}
|
||||
catch (ElementNotFoundException)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw;
|
||||
}
|
||||
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Buyers_PhoneNumber" })
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new ElementExistsException("PhoneNumber", buyerDataModel.PhoneNumber);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public void DelElement(string id)
|
||||
{
|
||||
try
|
||||
{
|
||||
var element = GetBuyerById(id) ?? throw new ElementNotFoundException(id);
|
||||
_dbContext.Buyers.Remove(element);
|
||||
_dbContext.SaveChanges();
|
||||
}
|
||||
catch (ElementNotFoundException)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
private Buyer? GetBuyerById(string id) => _dbContext.Buyers.FirstOrDefault(x => x.Id == id);
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
using AutoMapper;
|
||||
using CatHasPawsContratcs.DataModels;
|
||||
using CatHasPawsContratcs.Exceptions;
|
||||
using CatHasPawsContratcs.StoragesContracts;
|
||||
using CatHasPawsDatabase.Models;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Npgsql;
|
||||
|
||||
namespace CatHasPawsDatabase.Implementations;
|
||||
|
||||
internal class ManufacturerStorageContract : IManufacturerStorageContract
|
||||
{
|
||||
private readonly CatHasPawsDbContext _dbContext;
|
||||
private readonly Mapper _mapper;
|
||||
|
||||
public ManufacturerStorageContract(CatHasPawsDbContext dbContext)
|
||||
{
|
||||
_dbContext = dbContext;
|
||||
var config = new MapperConfiguration(cfg =>
|
||||
{
|
||||
cfg.CreateMap<Manufacturer, ManufacturerDataModel>();
|
||||
cfg.CreateMap<ManufacturerDataModel, Manufacturer>();
|
||||
});
|
||||
_mapper = new Mapper(config);
|
||||
}
|
||||
|
||||
public List<ManufacturerDataModel> GetList()
|
||||
{
|
||||
try
|
||||
{
|
||||
return [.. _dbContext.Manufacturers.Select(x => _mapper.Map<ManufacturerDataModel>(x))];
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public ManufacturerDataModel? GetElementById(string id)
|
||||
{
|
||||
try
|
||||
{
|
||||
return _mapper.Map<ManufacturerDataModel>(GetManufacturerById(id));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public ManufacturerDataModel? GetElementByName(string name)
|
||||
{
|
||||
try
|
||||
{
|
||||
return _mapper.Map<ManufacturerDataModel>(_dbContext.Manufacturers.FirstOrDefault(x => x.ManufacturerName == name));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public ManufacturerDataModel? GetElementByOldName(string name)
|
||||
{
|
||||
try
|
||||
{
|
||||
return _mapper.Map<ManufacturerDataModel>(_dbContext.Manufacturers.FirstOrDefault(x => x.PrevManufacturerName == name ||
|
||||
x.PrevPrevManufacturerName == name));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public void AddElement(ManufacturerDataModel manufacturerDataModel)
|
||||
{
|
||||
try
|
||||
{
|
||||
_dbContext.Manufacturers.Add(_mapper.Map<Manufacturer>(manufacturerDataModel));
|
||||
_dbContext.SaveChanges();
|
||||
}
|
||||
catch (InvalidOperationException ex) when (ex.TargetSite?.Name == "ThrowIdentityConflict")
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new ElementExistsException("Id", manufacturerDataModel.Id);
|
||||
}
|
||||
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Manufacturers_ManufacturerName" })
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new ElementExistsException("ManufacturerName", manufacturerDataModel.ManufacturerName);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public void UpdElement(ManufacturerDataModel manufacturerDataModel)
|
||||
{
|
||||
try
|
||||
{
|
||||
var element = GetManufacturerById(manufacturerDataModel.Id) ?? throw new ElementNotFoundException(manufacturerDataModel.Id);
|
||||
if (element.ManufacturerName != manufacturerDataModel.ManufacturerName)
|
||||
{
|
||||
element.PrevPrevManufacturerName = element.PrevManufacturerName;
|
||||
element.PrevManufacturerName = element.ManufacturerName;
|
||||
element.ManufacturerName = manufacturerDataModel.ManufacturerName;
|
||||
}
|
||||
_dbContext.Manufacturers.Update(element);
|
||||
_dbContext.SaveChanges();
|
||||
}
|
||||
catch (ElementNotFoundException)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw;
|
||||
}
|
||||
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Manufacturers_ManufacturerName" })
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new ElementExistsException("ManufacturerName", manufacturerDataModel.ManufacturerName);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public void DelElement(string id)
|
||||
{
|
||||
try
|
||||
{
|
||||
var element = GetManufacturerById(id) ?? throw new ElementNotFoundException(id);
|
||||
_dbContext.Manufacturers.Remove(element);
|
||||
_dbContext.SaveChanges();
|
||||
}
|
||||
catch (ElementNotFoundException)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
private Manufacturer? GetManufacturerById(string id) => _dbContext.Manufacturers.FirstOrDefault(x => x.Id == id);
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
using AutoMapper;
|
||||
using CatHasPawsContratcs.DataModels;
|
||||
using CatHasPawsContratcs.Exceptions;
|
||||
using CatHasPawsContratcs.StoragesContracts;
|
||||
using CatHasPawsDatabase.Models;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Npgsql;
|
||||
|
||||
namespace CatHasPawsDatabase.Implementations;
|
||||
|
||||
internal class PostStorageContract : IPostStorageContract
|
||||
{
|
||||
private readonly CatHasPawsDbContext _dbContext;
|
||||
private readonly Mapper _mapper;
|
||||
|
||||
public PostStorageContract(CatHasPawsDbContext dbContext)
|
||||
{
|
||||
_dbContext = dbContext;
|
||||
var config = new MapperConfiguration(cfg =>
|
||||
{
|
||||
cfg.CreateMap<Post, PostDataModel>()
|
||||
.ForMember(x => x.Id, x => x.MapFrom(src => src.PostId));
|
||||
cfg.CreateMap<PostDataModel, Post>()
|
||||
.ForMember(x => x.Id, x => x.Ignore())
|
||||
.ForMember(x => x.PostId, x => x.MapFrom(src => src.Id))
|
||||
.ForMember(x => x.IsActual, x => x.MapFrom(src => true))
|
||||
.ForMember(x => x.ChangeDate, x => x.MapFrom(src => DateTime.UtcNow));
|
||||
});
|
||||
_mapper = new Mapper(config);
|
||||
}
|
||||
|
||||
public List<PostDataModel> GetList()
|
||||
{
|
||||
try
|
||||
{
|
||||
return [.. _dbContext.Posts.Select(x => _mapper.Map<PostDataModel>(x))];
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public List<PostDataModel> GetPostWithHistory(string postId)
|
||||
{
|
||||
try
|
||||
{
|
||||
return [.. _dbContext.Posts.Where(x => x.PostId == postId).Select(x => _mapper.Map<PostDataModel>(x))];
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public PostDataModel? GetElementById(string id)
|
||||
{
|
||||
try
|
||||
{
|
||||
return _mapper.Map<PostDataModel>(_dbContext.Posts.FirstOrDefault(x => x.PostId == id && x.IsActual));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public PostDataModel? GetElementByName(string name)
|
||||
{
|
||||
try
|
||||
{
|
||||
return _mapper.Map<PostDataModel>(_dbContext.Posts.FirstOrDefault(x => x.PostName == name && x.IsActual));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public void AddElement(PostDataModel postDataModel)
|
||||
{
|
||||
try
|
||||
{
|
||||
_dbContext.Posts.Add(_mapper.Map<Post>(postDataModel));
|
||||
_dbContext.SaveChanges();
|
||||
}
|
||||
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Posts_PostName_IsActual" })
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new ElementExistsException("PostName", postDataModel.PostName);
|
||||
}
|
||||
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Posts_PostId_IsActual" })
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new ElementExistsException("PostId", postDataModel.Id);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public void UpdElement(PostDataModel postDataModel)
|
||||
{
|
||||
try
|
||||
{
|
||||
var transaction = _dbContext.Database.BeginTransaction();
|
||||
try
|
||||
{
|
||||
var element = GetPostById(postDataModel.Id) ?? throw new ElementNotFoundException(postDataModel.Id);
|
||||
if (!element.IsActual)
|
||||
{
|
||||
throw new ElementDeletedException(postDataModel.Id);
|
||||
}
|
||||
element.IsActual = false;
|
||||
_dbContext.SaveChanges();
|
||||
var newElement = _mapper.Map<Post>(postDataModel);
|
||||
_dbContext.Posts.Add(newElement);
|
||||
_dbContext.SaveChanges();
|
||||
transaction.Commit();
|
||||
}
|
||||
catch
|
||||
{
|
||||
transaction.Rollback();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Posts_PostName_IsActual" })
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new ElementExistsException("PostName", postDataModel.PostName);
|
||||
}
|
||||
catch (Exception ex) when (ex is ElementDeletedException || ex is ElementNotFoundException)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public void DelElement(string id)
|
||||
{
|
||||
try
|
||||
{
|
||||
var element = GetPostById(id) ?? throw new ElementNotFoundException(id);
|
||||
if (!element.IsActual)
|
||||
{
|
||||
throw new ElementDeletedException(id);
|
||||
}
|
||||
element.IsActual = false;
|
||||
_dbContext.SaveChanges();
|
||||
}
|
||||
catch
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
public void ResElement(string id)
|
||||
{
|
||||
try
|
||||
{
|
||||
var element = GetPostById(id) ?? throw new ElementNotFoundException(id);
|
||||
element.IsActual = true;
|
||||
_dbContext.SaveChanges();
|
||||
}
|
||||
catch
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
private Post? GetPostById(string id) => _dbContext.Posts.Where(x => x.PostId == id).OrderByDescending(x => x.ChangeDate).FirstOrDefault();
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
using AutoMapper;
|
||||
using CatHasPawsContratcs.DataModels;
|
||||
using CatHasPawsContratcs.Exceptions;
|
||||
using CatHasPawsContratcs.StoragesContracts;
|
||||
using CatHasPawsDatabase.Models;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Npgsql;
|
||||
|
||||
namespace CatHasPawsDatabase.Implementations;
|
||||
|
||||
internal class ProductStorageContract : IProductStorageContract
|
||||
{
|
||||
private readonly CatHasPawsDbContext _dbContext;
|
||||
private readonly Mapper _mapper;
|
||||
|
||||
public ProductStorageContract(CatHasPawsDbContext dbContext)
|
||||
{
|
||||
_dbContext = dbContext;
|
||||
var config = new MapperConfiguration(cfg =>
|
||||
{
|
||||
cfg.CreateMap<Manufacturer, ManufacturerDataModel>();
|
||||
cfg.CreateMap<Product, ProductDataModel>();
|
||||
cfg.CreateMap<ProductDataModel, Product>()
|
||||
.ForMember(x => x.IsDeleted, x => x.MapFrom(src => false));
|
||||
cfg.CreateMap<ProductHistory, ProductHistoryDataModel>();
|
||||
});
|
||||
_mapper = new Mapper(config);
|
||||
}
|
||||
|
||||
public List<ProductDataModel> GetList(bool onlyActive = true, string? manufacturerId = null)
|
||||
{
|
||||
try
|
||||
{
|
||||
var query = _dbContext.Products.Include(x => x.Manufacturer).AsQueryable();
|
||||
if (onlyActive)
|
||||
{
|
||||
query = query.Where(x => !x.IsDeleted);
|
||||
}
|
||||
if (manufacturerId is not null)
|
||||
{
|
||||
query = query.Where(x => x.ManufacturerId == manufacturerId);
|
||||
}
|
||||
return [.. query.Select(x => _mapper.Map<ProductDataModel>(x))];
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public List<ProductHistoryDataModel> GetHistoryByProductId(string productId)
|
||||
{
|
||||
try
|
||||
{
|
||||
return [.. _dbContext.ProductHistories.Include(x => x.Product).Where(x => x.ProductId == productId).OrderByDescending(x => x.ChangeDate).Select(x => _mapper.Map<ProductHistoryDataModel>(x))];
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public ProductDataModel? GetElementById(string id)
|
||||
{
|
||||
try
|
||||
{
|
||||
return _mapper.Map<ProductDataModel>(GetProductById(id));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public ProductDataModel? GetElementByName(string name)
|
||||
{
|
||||
try
|
||||
{
|
||||
return _mapper.Map<ProductDataModel>(_dbContext.Products.Include(x => x.Manufacturer).FirstOrDefault(x => x.ProductName == name && !x.IsDeleted));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public void AddElement(ProductDataModel productDataModel)
|
||||
{
|
||||
try
|
||||
{
|
||||
_dbContext.Products.Add(_mapper.Map<Product>(productDataModel));
|
||||
_dbContext.SaveChanges();
|
||||
}
|
||||
catch (InvalidOperationException ex) when (ex.TargetSite?.Name == "ThrowIdentityConflict")
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new ElementExistsException("Id", productDataModel.Id);
|
||||
}
|
||||
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Products_ProductName_IsDeleted" })
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new ElementExistsException("ProductName", productDataModel.ProductName);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public void UpdElement(ProductDataModel productDataModel)
|
||||
{
|
||||
try
|
||||
{
|
||||
var transaction = _dbContext.Database.BeginTransaction();
|
||||
try
|
||||
{
|
||||
var element = GetProductById(productDataModel.Id) ?? throw new ElementNotFoundException(productDataModel.Id);
|
||||
if (element.Price != productDataModel.Price)
|
||||
{
|
||||
_dbContext.ProductHistories.Add(new ProductHistory() { ProductId = element.Id, OldPrice = element.Price });
|
||||
_dbContext.SaveChanges();
|
||||
}
|
||||
_dbContext.Products.Update(_mapper.Map(productDataModel, element));
|
||||
_dbContext.SaveChanges();
|
||||
transaction.Commit();
|
||||
}
|
||||
catch
|
||||
{
|
||||
transaction.Rollback();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Products_ProductName_IsDeleted" })
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new ElementExistsException("ProductName", productDataModel.ProductName);
|
||||
}
|
||||
catch (Exception ex) when (ex is ElementDeletedException || ex is ElementNotFoundException)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public void DelElement(string id)
|
||||
{
|
||||
try
|
||||
{
|
||||
var element = GetProductById(id) ?? throw new ElementNotFoundException(id);
|
||||
element.IsDeleted = true;
|
||||
_dbContext.SaveChanges();
|
||||
}
|
||||
catch (ElementNotFoundException ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
private Product? GetProductById(string id) => _dbContext.Products.Include(x => x.Manufacturer).FirstOrDefault(x => x.Id == id && !x.IsDeleted);
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
using AutoMapper;
|
||||
using CatHasPawsContratcs.DataModels;
|
||||
using CatHasPawsContratcs.Exceptions;
|
||||
using CatHasPawsContratcs.StoragesContracts;
|
||||
using CatHasPawsDatabase.Models;
|
||||
|
||||
namespace CatHasPawsDatabase.Implementations;
|
||||
|
||||
internal class SalaryStorageContract : ISalaryStorageContract
|
||||
{
|
||||
private readonly CatHasPawsDbContext _dbContext;
|
||||
private readonly Mapper _mapper;
|
||||
|
||||
public SalaryStorageContract(CatHasPawsDbContext dbContext)
|
||||
{
|
||||
_dbContext = dbContext;
|
||||
var config = new MapperConfiguration(cfg =>
|
||||
{
|
||||
cfg.CreateMap<Salary, SalaryDataModel>();
|
||||
cfg.CreateMap<SalaryDataModel, Salary>()
|
||||
.ForMember(dest => dest.WorkerSalary, opt => opt.MapFrom(src => src.Salary));
|
||||
});
|
||||
_mapper = new Mapper(config);
|
||||
}
|
||||
|
||||
public List<SalaryDataModel> GetList(DateTime startDate, DateTime endDate, string? workerId = null)
|
||||
{
|
||||
try
|
||||
{
|
||||
var query = _dbContext.Salaries.Where(x => x.SalaryDate >= startDate && x.SalaryDate <= endDate);
|
||||
if (workerId is not null)
|
||||
{
|
||||
query = query.Where(x => x.WorkerId == workerId);
|
||||
}
|
||||
return [.. query.Select(x => _mapper.Map<SalaryDataModel>(x))];
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public void AddElement(SalaryDataModel salaryDataModel)
|
||||
{
|
||||
try
|
||||
{
|
||||
_dbContext.Salaries.Add(_mapper.Map<Salary>(salaryDataModel));
|
||||
_dbContext.SaveChanges();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
using AutoMapper;
|
||||
using CatHasPawsContratcs.DataModels;
|
||||
using CatHasPawsContratcs.Exceptions;
|
||||
using CatHasPawsContratcs.StoragesContracts;
|
||||
using CatHasPawsDatabase.Models;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace CatHasPawsDatabase.Implementations;
|
||||
|
||||
internal class SaleStorageContract : ISaleStorageContract
|
||||
{
|
||||
private readonly CatHasPawsDbContext _dbContext;
|
||||
private readonly Mapper _mapper;
|
||||
|
||||
public SaleStorageContract(CatHasPawsDbContext dbContext)
|
||||
{
|
||||
_dbContext = dbContext;
|
||||
var config = new MapperConfiguration(cfg =>
|
||||
{
|
||||
cfg.CreateMap<Manufacturer, ManufacturerDataModel>();
|
||||
cfg.CreateMap<Buyer, BuyerDataModel>();
|
||||
cfg.CreateMap<Product, ProductDataModel>();
|
||||
cfg.CreateMap<Worker, WorkerDataModel>();
|
||||
cfg.CreateMap<SaleProduct, SaleProductDataModel>();
|
||||
cfg.CreateMap<SaleProductDataModel, SaleProduct>();
|
||||
cfg.CreateMap<Sale, SaleDataModel>();
|
||||
cfg.CreateMap<SaleDataModel, Sale>()
|
||||
.ForMember(x => x.IsCancel, x => x.MapFrom(src => false))
|
||||
.ForMember(x => x.SaleProducts, x => x.MapFrom(src => src.Products));
|
||||
});
|
||||
_mapper = new Mapper(config);
|
||||
}
|
||||
|
||||
public List<SaleDataModel> GetList(DateTime? startDate = null, DateTime? endDate = null, string? workerId = null, string? buyerId = null, string? productId = null)
|
||||
{
|
||||
try
|
||||
{
|
||||
var query = _dbContext.Sales.Include(x => x.Buyer).Include(x => x.Worker).Include(x => x.SaleProducts)!.ThenInclude(x => x.Product).AsQueryable();
|
||||
if (startDate is not null && endDate is not null)
|
||||
{
|
||||
query = query.Where(x => x.SaleDate >= startDate && x.SaleDate < endDate);
|
||||
}
|
||||
if (workerId is not null)
|
||||
{
|
||||
query = query.Where(x => x.WorkerId == workerId);
|
||||
}
|
||||
if (buyerId is not null)
|
||||
{
|
||||
query = query.Where(x => x.BuyerId == buyerId);
|
||||
}
|
||||
if (productId is not null)
|
||||
{
|
||||
query = query.Where(x => x.SaleProducts!.Any(y => y.ProductId == productId));
|
||||
}
|
||||
return [.. query.Select(x => _mapper.Map<SaleDataModel>(x))];
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public SaleDataModel? GetElementById(string id)
|
||||
{
|
||||
try
|
||||
{
|
||||
return _mapper.Map<SaleDataModel>(GetSaleById(id));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public void AddElement(SaleDataModel saleDataModel)
|
||||
{
|
||||
try
|
||||
{
|
||||
_dbContext.Sales.Add(_mapper.Map<Sale>(saleDataModel));
|
||||
_dbContext.SaveChanges();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public void DelElement(string id)
|
||||
{
|
||||
try
|
||||
{
|
||||
var element = GetSaleById(id) ?? throw new ElementNotFoundException(id);
|
||||
if (element.IsCancel)
|
||||
{
|
||||
throw new ElementDeletedException(id);
|
||||
}
|
||||
element.IsCancel = true;
|
||||
_dbContext.SaveChanges();
|
||||
}
|
||||
catch (Exception ex) when (ex is ElementDeletedException || ex is ElementNotFoundException)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
private Sale? GetSaleById(string id) => _dbContext.Sales.Include(x => x.Buyer).Include(x => x.Worker).Include(x => x.SaleProducts)!.ThenInclude(x => x.Product).FirstOrDefault(x => x.Id == id);
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
using AutoMapper;
|
||||
using CatHasPawsContratcs.DataModels;
|
||||
using CatHasPawsContratcs.Exceptions;
|
||||
using CatHasPawsContratcs.StoragesContracts;
|
||||
using CatHasPawsDatabase.Models;
|
||||
|
||||
namespace CatHasPawsDatabase.Implementations;
|
||||
|
||||
internal class WorkerStorageContract : IWorkerStorageContract
|
||||
{
|
||||
private readonly CatHasPawsDbContext _dbContext;
|
||||
private readonly Mapper _mapper;
|
||||
|
||||
public WorkerStorageContract(CatHasPawsDbContext dbContext)
|
||||
{
|
||||
_dbContext = dbContext;
|
||||
var config = new MapperConfiguration(cfg =>
|
||||
{
|
||||
cfg.CreateMap<Post, PostDataModel>()
|
||||
.ForMember(x => x.Id, x => x.MapFrom(src => src.PostId));
|
||||
cfg.CreateMap<Worker, WorkerDataModel>();
|
||||
cfg.CreateMap<WorkerDataModel, Worker>();
|
||||
});
|
||||
_mapper = new Mapper(config);
|
||||
}
|
||||
|
||||
public List<WorkerDataModel> GetList(bool onlyActive = true, string? postId = null, DateTime? fromBirthDate = null, DateTime? toBirthDate = null, DateTime? fromEmploymentDate = null, DateTime? toEmploymentDate = null)
|
||||
{
|
||||
try
|
||||
{
|
||||
var query = _dbContext.Workers.AsQueryable();
|
||||
if (onlyActive)
|
||||
{
|
||||
query = query.Where(x => !x.IsDeleted);
|
||||
}
|
||||
if (postId is not null)
|
||||
{
|
||||
query = query.Where(x => x.PostId == postId);
|
||||
}
|
||||
if (fromBirthDate is not null && toBirthDate is not null)
|
||||
{
|
||||
query = query.Where(x => x.BirthDate >= fromBirthDate && x.BirthDate <= toBirthDate);
|
||||
}
|
||||
if (fromEmploymentDate is not null && toEmploymentDate is not null)
|
||||
{
|
||||
query = query.Where(x => x.EmploymentDate >= fromEmploymentDate && x.EmploymentDate <= toEmploymentDate);
|
||||
}
|
||||
return [.. JoinPost(query).Select(x => _mapper.Map<WorkerDataModel>(x))];
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public WorkerDataModel? GetElementById(string id)
|
||||
{
|
||||
try
|
||||
{
|
||||
return _mapper.Map<WorkerDataModel>(GetWorkerById(id));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public WorkerDataModel? GetElementByFIO(string fio)
|
||||
{
|
||||
try
|
||||
{
|
||||
return _mapper.Map<WorkerDataModel>(AddPost(_dbContext.Workers.FirstOrDefault(x => x.FIO == fio && !x.IsDeleted)));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public void AddElement(WorkerDataModel workerDataModel)
|
||||
{
|
||||
try
|
||||
{
|
||||
_dbContext.Workers.Add(_mapper.Map<Worker>(workerDataModel));
|
||||
_dbContext.SaveChanges();
|
||||
}
|
||||
catch (InvalidOperationException ex) when (ex.TargetSite?.Name == "ThrowIdentityConflict")
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new ElementExistsException("Id", workerDataModel.Id);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public void UpdElement(WorkerDataModel workerDataModel)
|
||||
{
|
||||
try
|
||||
{
|
||||
var element = GetWorkerById(workerDataModel.Id) ?? throw new ElementNotFoundException(workerDataModel.Id);
|
||||
_dbContext.Workers.Update(_mapper.Map(workerDataModel, element));
|
||||
_dbContext.SaveChanges();
|
||||
}
|
||||
catch (ElementNotFoundException)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public void DelElement(string id)
|
||||
{
|
||||
try
|
||||
{
|
||||
var element = GetWorkerById(id) ?? throw new ElementNotFoundException(id);
|
||||
element.IsDeleted = true;
|
||||
_dbContext.SaveChanges();
|
||||
}
|
||||
catch (ElementNotFoundException)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
private Worker? GetWorkerById(string id) => AddPost(_dbContext.Workers.FirstOrDefault(x => x.Id == id && !x.IsDeleted));
|
||||
|
||||
private IQueryable<Worker> JoinPost(IQueryable<Worker> query)
|
||||
=> query.GroupJoin(_dbContext.Posts.Where(x => x.IsActual), x => x.PostId, y => y.PostId, (x, y) => new { Worker = x, Post = y })
|
||||
.SelectMany(xy => xy.Post.DefaultIfEmpty(), (x, y) => x.Worker.AddPost(y));
|
||||
|
||||
private Worker? AddPost(Worker? worker)
|
||||
=> worker?.AddPost(_dbContext.Posts.FirstOrDefault(x => x.PostId == worker.PostId && x.IsActual));
|
||||
}
|
||||
17
TheCatHasPawsProject/CatHasPawsDatabase/Models/Buyer.cs
Normal file
17
TheCatHasPawsProject/CatHasPawsDatabase/Models/Buyer.cs
Normal file
@@ -0,0 +1,17 @@
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
|
||||
namespace CatHasPawsDatabase.Models;
|
||||
|
||||
internal class Buyer
|
||||
{
|
||||
public required string Id { get; set; }
|
||||
|
||||
public required string FIO { get; set; }
|
||||
|
||||
public required string PhoneNumber { get; set; }
|
||||
|
||||
public double DiscountSize { get; set; }
|
||||
|
||||
[ForeignKey("BuyerId")]
|
||||
public List<Sale>? Sales { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
|
||||
namespace CatHasPawsDatabase.Models;
|
||||
|
||||
internal class Manufacturer
|
||||
{
|
||||
public required string Id { get; set; }
|
||||
|
||||
public required string ManufacturerName { get; set; }
|
||||
|
||||
public string? PrevManufacturerName { get; set; }
|
||||
|
||||
public string? PrevPrevManufacturerName { get; set; }
|
||||
|
||||
[ForeignKey("ManufacturerId")]
|
||||
public List<Product>? Products { get; set; }
|
||||
}
|
||||
20
TheCatHasPawsProject/CatHasPawsDatabase/Models/Post.cs
Normal file
20
TheCatHasPawsProject/CatHasPawsDatabase/Models/Post.cs
Normal file
@@ -0,0 +1,20 @@
|
||||
using CatHasPawsContratcs.Enums;
|
||||
|
||||
namespace CatHasPawsDatabase.Models;
|
||||
|
||||
internal class Post
|
||||
{
|
||||
public required string Id { get; set; } = Guid.NewGuid().ToString();
|
||||
|
||||
public required string PostId { get; set; }
|
||||
|
||||
public required string PostName { get; set; }
|
||||
|
||||
public PostType PostType { get; set; }
|
||||
|
||||
public double Salary { get; set; }
|
||||
|
||||
public bool IsActual { get; set; }
|
||||
|
||||
public DateTime ChangeDate { get; set; }
|
||||
}
|
||||
27
TheCatHasPawsProject/CatHasPawsDatabase/Models/Product.cs
Normal file
27
TheCatHasPawsProject/CatHasPawsDatabase/Models/Product.cs
Normal file
@@ -0,0 +1,27 @@
|
||||
using CatHasPawsContratcs.Enums;
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
|
||||
namespace CatHasPawsDatabase.Models;
|
||||
|
||||
internal class Product
|
||||
{
|
||||
public required string Id { get; set; }
|
||||
|
||||
public required string ProductName { get; set; }
|
||||
|
||||
public ProductType ProductType { get; set; }
|
||||
|
||||
public required string ManufacturerId { get; set; }
|
||||
|
||||
public double Price { get; set; }
|
||||
|
||||
public bool IsDeleted { get; set; }
|
||||
|
||||
public Manufacturer? Manufacturer { get; set; }
|
||||
|
||||
[ForeignKey("ProductId")]
|
||||
public List<ProductHistory>? ProductHistories { get; set; }
|
||||
|
||||
[ForeignKey("ProductId")]
|
||||
public List<SaleProduct>? SaleProducts { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
namespace CatHasPawsDatabase.Models;
|
||||
|
||||
internal class ProductHistory
|
||||
{
|
||||
public string Id { get; set; } = Guid.NewGuid().ToString();
|
||||
|
||||
public required string ProductId { get; set; }
|
||||
|
||||
public double OldPrice { get; set; }
|
||||
|
||||
public DateTime ChangeDate { get; set; }
|
||||
|
||||
public Product? Product { get; set; }
|
||||
}
|
||||
14
TheCatHasPawsProject/CatHasPawsDatabase/Models/Salary.cs
Normal file
14
TheCatHasPawsProject/CatHasPawsDatabase/Models/Salary.cs
Normal file
@@ -0,0 +1,14 @@
|
||||
namespace CatHasPawsDatabase.Models;
|
||||
|
||||
internal class Salary
|
||||
{
|
||||
public string Id { get; set; } = Guid.NewGuid().ToString();
|
||||
|
||||
public required string WorkerId { get; set; }
|
||||
|
||||
public DateTime SalaryDate { get; set; }
|
||||
|
||||
public double WorkerSalary { get; set; }
|
||||
|
||||
public Worker? Worker { get; set; }
|
||||
}
|
||||
30
TheCatHasPawsProject/CatHasPawsDatabase/Models/Sale.cs
Normal file
30
TheCatHasPawsProject/CatHasPawsDatabase/Models/Sale.cs
Normal file
@@ -0,0 +1,30 @@
|
||||
using CatHasPawsContratcs.Enums;
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
|
||||
namespace CatHasPawsDatabase.Models;
|
||||
|
||||
internal class Sale
|
||||
{
|
||||
public string Id { get; set; } = Guid.NewGuid().ToString();
|
||||
|
||||
public required string WorkerId { get; set; }
|
||||
|
||||
public string? BuyerId { get; set; }
|
||||
|
||||
public DateTime SaleDate { get; set; }
|
||||
|
||||
public double Sum { get; set; }
|
||||
|
||||
public DiscountType DiscountType { get; set; }
|
||||
|
||||
public double Discount { get; set; }
|
||||
|
||||
public bool IsCancel { get; set; }
|
||||
|
||||
public Worker? Worker { get; set; }
|
||||
|
||||
public Buyer? Buyer { get; set; }
|
||||
|
||||
[ForeignKey("SaleId")]
|
||||
public List<SaleProduct>? SaleProducts { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
namespace CatHasPawsDatabase.Models;
|
||||
|
||||
internal class SaleProduct
|
||||
{
|
||||
public required string SaleId { get; set; }
|
||||
|
||||
public required string ProductId { get; set; }
|
||||
|
||||
public int Count { get; set; }
|
||||
|
||||
public double Price { get; set; }
|
||||
|
||||
public Sale? Sale { get; set; }
|
||||
|
||||
public Product? Product { get; set; }
|
||||
}
|
||||
33
TheCatHasPawsProject/CatHasPawsDatabase/Models/Worker.cs
Normal file
33
TheCatHasPawsProject/CatHasPawsDatabase/Models/Worker.cs
Normal file
@@ -0,0 +1,33 @@
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
|
||||
namespace CatHasPawsDatabase.Models;
|
||||
|
||||
internal class Worker
|
||||
{
|
||||
public required string Id { get; set; }
|
||||
|
||||
public required string FIO { get; set; }
|
||||
|
||||
public required string PostId { get; set; }
|
||||
|
||||
public DateTime BirthDate { get; set; }
|
||||
|
||||
public DateTime EmploymentDate { get; set; }
|
||||
|
||||
public bool IsDeleted { get; set; }
|
||||
|
||||
[NotMapped]
|
||||
public Post? Post { get; set; }
|
||||
|
||||
[ForeignKey("WorkerId")]
|
||||
public List<Salary>? Salaries { get; set; }
|
||||
|
||||
[ForeignKey("WorkerId")]
|
||||
public List<Sale>? Sales { get; set; }
|
||||
|
||||
public Worker AddPost(Post? post)
|
||||
{
|
||||
Post = post;
|
||||
return this;
|
||||
}
|
||||
}
|
||||
@@ -33,61 +33,53 @@ internal class PostBusinessLogicContractTests
|
||||
//Arrange
|
||||
var listOriginal = new List<PostDataModel>()
|
||||
{
|
||||
new(Guid.NewGuid().ToString(),"name 1", PostType.Assistant, 10, true, DateTime.UtcNow),
|
||||
new(Guid.NewGuid().ToString(), "name 2", PostType.Assistant, 10, false, DateTime.UtcNow),
|
||||
new(Guid.NewGuid().ToString(), "name 3", PostType.Assistant, 10, true, DateTime.UtcNow),
|
||||
new(Guid.NewGuid().ToString(),"name 1", PostType.Assistant, 10),
|
||||
new(Guid.NewGuid().ToString(), "name 2", PostType.Assistant, 10),
|
||||
new(Guid.NewGuid().ToString(), "name 3", PostType.Assistant, 10),
|
||||
};
|
||||
_postStorageContract.Setup(x => x.GetList(It.IsAny<bool>())).Returns(listOriginal);
|
||||
_postStorageContract.Setup(x => x.GetList()).Returns(listOriginal);
|
||||
//Act
|
||||
var listOnlyActive = _postBusinessLogicContract.GetAllPosts(true);
|
||||
var listAll = _postBusinessLogicContract.GetAllPosts(false);
|
||||
var list = _postBusinessLogicContract.GetAllPosts();
|
||||
//Assert
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(listOnlyActive, Is.Not.Null);
|
||||
Assert.That(listAll, Is.Not.Null);
|
||||
Assert.That(listOnlyActive, Is.EquivalentTo(listOriginal));
|
||||
Assert.That(listAll, Is.EquivalentTo(listOriginal));
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Is.EquivalentTo(listOriginal));
|
||||
});
|
||||
_postStorageContract.Verify(x => x.GetList(true), Times.Once);
|
||||
_postStorageContract.Verify(x => x.GetList(false), Times.Once);
|
||||
_postStorageContract.Verify(x => x.GetList(), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetAllPosts_ReturnEmptyList_Test()
|
||||
{
|
||||
//Arrange
|
||||
_postStorageContract.Setup(x => x.GetList(It.IsAny<bool>())).Returns([]);
|
||||
_postStorageContract.Setup(x => x.GetList()).Returns([]);
|
||||
//Act
|
||||
var listOnlyActive = _postBusinessLogicContract.GetAllPosts(true);
|
||||
var listAll = _postBusinessLogicContract.GetAllPosts(false);
|
||||
var list = _postBusinessLogicContract.GetAllPosts();
|
||||
//Assert
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(listOnlyActive, Is.Not.Null);
|
||||
Assert.That(listAll, Is.Not.Null);
|
||||
Assert.That(listOnlyActive, Has.Count.EqualTo(0));
|
||||
Assert.That(listAll, Has.Count.EqualTo(0));
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(0));
|
||||
});
|
||||
_postStorageContract.Verify(x => x.GetList(It.IsAny<bool>()), Times.Exactly(2));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetAllPosts_ReturnNull_ThrowException_Test()
|
||||
{
|
||||
//Act&Assert
|
||||
Assert.That(() => _postBusinessLogicContract.GetAllPosts(It.IsAny<bool>()), Throws.TypeOf<NullListException>());
|
||||
_postStorageContract.Verify(x => x.GetList(It.IsAny<bool>()), Times.Once);
|
||||
Assert.That(() => _postBusinessLogicContract.GetAllPosts(), Throws.TypeOf<NullListException>());
|
||||
_postStorageContract.Verify(x => x.GetList(), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetAllPosts_StorageThrowError_ThrowException_Test()
|
||||
{
|
||||
//Arrange
|
||||
_postStorageContract.Setup(x => x.GetList(It.IsAny<bool>())).Throws(new StorageException(new InvalidOperationException()));
|
||||
_postStorageContract.Setup(x => x.GetList()).Throws(new StorageException(new InvalidOperationException()));
|
||||
//Act&Assert
|
||||
Assert.That(() => _postBusinessLogicContract.GetAllPosts(It.IsAny<bool>()), Throws.TypeOf<StorageException>());
|
||||
_postStorageContract.Verify(x => x.GetList(It.IsAny<bool>()), Times.Once);
|
||||
Assert.That(() => _postBusinessLogicContract.GetAllPosts(), Throws.TypeOf<StorageException>());
|
||||
_postStorageContract.Verify(x => x.GetList(), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
@@ -97,8 +89,8 @@ internal class PostBusinessLogicContractTests
|
||||
var postId = Guid.NewGuid().ToString();
|
||||
var listOriginal = new List<PostDataModel>()
|
||||
{
|
||||
new(postId, "name 1", PostType.Assistant, 10, true, DateTime.UtcNow),
|
||||
new(postId, "name 2", PostType.Assistant, 10, false, DateTime.UtcNow)
|
||||
new(postId, "name 1", PostType.Assistant, 10),
|
||||
new(postId, "name 2", PostType.Assistant, 10)
|
||||
};
|
||||
_postStorageContract.Setup(x => x.GetPostWithHistory(It.IsAny<string>())).Returns(listOriginal);
|
||||
//Act
|
||||
@@ -162,7 +154,7 @@ internal class PostBusinessLogicContractTests
|
||||
{
|
||||
//Arrange
|
||||
var id = Guid.NewGuid().ToString();
|
||||
var record = new PostDataModel(id, "name", PostType.Assistant, 10, true, DateTime.UtcNow);
|
||||
var record = new PostDataModel(id, "name", PostType.Assistant, 10);
|
||||
_postStorageContract.Setup(x => x.GetElementById(id)).Returns(record);
|
||||
//Act
|
||||
var element = _postBusinessLogicContract.GetPostByData(id);
|
||||
@@ -177,7 +169,7 @@ internal class PostBusinessLogicContractTests
|
||||
{
|
||||
//Arrange
|
||||
var postName = "name";
|
||||
var record = new PostDataModel(Guid.NewGuid().ToString(), postName, PostType.Assistant, 10, true, DateTime.UtcNow);
|
||||
var record = new PostDataModel(Guid.NewGuid().ToString(), postName, PostType.Assistant, 10);
|
||||
_postStorageContract.Setup(x => x.GetElementByName(postName)).Returns(record);
|
||||
//Act
|
||||
var element = _postBusinessLogicContract.GetPostByData(postName);
|
||||
@@ -233,12 +225,11 @@ internal class PostBusinessLogicContractTests
|
||||
{
|
||||
//Arrange
|
||||
var flag = false;
|
||||
var record = new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Supervisor, 10, true, DateTime.UtcNow.AddDays(-1));
|
||||
var record = new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Supervisor, 10);
|
||||
_postStorageContract.Setup(x => x.AddElement(It.IsAny<PostDataModel>()))
|
||||
.Callback((PostDataModel x) =>
|
||||
{
|
||||
flag = x.Id == record.Id && x.PostName == record.PostName && x.PostType == record.PostType && x.Salary == record.Salary &&
|
||||
x.ChangeDate == record.ChangeDate;
|
||||
flag = x.Id == record.Id && x.PostName == record.PostName && x.PostType == record.PostType && x.Salary == record.Salary;
|
||||
});
|
||||
//Act
|
||||
_postBusinessLogicContract.InsertPost(record);
|
||||
@@ -253,7 +244,7 @@ internal class PostBusinessLogicContractTests
|
||||
//Arrange
|
||||
_postStorageContract.Setup(x => x.AddElement(It.IsAny<PostDataModel>())).Throws(new ElementExistsException("Data", "Data"));
|
||||
//Act&Assert
|
||||
Assert.That(() => _postBusinessLogicContract.InsertPost(new(Guid.NewGuid().ToString(), "name", PostType.Supervisor, 10, true, DateTime.UtcNow)), Throws.TypeOf<ElementExistsException>());
|
||||
Assert.That(() => _postBusinessLogicContract.InsertPost(new(Guid.NewGuid().ToString(), "name", PostType.Supervisor, 10)), Throws.TypeOf<ElementExistsException>());
|
||||
_postStorageContract.Verify(x => x.AddElement(It.IsAny<PostDataModel>()), Times.Once);
|
||||
}
|
||||
|
||||
@@ -269,7 +260,7 @@ internal class PostBusinessLogicContractTests
|
||||
public void InsertPost_InvalidRecord_ThrowException_Test()
|
||||
{
|
||||
//Act&Assert
|
||||
Assert.That(() => _postBusinessLogicContract.InsertPost(new PostDataModel("id", "name", PostType.Supervisor, 10, true, DateTime.UtcNow)), Throws.TypeOf<ValidationException>());
|
||||
Assert.That(() => _postBusinessLogicContract.InsertPost(new PostDataModel("id", "name", PostType.Supervisor, 10)), Throws.TypeOf<ValidationException>());
|
||||
_postStorageContract.Verify(x => x.AddElement(It.IsAny<PostDataModel>()), Times.Never);
|
||||
}
|
||||
|
||||
@@ -279,7 +270,7 @@ internal class PostBusinessLogicContractTests
|
||||
//Arrange
|
||||
_postStorageContract.Setup(x => x.AddElement(It.IsAny<PostDataModel>())).Throws(new StorageException(new InvalidOperationException()));
|
||||
//Act&Assert
|
||||
Assert.That(() => _postBusinessLogicContract.InsertPost(new(Guid.NewGuid().ToString(), "name", PostType.Supervisor, 10, true, DateTime.UtcNow)), Throws.TypeOf<StorageException>());
|
||||
Assert.That(() => _postBusinessLogicContract.InsertPost(new(Guid.NewGuid().ToString(), "name", PostType.Supervisor, 10)), Throws.TypeOf<StorageException>());
|
||||
_postStorageContract.Verify(x => x.AddElement(It.IsAny<PostDataModel>()), Times.Once);
|
||||
}
|
||||
|
||||
@@ -288,12 +279,11 @@ internal class PostBusinessLogicContractTests
|
||||
{
|
||||
//Arrange
|
||||
var flag = false;
|
||||
var record = new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Supervisor, 10, true, DateTime.UtcNow.AddDays(-1));
|
||||
var record = new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Supervisor, 10);
|
||||
_postStorageContract.Setup(x => x.UpdElement(It.IsAny<PostDataModel>()))
|
||||
.Callback((PostDataModel x) =>
|
||||
{
|
||||
flag = x.Id == record.Id && x.PostName == record.PostName && x.PostType == record.PostType && x.Salary == record.Salary &&
|
||||
x.ChangeDate == record.ChangeDate;
|
||||
flag = x.Id == record.Id && x.PostName == record.PostName && x.PostType == record.PostType && x.Salary == record.Salary;
|
||||
});
|
||||
//Act
|
||||
_postBusinessLogicContract.UpdatePost(record);
|
||||
@@ -308,7 +298,7 @@ internal class PostBusinessLogicContractTests
|
||||
//Arrange
|
||||
_postStorageContract.Setup(x => x.UpdElement(It.IsAny<PostDataModel>())).Throws(new ElementNotFoundException(""));
|
||||
//Act&Assert
|
||||
Assert.That(() => _postBusinessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "name", PostType.Supervisor, 10, true, DateTime.UtcNow)), Throws.TypeOf<ElementNotFoundException>());
|
||||
Assert.That(() => _postBusinessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "name", PostType.Supervisor, 10)), Throws.TypeOf<ElementNotFoundException>());
|
||||
_postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Once);
|
||||
}
|
||||
|
||||
@@ -318,7 +308,7 @@ internal class PostBusinessLogicContractTests
|
||||
//Arrange
|
||||
_postStorageContract.Setup(x => x.UpdElement(It.IsAny<PostDataModel>())).Throws(new ElementExistsException("Data", "Data"));
|
||||
//Act&Assert
|
||||
Assert.That(() => _postBusinessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "anme", PostType.Supervisor, 10, true, DateTime.UtcNow)), Throws.TypeOf<ElementExistsException>());
|
||||
Assert.That(() => _postBusinessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "anme", PostType.Supervisor, 10)), Throws.TypeOf<ElementExistsException>());
|
||||
_postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Once);
|
||||
}
|
||||
|
||||
@@ -334,7 +324,7 @@ internal class PostBusinessLogicContractTests
|
||||
public void UpdatePost_InvalidRecord_ThrowException_Test()
|
||||
{
|
||||
//Act&Assert
|
||||
Assert.That(() => _postBusinessLogicContract.UpdatePost(new PostDataModel("id", "name", PostType.Supervisor, 10, true, DateTime.UtcNow)), Throws.TypeOf<ValidationException>());
|
||||
Assert.That(() => _postBusinessLogicContract.UpdatePost(new PostDataModel("id", "name", PostType.Supervisor, 10)), Throws.TypeOf<ValidationException>());
|
||||
_postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Never);
|
||||
}
|
||||
|
||||
@@ -344,7 +334,7 @@ internal class PostBusinessLogicContractTests
|
||||
//Arrange
|
||||
_postStorageContract.Setup(x => x.UpdElement(It.IsAny<PostDataModel>())).Throws(new StorageException(new InvalidOperationException()));
|
||||
//Act&Assert
|
||||
Assert.That(() => _postBusinessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "name", PostType.Supervisor, 10, true, DateTime.UtcNow)), Throws.TypeOf<StorageException>());
|
||||
Assert.That(() => _postBusinessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "name", PostType.Supervisor, 10)), Throws.TypeOf<StorageException>());
|
||||
_postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Once);
|
||||
}
|
||||
|
||||
|
||||
@@ -186,12 +186,12 @@ internal class SalaryBusinessLogicContractTests
|
||||
{
|
||||
//Arrange
|
||||
var workerId = 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(), workerId, null, saleSum, DiscountType.None, 0, false, [])]);
|
||||
.Returns([new SaleDataModel(Guid.NewGuid().ToString(), workerId, null, DiscountType.None, false, [new SaleProductDataModel(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.Assistant, postSalary, true, DateTime.UtcNow));
|
||||
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Assistant, postSalary));
|
||||
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
|
||||
.Returns([new WorkerDataModel(workerId, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)]);
|
||||
var sum = 0.0;
|
||||
@@ -220,13 +220,13 @@ internal class SalaryBusinessLogicContractTests
|
||||
new(worker3Id, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)
|
||||
};
|
||||
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
|
||||
.Returns([new SaleDataModel(Guid.NewGuid().ToString(), worker1Id, null, 1, DiscountType.None, 0, false, []),
|
||||
new SaleDataModel(Guid.NewGuid().ToString(), worker1Id, null, 1, DiscountType.None, 0, false, []),
|
||||
new SaleDataModel(Guid.NewGuid().ToString(), worker2Id, null, 1, DiscountType.None, 0, false, []),
|
||||
new SaleDataModel(Guid.NewGuid().ToString(), worker3Id, null, 1, DiscountType.None, 0, false, []),
|
||||
new SaleDataModel(Guid.NewGuid().ToString(), worker3Id, null, 1, DiscountType.None, 0, false, [])]);
|
||||
.Returns([new SaleDataModel(Guid.NewGuid().ToString(), worker1Id, null, DiscountType.None, false, []),
|
||||
new SaleDataModel(Guid.NewGuid().ToString(), worker1Id, null, DiscountType.None, false, []),
|
||||
new SaleDataModel(Guid.NewGuid().ToString(), worker2Id, null, DiscountType.None, false, []),
|
||||
new SaleDataModel(Guid.NewGuid().ToString(), worker3Id, null, DiscountType.None, false, []),
|
||||
new SaleDataModel(Guid.NewGuid().ToString(), worker3Id, null, DiscountType.None, false, [])]);
|
||||
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
|
||||
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Assistant, 2000, true, DateTime.UtcNow));
|
||||
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Assistant, 2000));
|
||||
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
|
||||
.Returns(list);
|
||||
//Act
|
||||
@@ -236,7 +236,7 @@ internal class SalaryBusinessLogicContractTests
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void CalculateSalaryByMounth_WithoitSalesByWorker_Test()
|
||||
public void CalculateSalaryByMounth_WithoutSalesByWorker_Test()
|
||||
{
|
||||
//Arrange
|
||||
var postSalary = 2000.0;
|
||||
@@ -244,7 +244,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.Assistant, postSalary, true, DateTime.UtcNow));
|
||||
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Assistant, postSalary));
|
||||
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
|
||||
.Returns([new WorkerDataModel(workerId, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)]);
|
||||
var sum = 0.0;
|
||||
@@ -266,7 +266,7 @@ internal class SalaryBusinessLogicContractTests
|
||||
//Arrange
|
||||
var workerId = Guid.NewGuid().ToString();
|
||||
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
|
||||
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Assistant, 2000, true, DateTime.UtcNow));
|
||||
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Assistant, 2000));
|
||||
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
|
||||
.Returns([new WorkerDataModel(workerId, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)]);
|
||||
//Act&Assert
|
||||
@@ -279,7 +279,7 @@ internal class SalaryBusinessLogicContractTests
|
||||
//Arrange
|
||||
var workerId = Guid.NewGuid().ToString();
|
||||
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
|
||||
.Returns([new SaleDataModel(Guid.NewGuid().ToString(), workerId, null, 200, DiscountType.None, 0, false, [])]);
|
||||
.Returns([new SaleDataModel(Guid.NewGuid().ToString(), workerId, null, DiscountType.None, false, [])]);
|
||||
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
|
||||
.Returns([new WorkerDataModel(workerId, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)]);
|
||||
//Act&Assert
|
||||
@@ -292,9 +292,9 @@ internal class SalaryBusinessLogicContractTests
|
||||
//Arrange
|
||||
var workerId = Guid.NewGuid().ToString();
|
||||
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
|
||||
.Returns([new SaleDataModel(Guid.NewGuid().ToString(), workerId, null, 200, DiscountType.None, 0, false, [])]);
|
||||
.Returns([new SaleDataModel(Guid.NewGuid().ToString(), workerId, null, DiscountType.None, false, [])]);
|
||||
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
|
||||
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Assistant, 2000, true, DateTime.UtcNow));
|
||||
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Assistant, 2000));
|
||||
//Act&Assert
|
||||
Assert.That(() => _salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow), Throws.TypeOf<NullListException>());
|
||||
}
|
||||
@@ -307,7 +307,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.Assistant, 2000, true, DateTime.UtcNow));
|
||||
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Assistant, 2000));
|
||||
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
|
||||
.Returns([new WorkerDataModel(workerId, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)]);
|
||||
//Act&Assert
|
||||
@@ -320,7 +320,7 @@ internal class SalaryBusinessLogicContractTests
|
||||
//Arrange
|
||||
var workerId = Guid.NewGuid().ToString();
|
||||
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
|
||||
.Returns([new SaleDataModel(Guid.NewGuid().ToString(), workerId, null, 200, DiscountType.None, 0, false, [])]);
|
||||
.Returns([new SaleDataModel(Guid.NewGuid().ToString(), workerId, null, DiscountType.None, false, [])]);
|
||||
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
|
||||
.Throws(new StorageException(new InvalidOperationException()));
|
||||
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
|
||||
@@ -335,9 +335,9 @@ internal class SalaryBusinessLogicContractTests
|
||||
//Arrange
|
||||
var workerId = Guid.NewGuid().ToString();
|
||||
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
|
||||
.Returns([new SaleDataModel(Guid.NewGuid().ToString(), workerId, null, 200, DiscountType.None, 0, false, [])]);
|
||||
.Returns([new SaleDataModel(Guid.NewGuid().ToString(), workerId, null, DiscountType.None, false, [])]);
|
||||
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
|
||||
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Assistant, 2000, true, DateTime.UtcNow));
|
||||
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Assistant, 2000));
|
||||
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
|
||||
.Throws(new StorageException(new InvalidOperationException()));
|
||||
//Act&Assert
|
||||
|
||||
@@ -34,10 +34,10 @@ internal class SaleBusinessLogicContractTests
|
||||
var date = DateTime.UtcNow;
|
||||
var listOriginal = new List<SaleDataModel>()
|
||||
{
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, DiscountType.None, 0, false,
|
||||
[new SaleProductDataModel(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 SaleProductDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5, 1.2)]),
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, DiscountType.None, false, []),
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, DiscountType.None, false, []),
|
||||
};
|
||||
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Returns(listOriginal);
|
||||
//Act
|
||||
@@ -98,10 +98,10 @@ internal class SaleBusinessLogicContractTests
|
||||
var workerId = Guid.NewGuid().ToString();
|
||||
var listOriginal = new List<SaleDataModel>()
|
||||
{
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, DiscountType.None, 0, false,
|
||||
[new SaleProductDataModel(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 SaleProductDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5, 1.2)]),
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, DiscountType.None, false, []),
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, DiscountType.None, false, []),
|
||||
};
|
||||
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Returns(listOriginal);
|
||||
//Act
|
||||
@@ -179,10 +179,10 @@ internal class SaleBusinessLogicContractTests
|
||||
var buyerId = Guid.NewGuid().ToString();
|
||||
var listOriginal = new List<SaleDataModel>()
|
||||
{
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, DiscountType.None, 0, false,
|
||||
[new SaleProductDataModel(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 SaleProductDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5, 1.2)]),
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, DiscountType.None, false, []),
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, DiscountType.None, false, []),
|
||||
};
|
||||
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Returns(listOriginal);
|
||||
//Act
|
||||
@@ -260,10 +260,10 @@ internal class SaleBusinessLogicContractTests
|
||||
var productId = Guid.NewGuid().ToString();
|
||||
var listOriginal = new List<SaleDataModel>()
|
||||
{
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, DiscountType.None, 0, false,
|
||||
[new SaleProductDataModel(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 SaleProductDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5, 1.2)]),
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, DiscountType.None, false, []),
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, DiscountType.None, false, []),
|
||||
};
|
||||
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Returns(listOriginal);
|
||||
//Act
|
||||
@@ -338,8 +338,8 @@ internal class SaleBusinessLogicContractTests
|
||||
{
|
||||
//Arrange
|
||||
var id = Guid.NewGuid().ToString();
|
||||
var record = new SaleDataModel(id, Guid.NewGuid().ToString(), null, 10, DiscountType.None, 0, false,
|
||||
[new SaleProductDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]);
|
||||
var record = new SaleDataModel(id, Guid.NewGuid().ToString(), null, DiscountType.None, false,
|
||||
[new SaleProductDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5, 1.2)]);
|
||||
_saleStorageContract.Setup(x => x.GetElementById(id)).Returns(record);
|
||||
//Act
|
||||
var element = _saleBusinessLogicContract.GetSaleByData(id);
|
||||
@@ -389,17 +389,17 @@ 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 SaleProductDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]);
|
||||
var record = new SaleDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), DiscountType.None,
|
||||
false, [new SaleProductDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5, 1.2)]);
|
||||
_saleStorageContract.Setup(x => x.AddElement(It.IsAny<SaleDataModel>()))
|
||||
.Callback((SaleDataModel x) =>
|
||||
{
|
||||
flag = x.Id == record.Id && x.WorkerId == record.WorkerId && x.BuyerId == record.BuyerId &&
|
||||
x.SaleDate == record.SaleDate && x.Sum == record.Sum && x.DiscountType == record.DiscountType &&
|
||||
x.Discount == record.Discount && x.IsCancel == record.IsCancel && x.Products.Count == record.Products.Count &&
|
||||
x.Products.First().ProductId == record.Products.First().ProductId &&
|
||||
x.Products.First().SaleId == record.Products.First().SaleId &&
|
||||
x.Products.First().Count == record.Products.First().Count;
|
||||
x.Discount == record.Discount && x.IsCancel == record.IsCancel && x.Products?.Count == record.Products?.Count &&
|
||||
x.Products?.First().ProductId == record.Products?.First().ProductId &&
|
||||
x.Products?.First().SaleId == record.Products?.First().SaleId &&
|
||||
x.Products?.First().Count == record.Products?.First().Count;
|
||||
});
|
||||
//Act
|
||||
_saleBusinessLogicContract.InsertSale(record);
|
||||
@@ -415,7 +415,7 @@ internal class SaleBusinessLogicContractTests
|
||||
_saleStorageContract.Setup(x => x.AddElement(It.IsAny<SaleDataModel>())).Throws(new ElementExistsException("Data", "Data"));
|
||||
//Act&Assert
|
||||
Assert.That(() => _saleBusinessLogicContract.InsertSale(new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(),
|
||||
Guid.NewGuid().ToString(), 10, DiscountType.None, 10, false, [new SaleProductDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<ElementExistsException>());
|
||||
Guid.NewGuid().ToString(), DiscountType.None, false, [new SaleProductDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5, 1.2)])), Throws.TypeOf<ElementExistsException>());
|
||||
_saleStorageContract.Verify(x => x.AddElement(It.IsAny<SaleDataModel>()), Times.Once);
|
||||
}
|
||||
|
||||
@@ -431,7 +431,7 @@ internal class SaleBusinessLogicContractTests
|
||||
public void InsertSale_InvalidRecord_ThrowException_Test()
|
||||
{
|
||||
//Act&Assert
|
||||
Assert.That(() => _saleBusinessLogicContract.InsertSale(new SaleDataModel("id", Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 10, DiscountType.None, 10, false, [])), Throws.TypeOf<ValidationException>());
|
||||
Assert.That(() => _saleBusinessLogicContract.InsertSale(new SaleDataModel("id", Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), DiscountType.None, false, [])), Throws.TypeOf<ValidationException>());
|
||||
_saleStorageContract.Verify(x => x.AddElement(It.IsAny<SaleDataModel>()), Times.Never);
|
||||
}
|
||||
|
||||
@@ -442,7 +442,7 @@ internal class SaleBusinessLogicContractTests
|
||||
_saleStorageContract.Setup(x => x.AddElement(It.IsAny<SaleDataModel>())).Throws(new StorageException(new InvalidOperationException()));
|
||||
//Act&Assert
|
||||
Assert.That(() => _saleBusinessLogicContract.InsertSale(new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(),
|
||||
Guid.NewGuid().ToString(), 10, DiscountType.None, 10, false, [new SaleProductDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<StorageException>());
|
||||
Guid.NewGuid().ToString(), DiscountType.None, false, [new SaleProductDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5, 1.2)])), Throws.TypeOf<StorageException>());
|
||||
_saleStorageContract.Verify(x => x.AddElement(It.IsAny<SaleDataModel>()), Times.Once);
|
||||
}
|
||||
|
||||
|
||||
@@ -8,8 +8,17 @@
|
||||
<IsPackable>false</IsPackable>
|
||||
</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.2" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="9.0.2" />
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.11.1" />
|
||||
<PackageReference Include="Moq" Version="4.20.72" />
|
||||
<PackageReference Include="NUnit" Version="4.2.2" />
|
||||
@@ -20,6 +29,8 @@
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\CatHasPawsBusinessLogic\CatHasPawsBusinessLogic.csproj" />
|
||||
<ProjectReference Include="..\CatHasPawsContratcs\CatHasPawsContratcs.csproj" />
|
||||
<ProjectReference Include="..\CatHasPawsDatabase\CatHasPawsDatabase.csproj" />
|
||||
<ProjectReference Include="..\CatHasPawsWebApi\CatHasPawsWebApi.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
||||
@@ -10,41 +10,41 @@ internal class PostDataModelTests
|
||||
[Test]
|
||||
public void IdIsNullOrEmptyTest()
|
||||
{
|
||||
var post = CreateDataModel(null, "name", PostType.Assistant, 10, true, DateTime.UtcNow);
|
||||
var post = CreateDataModel(null, "name", PostType.Assistant, 10);
|
||||
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
|
||||
post = CreateDataModel(string.Empty, "name", PostType.Assistant, 10, true, DateTime.UtcNow);
|
||||
post = CreateDataModel(string.Empty, "name", PostType.Assistant, 10);
|
||||
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void IdIsNotGuidTest()
|
||||
{
|
||||
var post = CreateDataModel("id", "name", PostType.Assistant, 10, true, DateTime.UtcNow);
|
||||
var post = CreateDataModel("id", "name", PostType.Assistant, 10);
|
||||
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void PostNameIsEmptyTest()
|
||||
{
|
||||
var manufacturer = CreateDataModel(Guid.NewGuid().ToString(), null, PostType.Assistant, 10, true, DateTime.UtcNow);
|
||||
var manufacturer = CreateDataModel(Guid.NewGuid().ToString(), null, PostType.Assistant, 10);
|
||||
Assert.That(() => manufacturer.Validate(), Throws.TypeOf<ValidationException>());
|
||||
manufacturer = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, PostType.Assistant, 10, true, DateTime.UtcNow);
|
||||
manufacturer = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, PostType.Assistant, 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.Assistant, 0, true, DateTime.UtcNow);
|
||||
var post = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.Assistant, 0);
|
||||
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
|
||||
post = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.Assistant, -10, true, DateTime.UtcNow);
|
||||
post = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.Assistant, -10);
|
||||
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
@@ -55,9 +55,7 @@ internal class PostDataModelTests
|
||||
var postName = "name";
|
||||
var postType = PostType.Assistant;
|
||||
var salary = 10;
|
||||
var isActual = false;
|
||||
var changeDate = DateTime.UtcNow.AddDays(-1);
|
||||
var post = CreateDataModel(postId, postName, postType, salary, isActual, changeDate);
|
||||
var post = CreateDataModel(postId, postName, postType, salary);
|
||||
Assert.That(() => post.Validate(), Throws.Nothing);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
@@ -65,11 +63,9 @@ internal class PostDataModelTests
|
||||
Assert.That(post.PostName, Is.EqualTo(postName));
|
||||
Assert.That(post.PostType, Is.EqualTo(postType));
|
||||
Assert.That(post.Salary, Is.EqualTo(salary));
|
||||
Assert.That(post.IsActual, Is.EqualTo(isActual));
|
||||
Assert.That(post.ChangeDate, Is.EqualTo(changeDate));
|
||||
});
|
||||
}
|
||||
|
||||
private static PostDataModel CreateDataModel(string? id, string? postName, PostType postType, double salary, bool isActual, DateTime changeDate) =>
|
||||
new(id, postName, postType, salary, isActual, changeDate);
|
||||
private static PostDataModel CreateDataModel(string? id, string? postName, PostType postType, double salary) =>
|
||||
new(id, postName, postType, salary);
|
||||
}
|
||||
@@ -10,88 +10,120 @@ internal class SaleDataModelTests
|
||||
[Test]
|
||||
public void IdIsNullOrEmptyTest()
|
||||
{
|
||||
var sale = CreateDataModel(null, Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 10, DiscountType.OnSale, 10, false, CreateSubDataModel());
|
||||
var sale = CreateDataModel(null, Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), DiscountType.OnSale, false, CreateSubDataModel());
|
||||
Assert.That(() => sale.Validate(), Throws.TypeOf<ValidationException>());
|
||||
sale = CreateDataModel(string.Empty, Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 10, DiscountType.OnSale, 10, false, CreateSubDataModel());
|
||||
sale = CreateDataModel(string.Empty, Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), DiscountType.OnSale, false, CreateSubDataModel());
|
||||
Assert.That(() => sale.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void IdIsNotGuidTest()
|
||||
{
|
||||
var sale = CreateDataModel("id", Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 10, DiscountType.OnSale, 10, false, CreateSubDataModel());
|
||||
var sale = CreateDataModel("id", Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), DiscountType.OnSale, false, CreateSubDataModel());
|
||||
Assert.That(() => sale.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
[Test]
|
||||
public void WorkerIdIsNullOrEmptyTest()
|
||||
{
|
||||
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 WorkerIdIsNotGuidTest()
|
||||
{
|
||||
var sale = CreateDataModel(Guid.NewGuid().ToString(), "workerId", Guid.NewGuid().ToString(), 10, DiscountType.OnSale, 10, false, CreateSubDataModel());
|
||||
var sale = CreateDataModel(Guid.NewGuid().ToString(), "workerId", Guid.NewGuid().ToString(), DiscountType.OnSale, false, CreateSubDataModel());
|
||||
Assert.That(() => sale.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void BuyerIdIsNotGuidTest()
|
||||
{
|
||||
var sale = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), "buyerId", 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(), "buyerId", DiscountType.OnSale, false, CreateSubDataModel());
|
||||
Assert.That(() => sale.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ProductsIsNullOrEmptyTest()
|
||||
{
|
||||
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 workerId = Guid.NewGuid().ToString();
|
||||
var buyerId = Guid.NewGuid().ToString();
|
||||
var products = new List<SaleProductDataModel>()
|
||||
{
|
||||
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 = products.Sum(x => x.Price * x.Count);
|
||||
var saleNone = CreateDataModel(saleId, workerId, buyerId, DiscountType.None, isCancel, products);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(saleNone.Sum, Is.EqualTo(totalSum));
|
||||
Assert.That(saleNone.Discount, Is.EqualTo(0));
|
||||
});
|
||||
var saleOnSale = CreateDataModel(saleId, workerId, buyerId, DiscountType.OnSale, isCancel, products);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(saleOnSale.Sum, Is.EqualTo(totalSum));
|
||||
Assert.That(saleOnSale.Discount, Is.EqualTo(totalSum * 0.1));
|
||||
});
|
||||
var saleRegularCustomer = CreateDataModel(saleId, workerId, buyerId, DiscountType.RegularCustomer, isCancel, products);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(saleRegularCustomer.Sum, Is.EqualTo(totalSum));
|
||||
Assert.That(saleRegularCustomer.Discount, Is.EqualTo(totalSum * 0.5));
|
||||
});
|
||||
var saleCertificate = CreateDataModel(saleId, workerId, buyerId, DiscountType.Certificate, isCancel, products);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(saleCertificate.Sum, Is.EqualTo(totalSum));
|
||||
Assert.That(saleCertificate.Discount, Is.EqualTo(totalSum * 0.3));
|
||||
});
|
||||
var saleMulty = CreateDataModel(saleId, workerId, buyerId, DiscountType.Certificate | DiscountType.RegularCustomer, isCancel, products);
|
||||
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 workerId = Guid.NewGuid().ToString();
|
||||
var buyerId = Guid.NewGuid().ToString();
|
||||
var sum = 10;
|
||||
var discountType = DiscountType.Certificate;
|
||||
var discount = 1;
|
||||
var isCancel = true;
|
||||
var products = CreateSubDataModel();
|
||||
var sale = CreateDataModel(saleId, workerId, buyerId, sum, discountType, discount, isCancel, products);
|
||||
var sale = CreateDataModel(saleId, workerId, buyerId, discountType, isCancel, products);
|
||||
Assert.That(() => sale.Validate(), Throws.Nothing);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(sale.Id, Is.EqualTo(saleId));
|
||||
Assert.That(sale.WorkerId, Is.EqualTo(workerId));
|
||||
Assert.That(sale.BuyerId, Is.EqualTo(buyerId));
|
||||
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.Products, Is.EquivalentTo(products));
|
||||
});
|
||||
}
|
||||
|
||||
private static SaleDataModel CreateDataModel(string? id, string? workerId, string? buyerId, double sum, DiscountType discountType, double discount, bool isCancel, List<SaleProductDataModel>? products) =>
|
||||
new(id, workerId, buyerId, sum, discountType, discount, isCancel, products);
|
||||
private static SaleDataModel CreateDataModel(string? id, string? workerId, string? buyerId, DiscountType discountType, bool isCancel, List<SaleProductDataModel>? products) =>
|
||||
new(id, workerId, buyerId, discountType, isCancel, products);
|
||||
|
||||
private static List<SaleProductDataModel> CreateSubDataModel()
|
||||
=> [new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 1)];
|
||||
=> [new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 1, 1.1)];
|
||||
}
|
||||
@@ -9,41 +9,50 @@ internal class SaleProductDataModelTests
|
||||
[Test]
|
||||
public void SaleIdIsNullOrEmptyTest()
|
||||
{
|
||||
var saleProduct = CreateDataModel(null, Guid.NewGuid().ToString(), 10);
|
||||
var saleProduct = CreateDataModel(null, Guid.NewGuid().ToString(), 10, 1.1);
|
||||
Assert.That(() => saleProduct.Validate(), Throws.TypeOf<ValidationException>());
|
||||
saleProduct = CreateDataModel(string.Empty, Guid.NewGuid().ToString(), 10);
|
||||
saleProduct = CreateDataModel(string.Empty, Guid.NewGuid().ToString(), 10, 1.1);
|
||||
Assert.That(() => saleProduct.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void SaleIdIsNotGuidTest()
|
||||
{
|
||||
var saleProduct = CreateDataModel("saleId", Guid.NewGuid().ToString(), 10);
|
||||
var saleProduct = CreateDataModel("saleId", Guid.NewGuid().ToString(), 10, 1.1);
|
||||
Assert.That(() => saleProduct.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ProductIdIsNullOrEmptyTest()
|
||||
{
|
||||
var saleProduct = CreateDataModel(Guid.NewGuid().ToString(), null, 10);
|
||||
var saleProduct = CreateDataModel(Guid.NewGuid().ToString(), null, 10, 1.1);
|
||||
Assert.That(() => saleProduct.Validate(), Throws.TypeOf<ValidationException>());
|
||||
saleProduct = CreateDataModel(string.Empty, Guid.NewGuid().ToString(), 10);
|
||||
saleProduct = CreateDataModel(string.Empty, Guid.NewGuid().ToString(), 10, 1.1);
|
||||
Assert.That(() => saleProduct.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ProductIdIsNotGuidTest()
|
||||
{
|
||||
var saleProduct = CreateDataModel(Guid.NewGuid().ToString(), "productId", 10);
|
||||
var saleProduct = CreateDataModel(Guid.NewGuid().ToString(), "productId", 10, 1.1);
|
||||
Assert.That(() => saleProduct.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void CountIsLessOrZeroTest()
|
||||
{
|
||||
var saleProduct = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 0);
|
||||
var saleProduct = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 0, 1.1);
|
||||
Assert.That(() => saleProduct.Validate(), Throws.TypeOf<ValidationException>());
|
||||
saleProduct = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), -10);
|
||||
saleProduct = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), -10, 1.1);
|
||||
Assert.That(() => saleProduct.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void PriceIsLessOrZeroTest()
|
||||
{
|
||||
var saleProduct = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 1, 0);
|
||||
Assert.That(() => saleProduct.Validate(), Throws.TypeOf<ValidationException>());
|
||||
saleProduct = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 1, -10);
|
||||
Assert.That(() => saleProduct.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
@@ -53,16 +62,18 @@ internal class SaleProductDataModelTests
|
||||
var saleId = Guid.NewGuid().ToString();
|
||||
var productId = Guid.NewGuid().ToString();
|
||||
var count = 10;
|
||||
var saleProduct = CreateDataModel(saleId, productId, count);
|
||||
var price = 1.2;
|
||||
var saleProduct = CreateDataModel(saleId, productId, count, price);
|
||||
Assert.That(() => saleProduct.Validate(), Throws.Nothing);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(saleProduct.SaleId, Is.EqualTo(saleId));
|
||||
Assert.That(saleProduct.ProductId, Is.EqualTo(productId));
|
||||
Assert.That(saleProduct.Count, Is.EqualTo(count));
|
||||
Assert.That(saleProduct.Price, Is.EqualTo(price));
|
||||
});
|
||||
}
|
||||
|
||||
private static SaleProductDataModel CreateDataModel(string? saleId, string? productId, int count) =>
|
||||
new(saleId, productId, count);
|
||||
private static SaleProductDataModel CreateDataModel(string? saleId, string? productId, int count, double price) =>
|
||||
new(saleId, productId, count, price);
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
using CatHasPawsContratcs.Enums;
|
||||
using CatHasPawsDatabase;
|
||||
using CatHasPawsDatabase.Models;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace CatHasPawsTests.Infrastructure;
|
||||
|
||||
internal static class CatHasPawsDbContextExtensions
|
||||
{
|
||||
public static Buyer InsertBuyerToDatabaseAndReturn(this CatHasPawsDbContext dbContext, string? id = null, string fio = "test", string phoneNumber = "+7-777-777-77-77", double discountSize = 10)
|
||||
{
|
||||
var buyer = new Buyer() { Id = id ?? Guid.NewGuid().ToString(), FIO = fio, PhoneNumber = phoneNumber, DiscountSize = discountSize };
|
||||
dbContext.Buyers.Add(buyer);
|
||||
dbContext.SaveChanges();
|
||||
return buyer;
|
||||
}
|
||||
|
||||
public static Manufacturer InsertManufacturerToDatabaseAndReturn(this CatHasPawsDbContext dbContext, string? id = null, string manufacturerName = "test", string prevManufacturerName = "prev", string prevPrevManufacturerName = "prevPrev")
|
||||
{
|
||||
var manufacturer = new Manufacturer() { Id = id ?? Guid.NewGuid().ToString(), ManufacturerName = manufacturerName, PrevManufacturerName = prevManufacturerName, PrevPrevManufacturerName = prevPrevManufacturerName };
|
||||
dbContext.Manufacturers.Add(manufacturer);
|
||||
dbContext.SaveChanges();
|
||||
return manufacturer;
|
||||
}
|
||||
|
||||
public static Post InsertPostToDatabaseAndReturn(this CatHasPawsDbContext dbContext, string? id = null, string postName = "test", PostType postType = PostType.Assistant, 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 Product InsertProductToDatabaseAndReturn(this CatHasPawsDbContext dbContext, string manufacturerId, string? id = null, string productName = "test", ProductType productType = ProductType.Feed, double price = 1, bool isDeleted = false)
|
||||
{
|
||||
var product = new Product() { Id = id ?? Guid.NewGuid().ToString(), ManufacturerId = manufacturerId, ProductName = productName, ProductType = productType, Price = price, IsDeleted = isDeleted };
|
||||
dbContext.Products.Add(product);
|
||||
dbContext.SaveChanges();
|
||||
return product;
|
||||
}
|
||||
|
||||
public static ProductHistory InsertProductHistoryToDatabaseAndReturn(this CatHasPawsDbContext dbContext, string productId, double price = 10, DateTime? changeDate = null)
|
||||
{
|
||||
var productHistory = new ProductHistory() { Id = Guid.NewGuid().ToString(), ProductId = productId, OldPrice = price, ChangeDate = changeDate ?? DateTime.UtcNow };
|
||||
dbContext.ProductHistories.Add(productHistory);
|
||||
dbContext.SaveChanges();
|
||||
return productHistory;
|
||||
}
|
||||
|
||||
public static Salary InsertSalaryToDatabaseAndReturn(this CatHasPawsDbContext dbContext, string workerId, double workerSalary = 1, DateTime? salaryDate = null)
|
||||
{
|
||||
var salary = new Salary() { WorkerId = workerId, WorkerSalary = workerSalary, SalaryDate = salaryDate ?? DateTime.UtcNow };
|
||||
dbContext.Salaries.Add(salary);
|
||||
dbContext.SaveChanges();
|
||||
return salary;
|
||||
}
|
||||
|
||||
public static Sale InsertSaleToDatabaseAndReturn(this CatHasPawsDbContext dbContext, string workerId, string? buyerId = null, DateTime? saleDate = null, double sum = 1, DiscountType discountType = DiscountType.OnSale, double discount = 0, bool isCancel = false, List<(string, int, double)>? products = null)
|
||||
{
|
||||
var sale = new Sale() { WorkerId = workerId, BuyerId = buyerId, SaleDate = saleDate ?? DateTime.UtcNow, Sum = sum, DiscountType = discountType, Discount = discount, IsCancel = isCancel, SaleProducts = [] };
|
||||
if (products is not null)
|
||||
{
|
||||
foreach (var elem in products)
|
||||
{
|
||||
sale.SaleProducts.Add(new SaleProduct { ProductId = elem.Item1, SaleId = sale.Id, Count = elem.Item2, Price = elem.Item3 });
|
||||
}
|
||||
}
|
||||
dbContext.Sales.Add(sale);
|
||||
dbContext.SaveChanges();
|
||||
return sale;
|
||||
}
|
||||
|
||||
public static Worker InsertWorkerToDatabaseAndReturn(this CatHasPawsDbContext dbContext, string? id = null, string fio = "test", string? postId = null, DateTime? birthDate = null, DateTime? employmentDate = null, bool isDeleted = false)
|
||||
{
|
||||
var worker = new Worker() { Id = id ?? Guid.NewGuid().ToString(), FIO = fio, PostId = postId ?? Guid.NewGuid().ToString(), BirthDate = birthDate ?? DateTime.UtcNow.AddYears(-20), EmploymentDate = employmentDate ?? DateTime.UtcNow, IsDeleted = isDeleted };
|
||||
dbContext.Workers.Add(worker);
|
||||
dbContext.SaveChanges();
|
||||
return worker;
|
||||
}
|
||||
|
||||
public static Buyer? GetBuyerFromDatabase(this CatHasPawsDbContext dbContext, string id) => dbContext.Buyers.FirstOrDefault(x => x.Id == id);
|
||||
|
||||
public static Manufacturer? GetManufacturerFromDatabase(this CatHasPawsDbContext dbContext, string id) => dbContext.Manufacturers.FirstOrDefault(x => x.Id == id);
|
||||
|
||||
public static Post? GetPostFromDatabaseByPostId(this CatHasPawsDbContext dbContext, string id) => dbContext.Posts.FirstOrDefault(x => x.PostId == id && x.IsActual);
|
||||
|
||||
public static Post[] GetPostsFromDatabaseByPostId(this CatHasPawsDbContext dbContext, string id) => [.. dbContext.Posts.Where(x => x.PostId == id).OrderByDescending(x => x.ChangeDate)];
|
||||
|
||||
public static Product? GetProductFromDatabaseById(this CatHasPawsDbContext dbContext, string id) => dbContext.Products.FirstOrDefault(x => x.Id == id);
|
||||
|
||||
public static Salary[] GetSalariesFromDatabaseByWorkerId(this CatHasPawsDbContext dbContext, string id) => [.. dbContext.Salaries.Where(x => x.WorkerId == id)];
|
||||
|
||||
public static Sale? GetSaleFromDatabaseById(this CatHasPawsDbContext dbContext, string id) => dbContext.Sales.Include(x => x.SaleProducts).FirstOrDefault(x => x.Id == id);
|
||||
|
||||
public static Sale[] GetSalesByBuyerId(this CatHasPawsDbContext dbContext, string? buyerId) => [.. dbContext.Sales.Include(x => x.SaleProducts).Where(x => x.BuyerId == buyerId)];
|
||||
|
||||
public static Worker? GetWorkerFromDatabaseById(this CatHasPawsDbContext dbContext, string id) => dbContext.Workers.FirstOrDefault(x => x.Id == id);
|
||||
|
||||
public static void RemoveBuyersFromDatabase(this CatHasPawsDbContext dbContext) => dbContext.ExecuteSqlRaw("TRUNCATE \"Buyers\" CASCADE;");
|
||||
|
||||
public static void RemoveManufacturersFromDatabase(this CatHasPawsDbContext dbContext) => dbContext.ExecuteSqlRaw("TRUNCATE \"Manufacturers\" CASCADE;");
|
||||
|
||||
public static void RemovePostsFromDatabase(this CatHasPawsDbContext dbContext) => dbContext.ExecuteSqlRaw("TRUNCATE \"Posts\" CASCADE;");
|
||||
|
||||
public static void RemoveProductsFromDatabase(this CatHasPawsDbContext dbContext) => dbContext.ExecuteSqlRaw("TRUNCATE \"Products\" CASCADE;");
|
||||
|
||||
public static void RemoveSalariesFromDatabase(this CatHasPawsDbContext dbContext) => dbContext.ExecuteSqlRaw("TRUNCATE \"Salaries\" CASCADE;");
|
||||
|
||||
public static void RemoveSalesFromDatabase(this CatHasPawsDbContext dbContext) => dbContext.ExecuteSqlRaw("TRUNCATE \"Sales\" CASCADE;");
|
||||
|
||||
public static void RemoveWorkersFromDatabase(this CatHasPawsDbContext dbContext) => dbContext.ExecuteSqlRaw("TRUNCATE \"Workers\" CASCADE;");
|
||||
|
||||
private static void ExecuteSqlRaw(this CatHasPawsDbContext dbContext, string command) => dbContext.Database.ExecuteSqlRaw(command);
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
using CatHasPawsContratcs.Infrastructure;
|
||||
|
||||
namespace CatHasPawsTests.Infrastructure;
|
||||
|
||||
internal class ConfigurationDatabaseTest : IConfigurationDatabase
|
||||
{
|
||||
public string ConnectionString =>
|
||||
"Host=127.0.0.1;Port=5432;Database=CatHasPawsTest;Username=postgres;Password=postgres;";
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
using CatHasPawsContratcs.Infrastructure;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.AspNetCore.Mvc.Testing;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace CatHasPawsTests.Infrastructure;
|
||||
|
||||
internal class CustomWebApplicationFactory<TProgram> : WebApplicationFactory<TProgram>
|
||||
where TProgram : class
|
||||
{
|
||||
protected override void ConfigureWebHost(IWebHostBuilder builder)
|
||||
{
|
||||
builder.ConfigureServices(services =>
|
||||
{
|
||||
var databaseConfig = services.SingleOrDefault(x => x.ServiceType == typeof(IConfigurationDatabase));
|
||||
if (databaseConfig is not null)
|
||||
services.Remove(databaseConfig);
|
||||
|
||||
var loggerFactory = services.SingleOrDefault(x => x.ServiceType == typeof(LoggerFactory));
|
||||
if (loggerFactory is not null)
|
||||
services.Remove(loggerFactory);
|
||||
|
||||
services.AddSingleton<IConfigurationDatabase, ConfigurationDatabaseTest>();
|
||||
});
|
||||
|
||||
builder.UseEnvironment("Development");
|
||||
|
||||
base.ConfigureWebHost(builder);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
using CatHasPawsDatabase;
|
||||
using CatHasPawsTests.Infrastructure;
|
||||
|
||||
namespace CatHasPawsTests.StoragesContracts;
|
||||
|
||||
internal abstract class BaseStorageContractTest
|
||||
{
|
||||
protected CatHasPawsDbContext CatHasPawsDbContext { get; private set; }
|
||||
|
||||
[OneTimeSetUp]
|
||||
public void OneTimeSetUp()
|
||||
{
|
||||
CatHasPawsDbContext = new CatHasPawsDbContext(new ConfigurationDatabaseTest());
|
||||
|
||||
CatHasPawsDbContext.Database.EnsureDeleted();
|
||||
CatHasPawsDbContext.Database.EnsureCreated();
|
||||
}
|
||||
|
||||
[OneTimeTearDown]
|
||||
public void OneTimeTearDown()
|
||||
{
|
||||
CatHasPawsDbContext.Database.EnsureDeleted();
|
||||
CatHasPawsDbContext.Dispose();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
using CatHasPawsContratcs.DataModels;
|
||||
using CatHasPawsContratcs.Exceptions;
|
||||
using CatHasPawsDatabase.Implementations;
|
||||
using CatHasPawsDatabase.Models;
|
||||
using CatHasPawsTests.Infrastructure;
|
||||
|
||||
namespace CatHasPawsTests.StoragesContracts;
|
||||
|
||||
[TestFixture]
|
||||
internal class BuyerStorageContractTests : BaseStorageContractTest
|
||||
{
|
||||
private BuyerStorageContract _buyerStorageContract;
|
||||
|
||||
[SetUp]
|
||||
public void SetUp()
|
||||
{
|
||||
_buyerStorageContract = new BuyerStorageContract(CatHasPawsDbContext);
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
CatHasPawsDbContext.RemoveSalesFromDatabase();
|
||||
CatHasPawsDbContext.RemoveWorkersFromDatabase();
|
||||
CatHasPawsDbContext.RemoveBuyersFromDatabase();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_WhenHaveRecords_Test()
|
||||
{
|
||||
var buyer = CatHasPawsDbContext.InsertBuyerToDatabaseAndReturn(phoneNumber: "+5-555-555-55-55");
|
||||
CatHasPawsDbContext.InsertBuyerToDatabaseAndReturn(phoneNumber: "+6-666-666-66-66");
|
||||
CatHasPawsDbContext.InsertBuyerToDatabaseAndReturn(phoneNumber: "+7-777-777-77-77");
|
||||
var list = _buyerStorageContract.GetList();
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(3));
|
||||
AssertElement(list.First(x => x.Id == buyer.Id), buyer);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_WhenNoRecords_Test()
|
||||
{
|
||||
var list = _buyerStorageContract.GetList();
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Is.Empty);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenHaveRecord_Test()
|
||||
{
|
||||
var buyer = CatHasPawsDbContext.InsertBuyerToDatabaseAndReturn();
|
||||
AssertElement(_buyerStorageContract.GetElementById(buyer.Id), buyer);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenNoRecord_Test()
|
||||
{
|
||||
CatHasPawsDbContext.InsertBuyerToDatabaseAndReturn();
|
||||
Assert.That(() => _buyerStorageContract.GetElementById(Guid.NewGuid().ToString()), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementByFIO_WhenHaveRecord_Test()
|
||||
{
|
||||
var buyer = CatHasPawsDbContext.InsertBuyerToDatabaseAndReturn();
|
||||
AssertElement(_buyerStorageContract.GetElementByFIO(buyer.FIO), buyer);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementByFIO_WhenNoRecord_Test()
|
||||
{
|
||||
CatHasPawsDbContext.InsertBuyerToDatabaseAndReturn();
|
||||
Assert.That(() => _buyerStorageContract.GetElementByFIO("New Fio"), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementByPhoneNumber_WhenHaveRecord_Test()
|
||||
{
|
||||
var buyer = CatHasPawsDbContext.InsertBuyerToDatabaseAndReturn();
|
||||
AssertElement(_buyerStorageContract.GetElementByPhoneNumber(buyer.PhoneNumber), buyer);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementByPhoneNumber_WhenNoRecord_Test()
|
||||
{
|
||||
CatHasPawsDbContext.InsertBuyerToDatabaseAndReturn();
|
||||
Assert.That(() => _buyerStorageContract.GetElementByPhoneNumber("+8-888-888-88-88"), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_Test()
|
||||
{
|
||||
var buyer = CreateModel(Guid.NewGuid().ToString());
|
||||
_buyerStorageContract.AddElement(buyer);
|
||||
AssertElement(CatHasPawsDbContext.GetBuyerFromDatabase(buyer.Id), buyer);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_WhenHaveRecordWithSameId_Test()
|
||||
{
|
||||
var buyer = CreateModel(Guid.NewGuid().ToString(), "New Fio", "+5-555-555-55-55", 500);
|
||||
CatHasPawsDbContext.InsertBuyerToDatabaseAndReturn(buyer.Id);
|
||||
Assert.That(() => _buyerStorageContract.AddElement(buyer), Throws.TypeOf<ElementExistsException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_WhenHaveRecordWithSamePhoneNumber_Test()
|
||||
{
|
||||
var buyer = CreateModel(Guid.NewGuid().ToString(), "New Fio", "+5-555-555-55-55", 500);
|
||||
CatHasPawsDbContext.InsertBuyerToDatabaseAndReturn(phoneNumber: buyer.PhoneNumber);
|
||||
Assert.That(() => _buyerStorageContract.AddElement(buyer), Throws.TypeOf<ElementExistsException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_UpdElement_Test()
|
||||
{
|
||||
var buyer = CreateModel(Guid.NewGuid().ToString(), "New Fio", "+5-555-555-55-55", 500);
|
||||
CatHasPawsDbContext.InsertBuyerToDatabaseAndReturn(buyer.Id);
|
||||
_buyerStorageContract.UpdElement(buyer);
|
||||
AssertElement(CatHasPawsDbContext.GetBuyerFromDatabase(buyer.Id), buyer);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_UpdElement_WhenNoRecordWithThisId_Test()
|
||||
{
|
||||
Assert.That(() => _buyerStorageContract.UpdElement(CreateModel(Guid.NewGuid().ToString())), Throws.TypeOf<ElementNotFoundException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_UpdElement_WhenHaveRecordWithSamePhoneNumber_Test()
|
||||
{
|
||||
var buyer = CreateModel(Guid.NewGuid().ToString(), "New Fio", "+5-555-555-55-55", 500);
|
||||
CatHasPawsDbContext.InsertBuyerToDatabaseAndReturn(buyer.Id, phoneNumber: "+7-777-777-77-77");
|
||||
CatHasPawsDbContext.InsertBuyerToDatabaseAndReturn(phoneNumber: buyer.PhoneNumber);
|
||||
Assert.That(() => _buyerStorageContract.UpdElement(buyer), Throws.TypeOf<ElementExistsException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_DelElement_Test()
|
||||
{
|
||||
var buyer = CatHasPawsDbContext.InsertBuyerToDatabaseAndReturn();
|
||||
_buyerStorageContract.DelElement(buyer.Id);
|
||||
Assert.That(CatHasPawsDbContext.GetBuyerFromDatabase(buyer.Id), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_DelElement_WhenHaveSalesByThisBuyer_Test()
|
||||
{
|
||||
var buyer = CatHasPawsDbContext.InsertBuyerToDatabaseAndReturn();
|
||||
var worker = CatHasPawsDbContext.InsertWorkerToDatabaseAndReturn();
|
||||
CatHasPawsDbContext.InsertSaleToDatabaseAndReturn(worker.Id, buyer.Id);
|
||||
CatHasPawsDbContext.InsertSaleToDatabaseAndReturn(worker.Id, buyer.Id);
|
||||
var salesBeforeDelete = CatHasPawsDbContext.GetSalesByBuyerId(buyer.Id);
|
||||
_buyerStorageContract.DelElement(buyer.Id);
|
||||
var element = CatHasPawsDbContext.GetBuyerFromDatabase(buyer.Id);
|
||||
var salesAfterDelete = CatHasPawsDbContext.GetSalesByBuyerId(buyer.Id);
|
||||
var salesNoBuyers = CatHasPawsDbContext.GetSalesByBuyerId(null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(element, Is.Null);
|
||||
Assert.That(salesBeforeDelete, Has.Length.EqualTo(2));
|
||||
Assert.That(salesAfterDelete, Is.Empty);
|
||||
Assert.That(salesNoBuyers, Has.Length.EqualTo(2));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_DelElement_WhenNoRecordWithThisId_Test()
|
||||
{
|
||||
Assert.That(() => _buyerStorageContract.DelElement(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
|
||||
}
|
||||
|
||||
private static void AssertElement(BuyerDataModel? actual, Buyer expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.Id, Is.EqualTo(expected.Id));
|
||||
Assert.That(actual.FIO, Is.EqualTo(expected.FIO));
|
||||
Assert.That(actual.PhoneNumber, Is.EqualTo(expected.PhoneNumber));
|
||||
Assert.That(actual.DiscountSize, Is.EqualTo(expected.DiscountSize));
|
||||
});
|
||||
}
|
||||
|
||||
private static BuyerDataModel CreateModel(string id, string fio = "test", string phoneNumber = "+7-777-777-77-77", double discountSize = 10)
|
||||
=> new(id, fio, phoneNumber, discountSize);
|
||||
|
||||
private static void AssertElement(Buyer? actual, BuyerDataModel expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.Id, Is.EqualTo(expected.Id));
|
||||
Assert.That(actual.FIO, Is.EqualTo(expected.FIO));
|
||||
Assert.That(actual.PhoneNumber, Is.EqualTo(expected.PhoneNumber));
|
||||
Assert.That(actual.DiscountSize, Is.EqualTo(expected.DiscountSize));
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
using CatHasPawsContratcs.DataModels;
|
||||
using CatHasPawsContratcs.Exceptions;
|
||||
using CatHasPawsDatabase;
|
||||
using CatHasPawsDatabase.Implementations;
|
||||
using CatHasPawsDatabase.Models;
|
||||
using CatHasPawsTests.Infrastructure;
|
||||
|
||||
namespace CatHasPawsTests.StoragesContracts;
|
||||
|
||||
[TestFixture]
|
||||
internal class ManufacturerStorageContractTests : BaseStorageContractTest
|
||||
{
|
||||
private ManufacturerStorageContract _manufacturerStorageContract;
|
||||
|
||||
[SetUp]
|
||||
public void SetUp()
|
||||
{
|
||||
_manufacturerStorageContract = new ManufacturerStorageContract(CatHasPawsDbContext);
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
CatHasPawsDbContext.RemoveProductsFromDatabase();
|
||||
CatHasPawsDbContext.RemoveManufacturersFromDatabase();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_WhenHaveRecords_Test()
|
||||
{
|
||||
var manufacturer = CatHasPawsDbContext.InsertManufacturerToDatabaseAndReturn(manufacturerName: "name 1");
|
||||
CatHasPawsDbContext.InsertManufacturerToDatabaseAndReturn(manufacturerName: "name 2");
|
||||
CatHasPawsDbContext.InsertManufacturerToDatabaseAndReturn(manufacturerName: "name 3");
|
||||
var list = _manufacturerStorageContract.GetList();
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(3));
|
||||
AssertElement(list.First(x => x.Id == manufacturer.Id), manufacturer);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_WhenNoRecords_Test()
|
||||
{
|
||||
var list = _manufacturerStorageContract.GetList();
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Is.Empty);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenHaveRecord_Test()
|
||||
{
|
||||
var manufacturer = CatHasPawsDbContext.InsertManufacturerToDatabaseAndReturn();
|
||||
AssertElement(_manufacturerStorageContract.GetElementById(manufacturer.Id), manufacturer);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenNoRecord_Test()
|
||||
{
|
||||
CatHasPawsDbContext.InsertManufacturerToDatabaseAndReturn();
|
||||
Assert.That(() => _manufacturerStorageContract.GetElementById(Guid.NewGuid().ToString()), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementByName_WhenHaveRecord_Test()
|
||||
{
|
||||
var manufacturer = CatHasPawsDbContext.InsertManufacturerToDatabaseAndReturn();
|
||||
AssertElement(_manufacturerStorageContract.GetElementByName(manufacturer.ManufacturerName), manufacturer);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementByName_WhenNoRecord_Test()
|
||||
{
|
||||
CatHasPawsDbContext.InsertManufacturerToDatabaseAndReturn();
|
||||
Assert.That(() => _manufacturerStorageContract.GetElementByName("name"), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementByOldName_WhenHaveRecord_Test()
|
||||
{
|
||||
var manufacturer = CatHasPawsDbContext.InsertManufacturerToDatabaseAndReturn();
|
||||
AssertElement(_manufacturerStorageContract.GetElementByOldName(manufacturer.PrevManufacturerName!), manufacturer);
|
||||
AssertElement(_manufacturerStorageContract.GetElementByOldName(manufacturer.PrevPrevManufacturerName!), manufacturer);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementByOldName_WhenNoRecord_Test()
|
||||
{
|
||||
CatHasPawsDbContext.InsertManufacturerToDatabaseAndReturn();
|
||||
Assert.That(() => _manufacturerStorageContract.GetElementByOldName("name"), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_Test()
|
||||
{
|
||||
var manufacturer = CreateModel(Guid.NewGuid().ToString());
|
||||
_manufacturerStorageContract.AddElement(manufacturer);
|
||||
AssertElement(CatHasPawsDbContext.GetManufacturerFromDatabase(manufacturer.Id), manufacturer);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_WhenHaveRecordWithSameId_Test()
|
||||
{
|
||||
var manufacturer = CreateModel(Guid.NewGuid().ToString(), "name unique");
|
||||
CatHasPawsDbContext.InsertManufacturerToDatabaseAndReturn(manufacturer.Id);
|
||||
Assert.That(() => _manufacturerStorageContract.AddElement(manufacturer), Throws.TypeOf<ElementExistsException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_WhenHaveRecordWithSameManufacturerName_Test()
|
||||
{
|
||||
var manufacturer = CreateModel(Guid.NewGuid().ToString(), "name unique");
|
||||
CatHasPawsDbContext.InsertManufacturerToDatabaseAndReturn(manufacturerName: manufacturer.ManufacturerName);
|
||||
Assert.That(() => _manufacturerStorageContract.AddElement(manufacturer), Throws.TypeOf<ElementExistsException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_UpdElement_Test()
|
||||
{
|
||||
var manufacturer = CreateModel(Guid.NewGuid().ToString(), "name new", "test", "prev");
|
||||
CatHasPawsDbContext.InsertManufacturerToDatabaseAndReturn(manufacturer.Id, manufacturerName: manufacturer.PrevManufacturerName!, prevManufacturerName: manufacturer.PrevPrevManufacturerName!);
|
||||
_manufacturerStorageContract.UpdElement(CreateModel(manufacturer.Id, "name new", "some name", "some name"));
|
||||
AssertElement(CatHasPawsDbContext.GetManufacturerFromDatabase(manufacturer.Id), manufacturer);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_UpdElement_WhenNoChangeManufacturerName_Test()
|
||||
{
|
||||
var manufacturer = CreateModel(Guid.NewGuid().ToString(), "name new", "test", "prev");
|
||||
CatHasPawsDbContext.InsertManufacturerToDatabaseAndReturn(manufacturer.Id, manufacturerName: manufacturer.ManufacturerName!, prevManufacturerName: manufacturer.PrevManufacturerName!, prevPrevManufacturerName: manufacturer.PrevPrevManufacturerName!);
|
||||
_manufacturerStorageContract.UpdElement(manufacturer);
|
||||
AssertElement(CatHasPawsDbContext.GetManufacturerFromDatabase(manufacturer.Id), manufacturer);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_UpdElement_WhenNoRecordWithThisId_Test()
|
||||
{
|
||||
Assert.That(() => _manufacturerStorageContract.UpdElement(CreateModel(Guid.NewGuid().ToString())), Throws.TypeOf<ElementNotFoundException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_UpdElement_WhenHaveRecordWithSameManufacturerName_Test()
|
||||
{
|
||||
var manufacturer = CreateModel(Guid.NewGuid().ToString(), "name unique");
|
||||
CatHasPawsDbContext.InsertManufacturerToDatabaseAndReturn(manufacturer.Id, manufacturerName: "some name");
|
||||
CatHasPawsDbContext.InsertManufacturerToDatabaseAndReturn(manufacturerName: manufacturer.ManufacturerName);
|
||||
Assert.That(() => _manufacturerStorageContract.UpdElement(manufacturer), Throws.TypeOf<ElementExistsException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_DelElement_WhenNoProducts_Test()
|
||||
{
|
||||
var manufacturer = CatHasPawsDbContext.InsertManufacturerToDatabaseAndReturn();
|
||||
_manufacturerStorageContract.DelElement(manufacturer.Id);
|
||||
Assert.That(CatHasPawsDbContext.GetManufacturerFromDatabase(manufacturer.Id), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_DelElement_WhenHaveProducts_Test()
|
||||
{
|
||||
var manufacturer = CatHasPawsDbContext.InsertManufacturerToDatabaseAndReturn();
|
||||
CatHasPawsDbContext.InsertProductToDatabaseAndReturn(manufacturer.Id);
|
||||
Assert.That(() => _manufacturerStorageContract.DelElement(manufacturer.Id), Throws.TypeOf<StorageException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_DelElement_WhenNoRecordWithThisId_Test()
|
||||
{
|
||||
Assert.That(() => _manufacturerStorageContract.DelElement(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
|
||||
}
|
||||
|
||||
private static void AssertElement(ManufacturerDataModel? actual, Manufacturer expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.Id, Is.EqualTo(expected.Id));
|
||||
Assert.That(actual.ManufacturerName, Is.EqualTo(expected.ManufacturerName));
|
||||
Assert.That(actual.PrevManufacturerName, Is.EqualTo(expected.PrevManufacturerName));
|
||||
Assert.That(actual.PrevPrevManufacturerName, Is.EqualTo(expected.PrevPrevManufacturerName));
|
||||
});
|
||||
}
|
||||
|
||||
private static ManufacturerDataModel CreateModel(string id, string manufacturerName = "test", string prevManufacturerName = "prev", string prevPrevManufacturerName = "prevPrev")
|
||||
=> new(id, manufacturerName, prevManufacturerName, prevPrevManufacturerName);
|
||||
|
||||
private static void AssertElement(Manufacturer? actual, ManufacturerDataModel expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.Id, Is.EqualTo(expected.Id));
|
||||
Assert.That(actual.ManufacturerName, Is.EqualTo(expected.ManufacturerName));
|
||||
Assert.That(actual.PrevManufacturerName, Is.EqualTo(expected.PrevManufacturerName));
|
||||
Assert.That(actual.PrevPrevManufacturerName, Is.EqualTo(expected.PrevPrevManufacturerName));
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,253 @@
|
||||
using CatHasPawsContratcs.DataModels;
|
||||
using CatHasPawsContratcs.Enums;
|
||||
using CatHasPawsContratcs.Exceptions;
|
||||
using CatHasPawsDatabase.Implementations;
|
||||
using CatHasPawsDatabase.Models;
|
||||
using CatHasPawsTests.Infrastructure;
|
||||
|
||||
namespace CatHasPawsTests.StoragesContracts;
|
||||
|
||||
[TestFixture]
|
||||
internal class PostStorageContractTests : BaseStorageContractTest
|
||||
{
|
||||
private PostStorageContract _postStorageContract;
|
||||
|
||||
[SetUp]
|
||||
public void SetUp()
|
||||
{
|
||||
_postStorageContract = new PostStorageContract(CatHasPawsDbContext);
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
CatHasPawsDbContext.RemovePostsFromDatabase();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_WhenHaveRecords_Test()
|
||||
{
|
||||
var post = CatHasPawsDbContext.InsertPostToDatabaseAndReturn(postName: "name 1");
|
||||
CatHasPawsDbContext.InsertPostToDatabaseAndReturn(postName: "name 2");
|
||||
CatHasPawsDbContext.InsertPostToDatabaseAndReturn(postName: "name 3");
|
||||
var list = _postStorageContract.GetList();
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(3));
|
||||
AssertElement(list.First(x => x.Id == post.PostId), post);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_WhenNoRecords_Test()
|
||||
{
|
||||
var list = _postStorageContract.GetList();
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Is.Empty);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetPostWithHistory_WhenHaveRecords_Test()
|
||||
{
|
||||
var postId = Guid.NewGuid().ToString();
|
||||
CatHasPawsDbContext.InsertPostToDatabaseAndReturn(postName: "name 1", isActual: true);
|
||||
CatHasPawsDbContext.InsertPostToDatabaseAndReturn(postId, "name 2", isActual: true);
|
||||
CatHasPawsDbContext.InsertPostToDatabaseAndReturn(postId, "name 2", isActual: false);
|
||||
var list = _postStorageContract.GetPostWithHistory(postId);
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(2));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetPostWithHistory_WhenNoRecords_Test()
|
||||
{
|
||||
var postId = Guid.NewGuid().ToString();
|
||||
CatHasPawsDbContext.InsertPostToDatabaseAndReturn(postName: "name 1", isActual: true);
|
||||
CatHasPawsDbContext.InsertPostToDatabaseAndReturn(postId, "name 2", isActual: true);
|
||||
CatHasPawsDbContext.InsertPostToDatabaseAndReturn(postId, "name 2", isActual: false);
|
||||
var list = _postStorageContract.GetPostWithHistory(Guid.NewGuid().ToString());
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(0));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenHaveRecord_Test()
|
||||
{
|
||||
var post = CatHasPawsDbContext.InsertPostToDatabaseAndReturn();
|
||||
AssertElement(_postStorageContract.GetElementById(post.PostId), post);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenNoRecord_Test()
|
||||
{
|
||||
CatHasPawsDbContext.InsertPostToDatabaseAndReturn();
|
||||
Assert.That(() => _postStorageContract.GetElementById(Guid.NewGuid().ToString()), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenRecordWasDeleted_Test()
|
||||
{
|
||||
var post = CatHasPawsDbContext.InsertPostToDatabaseAndReturn(isActual: false);
|
||||
Assert.That(() => _postStorageContract.GetElementById(post.PostId), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenTrySearchById_Test()
|
||||
{
|
||||
var post = CatHasPawsDbContext.InsertPostToDatabaseAndReturn();
|
||||
Assert.That(() => _postStorageContract.GetElementById(post.Id), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementByName_WhenHaveRecord_Test()
|
||||
{
|
||||
var post = CatHasPawsDbContext.InsertPostToDatabaseAndReturn();
|
||||
AssertElement(_postStorageContract.GetElementByName(post.PostName), post);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementByName_WhenNoRecord_Test()
|
||||
{
|
||||
CatHasPawsDbContext.InsertPostToDatabaseAndReturn();
|
||||
Assert.That(() => _postStorageContract.GetElementByName("name"), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementByName_WhenRecordWasDeleted_Test()
|
||||
{
|
||||
var post = CatHasPawsDbContext.InsertPostToDatabaseAndReturn(isActual: false);
|
||||
Assert.That(() => _postStorageContract.GetElementById(post.PostName), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_Test()
|
||||
{
|
||||
var post = CreateModel(Guid.NewGuid().ToString());
|
||||
_postStorageContract.AddElement(post);
|
||||
AssertElement(CatHasPawsDbContext.GetPostFromDatabaseByPostId(post.Id), post);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_WhenHaveRecordWithSameName_Test()
|
||||
{
|
||||
var post = CreateModel(Guid.NewGuid().ToString(), "name unique");
|
||||
CatHasPawsDbContext.InsertPostToDatabaseAndReturn(postName: post.PostName, isActual: true);
|
||||
Assert.That(() => _postStorageContract.AddElement(post), Throws.TypeOf<ElementExistsException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_WhenHaveRecordWithSamePostId_Test()
|
||||
{
|
||||
var post = CreateModel(Guid.NewGuid().ToString());
|
||||
CatHasPawsDbContext.InsertPostToDatabaseAndReturn(post.Id, isActual: true);
|
||||
Assert.That(() => _postStorageContract.AddElement(post), Throws.TypeOf<ElementExistsException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_UpdElement_Test()
|
||||
{
|
||||
var post = CreateModel(Guid.NewGuid().ToString());
|
||||
CatHasPawsDbContext.InsertPostToDatabaseAndReturn(post.Id, isActual: true);
|
||||
_postStorageContract.UpdElement(post);
|
||||
var posts = CatHasPawsDbContext.GetPostsFromDatabaseByPostId(post.Id);
|
||||
Assert.That(posts, Is.Not.Null);
|
||||
Assert.That(posts, Has.Length.EqualTo(2));
|
||||
AssertElement(posts[0], CreateModel(post.Id));
|
||||
AssertElement(posts[^1], CreateModel(post.Id));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_UpdElement_WhenNoRecordWithThisId_Test()
|
||||
{
|
||||
Assert.That(() => _postStorageContract.UpdElement(CreateModel(Guid.NewGuid().ToString())), Throws.TypeOf<ElementNotFoundException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_UpdElement_WhenHaveRecordWithSameName_Test()
|
||||
{
|
||||
var post = CreateModel(Guid.NewGuid().ToString(), "New Name");
|
||||
CatHasPawsDbContext.InsertPostToDatabaseAndReturn(post.Id, postName: "name");
|
||||
CatHasPawsDbContext.InsertPostToDatabaseAndReturn(postName: post.PostName);
|
||||
Assert.That(() => _postStorageContract.UpdElement(post), Throws.TypeOf<ElementExistsException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_UpdElement_WhenRecordWasDeleted_Test()
|
||||
{
|
||||
var post = CreateModel(Guid.NewGuid().ToString());
|
||||
CatHasPawsDbContext.InsertPostToDatabaseAndReturn(post.Id, isActual: false);
|
||||
Assert.That(() => _postStorageContract.UpdElement(post), Throws.TypeOf<ElementDeletedException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_DelElement_Test()
|
||||
{
|
||||
var post = CatHasPawsDbContext.InsertPostToDatabaseAndReturn(isActual: true);
|
||||
_postStorageContract.DelElement(post.PostId);
|
||||
Assert.That(CatHasPawsDbContext.GetPostFromDatabaseByPostId(post.PostId), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_DelElement_WhenNoRecordWithThisId_Test()
|
||||
{
|
||||
Assert.That(() => _postStorageContract.DelElement(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_DelElement_WhenRecordWasDeleted_Test()
|
||||
{
|
||||
var post = CatHasPawsDbContext.InsertPostToDatabaseAndReturn(isActual: false);
|
||||
Assert.That(() => _postStorageContract.DelElement(post.PostId), Throws.TypeOf<ElementDeletedException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_ResElement_Test()
|
||||
{
|
||||
var post = CatHasPawsDbContext.InsertPostToDatabaseAndReturn(isActual: false);
|
||||
_postStorageContract.ResElement(post.PostId);
|
||||
var element = CatHasPawsDbContext.GetPostFromDatabaseByPostId(post.PostId);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(element, Is.Not.Null);
|
||||
Assert.That(element!.IsActual);
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_ResElement_WhenNoRecordWithThisId_Test()
|
||||
{
|
||||
Assert.That(() => _postStorageContract.ResElement(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_ResElement_WhenRecordNotWasDeleted_Test()
|
||||
{
|
||||
var post = CatHasPawsDbContext.InsertPostToDatabaseAndReturn(isActual: true);
|
||||
Assert.That(() => _postStorageContract.ResElement(post.PostId), Throws.Nothing);
|
||||
}
|
||||
|
||||
private static void AssertElement(PostDataModel? actual, Post expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.Id, Is.EqualTo(expected.PostId));
|
||||
Assert.That(actual.PostName, Is.EqualTo(expected.PostName));
|
||||
Assert.That(actual.PostType, Is.EqualTo(expected.PostType));
|
||||
Assert.That(actual.Salary, Is.EqualTo(expected.Salary));
|
||||
});
|
||||
}
|
||||
|
||||
private static PostDataModel CreateModel(string postId, string postName = "test", PostType postType = PostType.Assistant, double salary = 10)
|
||||
=> new(postId, postName, postType, salary);
|
||||
|
||||
private static void AssertElement(Post? actual, PostDataModel expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.PostId, Is.EqualTo(expected.Id));
|
||||
Assert.That(actual.PostName, Is.EqualTo(expected.PostName));
|
||||
Assert.That(actual.PostType, Is.EqualTo(expected.PostType));
|
||||
Assert.That(actual.Salary, Is.EqualTo(expected.Salary));
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,325 @@
|
||||
using CatHasPawsContratcs.DataModels;
|
||||
using CatHasPawsContratcs.Enums;
|
||||
using CatHasPawsContratcs.Exceptions;
|
||||
using CatHasPawsDatabase.Implementations;
|
||||
using CatHasPawsDatabase.Models;
|
||||
using CatHasPawsTests.Infrastructure;
|
||||
|
||||
namespace CatHasPawsTests.StoragesContracts;
|
||||
|
||||
[TestFixture]
|
||||
internal class ProductStorageContractTests : BaseStorageContractTest
|
||||
{
|
||||
private ProductStorageContract _productStorageContract;
|
||||
private Manufacturer _manufacturer;
|
||||
|
||||
[SetUp]
|
||||
public void SetUp()
|
||||
{
|
||||
_productStorageContract = new ProductStorageContract(CatHasPawsDbContext);
|
||||
_manufacturer = CatHasPawsDbContext.InsertManufacturerToDatabaseAndReturn();
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
CatHasPawsDbContext.RemoveProductsFromDatabase();
|
||||
CatHasPawsDbContext.RemoveManufacturersFromDatabase();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_WhenHaveRecords_Test()
|
||||
{
|
||||
var product = CatHasPawsDbContext.InsertProductToDatabaseAndReturn(_manufacturer.Id, productName: "name 1");
|
||||
CatHasPawsDbContext.InsertProductToDatabaseAndReturn(_manufacturer.Id, productName: "name 2");
|
||||
CatHasPawsDbContext.InsertProductToDatabaseAndReturn(_manufacturer.Id, productName: "name 3");
|
||||
var list = _productStorageContract.GetList();
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(3));
|
||||
AssertElement(list.First(x => x.Id == product.Id), product);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_WhenNoRecords_Test()
|
||||
{
|
||||
var list = _productStorageContract.GetList();
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Is.Empty);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_OnlyActual_Test()
|
||||
{
|
||||
CatHasPawsDbContext.InsertProductToDatabaseAndReturn(_manufacturer.Id, productName: "name 1", isDeleted: true);
|
||||
CatHasPawsDbContext.InsertProductToDatabaseAndReturn(_manufacturer.Id, productName: "name 2", isDeleted: false);
|
||||
CatHasPawsDbContext.InsertProductToDatabaseAndReturn(_manufacturer.Id, productName: "name 3", isDeleted: false);
|
||||
var list = _productStorageContract.GetList(onlyActive: true);
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(list, Has.Count.EqualTo(2));
|
||||
Assert.That(!list.Any(x => x.IsDeleted));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_IncludeNoActual_Test()
|
||||
{
|
||||
CatHasPawsDbContext.InsertProductToDatabaseAndReturn(_manufacturer.Id, productName: "name 1", isDeleted: true);
|
||||
CatHasPawsDbContext.InsertProductToDatabaseAndReturn(_manufacturer.Id, productName: "name 2", isDeleted: true);
|
||||
CatHasPawsDbContext.InsertProductToDatabaseAndReturn(_manufacturer.Id, productName: "name 3", isDeleted: false);
|
||||
var list = _productStorageContract.GetList(onlyActive: false);
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(list, Has.Count.EqualTo(3));
|
||||
Assert.That(list.Count(x => x.IsDeleted), Is.EqualTo(2));
|
||||
Assert.That(list.Count(x => !x.IsDeleted), Is.EqualTo(1));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_ByManufacturer_Test()
|
||||
{
|
||||
var manufacruer = CatHasPawsDbContext.InsertManufacturerToDatabaseAndReturn(manufacturerName: "name 2");
|
||||
CatHasPawsDbContext.InsertProductToDatabaseAndReturn(_manufacturer.Id, productName: "name 1", isDeleted: true);
|
||||
CatHasPawsDbContext.InsertProductToDatabaseAndReturn(_manufacturer.Id, productName: "name 2", isDeleted: false);
|
||||
CatHasPawsDbContext.InsertProductToDatabaseAndReturn(manufacruer.Id, productName: "name 3", isDeleted: false);
|
||||
var list = _productStorageContract.GetList(manufacturerId: _manufacturer.Id, onlyActive: false);
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(list, Has.Count.EqualTo(2));
|
||||
Assert.That(list.All(x => x.ManufacturerId == _manufacturer.Id));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_ByManufacturerOnlyActual_Test()
|
||||
{
|
||||
var manufacruer = CatHasPawsDbContext.InsertManufacturerToDatabaseAndReturn(manufacturerName: "name 2");
|
||||
CatHasPawsDbContext.InsertProductToDatabaseAndReturn(_manufacturer.Id, productName: "name 1", isDeleted: true);
|
||||
CatHasPawsDbContext.InsertProductToDatabaseAndReturn(_manufacturer.Id, productName: "name 2", isDeleted: false);
|
||||
CatHasPawsDbContext.InsertProductToDatabaseAndReturn(manufacruer.Id, productName: "name 3", isDeleted: false);
|
||||
var list = _productStorageContract.GetList(manufacturerId: _manufacturer.Id, onlyActive: true);
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(list, Has.Count.EqualTo(1));
|
||||
Assert.That(list.All(x => x.ManufacturerId == _manufacturer.Id && !x.IsDeleted));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetHistoryByProductId_WhenHaveRecords_Test()
|
||||
{
|
||||
var product = CatHasPawsDbContext.InsertProductToDatabaseAndReturn(_manufacturer.Id);
|
||||
CatHasPawsDbContext.InsertProductHistoryToDatabaseAndReturn(product.Id, 20, DateTime.UtcNow.AddDays(-1));
|
||||
CatHasPawsDbContext.InsertProductHistoryToDatabaseAndReturn(product.Id, 30, DateTime.UtcNow.AddMinutes(-10));
|
||||
CatHasPawsDbContext.InsertProductHistoryToDatabaseAndReturn(product.Id, 40, DateTime.UtcNow.AddDays(1));
|
||||
var list = _productStorageContract.GetHistoryByProductId(product.Id);
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(3));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetHistoryByProductId_WhenNoRecords_Test()
|
||||
{
|
||||
var product = CatHasPawsDbContext.InsertProductToDatabaseAndReturn(_manufacturer.Id);
|
||||
CatHasPawsDbContext.InsertProductHistoryToDatabaseAndReturn(product.Id, 20, DateTime.UtcNow.AddDays(-1));
|
||||
CatHasPawsDbContext.InsertProductHistoryToDatabaseAndReturn(product.Id, 30, DateTime.UtcNow.AddMinutes(-10));
|
||||
CatHasPawsDbContext.InsertProductHistoryToDatabaseAndReturn(product.Id, 40, DateTime.UtcNow.AddDays(1));
|
||||
var list = _productStorageContract.GetHistoryByProductId(Guid.NewGuid().ToString());
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(0));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenHaveRecord_Test()
|
||||
{
|
||||
var product = CatHasPawsDbContext.InsertProductToDatabaseAndReturn(_manufacturer.Id);
|
||||
AssertElement(_productStorageContract.GetElementById(product.Id), product);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenNoRecord_Test()
|
||||
{
|
||||
CatHasPawsDbContext.InsertProductToDatabaseAndReturn(_manufacturer.Id);
|
||||
Assert.That(() => _productStorageContract.GetElementById(Guid.NewGuid().ToString()), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenRecordWasDeleted_Test()
|
||||
{
|
||||
var product = CatHasPawsDbContext.InsertProductToDatabaseAndReturn(_manufacturer.Id, isDeleted: true);
|
||||
Assert.That(() => _productStorageContract.GetElementById(product.Id), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementByName_WhenHaveRecord_Test()
|
||||
{
|
||||
var product = CatHasPawsDbContext.InsertProductToDatabaseAndReturn(_manufacturer.Id);
|
||||
AssertElement(_productStorageContract.GetElementByName(product.ProductName), product);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementByName_WhenNoRecord_Test()
|
||||
{
|
||||
CatHasPawsDbContext.InsertProductToDatabaseAndReturn(_manufacturer.Id);
|
||||
Assert.That(() => _productStorageContract.GetElementByName("name"), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementByName_WhenRecordWasDeleted_Test()
|
||||
{
|
||||
var product = CatHasPawsDbContext.InsertProductToDatabaseAndReturn(_manufacturer.Id, isDeleted: true);
|
||||
Assert.That(() => _productStorageContract.GetElementById(product.ProductName), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_Test()
|
||||
{
|
||||
var product = CreateModel(Guid.NewGuid().ToString(), _manufacturer.Id, isDeleted: false);
|
||||
_productStorageContract.AddElement(product);
|
||||
AssertElement(CatHasPawsDbContext.GetProductFromDatabaseById(product.Id), product);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_WhenIsDeletedIsTrue_Test()
|
||||
{
|
||||
var product = CreateModel(Guid.NewGuid().ToString(), _manufacturer.Id, isDeleted: true);
|
||||
Assert.That(() => _productStorageContract.AddElement(product), Throws.Nothing);
|
||||
AssertElement(CatHasPawsDbContext.GetProductFromDatabaseById(product.Id), CreateModel(product.Id, _manufacturer.Id, isDeleted: false));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_WhenHaveRecordWithSameId_Test()
|
||||
{
|
||||
var product = CreateModel(Guid.NewGuid().ToString(), _manufacturer.Id);
|
||||
CatHasPawsDbContext.InsertProductToDatabaseAndReturn(_manufacturer.Id, product.Id, productName: "name unique");
|
||||
Assert.That(() => _productStorageContract.AddElement(product), Throws.TypeOf<ElementExistsException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_WhenHaveRecordWithSameName_Test()
|
||||
{
|
||||
var product = CreateModel(Guid.NewGuid().ToString(), _manufacturer.Id, "name unique", isDeleted: false);
|
||||
CatHasPawsDbContext.InsertProductToDatabaseAndReturn(_manufacturer.Id, productName: product.ProductName, isDeleted: false);
|
||||
Assert.That(() => _productStorageContract.AddElement(product), Throws.TypeOf<ElementExistsException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_WhenHaveRecordWithSameNameButOneWasDeleted_Test()
|
||||
{
|
||||
var product = CreateModel(Guid.NewGuid().ToString(), _manufacturer.Id, "name unique", isDeleted: false);
|
||||
CatHasPawsDbContext.InsertProductToDatabaseAndReturn(_manufacturer.Id, productName: product.ProductName, isDeleted: true);
|
||||
Assert.That(() => _productStorageContract.AddElement(product), Throws.Nothing);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_UpdElement_Test()
|
||||
{
|
||||
var product = CreateModel(Guid.NewGuid().ToString(), _manufacturer.Id, isDeleted: false);
|
||||
CatHasPawsDbContext.InsertProductToDatabaseAndReturn(_manufacturer.Id, id: product.Id, isDeleted: false);
|
||||
_productStorageContract.UpdElement(product);
|
||||
AssertElement(CatHasPawsDbContext.GetProductFromDatabaseById(product.Id), product);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_UpdElement_WhenIsDeletedIsTrue_Test()
|
||||
{
|
||||
var product = CreateModel(Guid.NewGuid().ToString(), _manufacturer.Id, isDeleted: true);
|
||||
CatHasPawsDbContext.InsertProductToDatabaseAndReturn(_manufacturer.Id, product.Id, isDeleted: false);
|
||||
_productStorageContract.UpdElement(product);
|
||||
AssertElement(CatHasPawsDbContext.GetProductFromDatabaseById(product.Id), CreateModel(product.Id, _manufacturer.Id, isDeleted: false));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_UpdElement_WhenNoRecordWithThisId_Test()
|
||||
{
|
||||
Assert.That(() => _productStorageContract.UpdElement(CreateModel(Guid.NewGuid().ToString(), _manufacturer.Id)), Throws.TypeOf<ElementNotFoundException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_UpdElement_WhenHaveRecordWithSameName_Test()
|
||||
{
|
||||
var product = CreateModel(Guid.NewGuid().ToString(), _manufacturer.Id, "name unique", isDeleted: false);
|
||||
CatHasPawsDbContext.InsertProductToDatabaseAndReturn(_manufacturer.Id, product.Id, productName: "name");
|
||||
CatHasPawsDbContext.InsertProductToDatabaseAndReturn(_manufacturer.Id, productName: product.ProductName);
|
||||
Assert.That(() => _productStorageContract.UpdElement(product), Throws.TypeOf<ElementExistsException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_UpdElement_WhenHaveRecordWithSameNameButOneWasDeleted_Test()
|
||||
{
|
||||
var product = CreateModel(Guid.NewGuid().ToString(), _manufacturer.Id, "name unique", isDeleted: false);
|
||||
CatHasPawsDbContext.InsertProductToDatabaseAndReturn(_manufacturer.Id, product.Id, productName: "name");
|
||||
CatHasPawsDbContext.InsertProductToDatabaseAndReturn(_manufacturer.Id, productName: product.ProductName, isDeleted: true);
|
||||
Assert.That(() => _productStorageContract.UpdElement(product), Throws.Nothing);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_UpdElement_WhenRecordWasDeleted_Test()
|
||||
{
|
||||
var product = CreateModel(Guid.NewGuid().ToString(), _manufacturer.Id);
|
||||
CatHasPawsDbContext.InsertProductToDatabaseAndReturn(_manufacturer.Id, product.Id, isDeleted: true);
|
||||
Assert.That(() => _productStorageContract.UpdElement(product), Throws.TypeOf<ElementNotFoundException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_DelElement_Test()
|
||||
{
|
||||
var product = CatHasPawsDbContext.InsertProductToDatabaseAndReturn(_manufacturer.Id, isDeleted: false);
|
||||
_productStorageContract.DelElement(product.Id);
|
||||
var element = CatHasPawsDbContext.GetProductFromDatabaseById(product.Id);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(element, Is.Not.Null);
|
||||
Assert.That(element!.IsDeleted);
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_DelElement_WhenNoRecordWithThisId_Test()
|
||||
{
|
||||
Assert.That(() => _productStorageContract.DelElement(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_DelElement_WhenRecordWasDeleted_Test()
|
||||
{
|
||||
var product = CatHasPawsDbContext.InsertProductToDatabaseAndReturn(_manufacturer.Id, isDeleted: true);
|
||||
Assert.That(() => _productStorageContract.DelElement(product.Id), Throws.TypeOf<ElementNotFoundException>());
|
||||
}
|
||||
|
||||
private static void AssertElement(ProductDataModel? actual, Product expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.Id, Is.EqualTo(expected.Id));
|
||||
Assert.That(actual.ManufacturerId, Is.EqualTo(expected.ManufacturerId));
|
||||
Assert.That(actual.ProductName, Is.EqualTo(expected.ProductName));
|
||||
Assert.That(actual.ProductType, Is.EqualTo(expected.ProductType));
|
||||
Assert.That(actual.Price, Is.EqualTo(expected.Price));
|
||||
Assert.That(actual.IsDeleted, Is.EqualTo(expected.IsDeleted));
|
||||
});
|
||||
}
|
||||
|
||||
private static ProductDataModel CreateModel(string id, string manufacturerId, string productName = "test", ProductType productType = ProductType.Feed, double price = 1, bool isDeleted = false)
|
||||
=> new(id, productName, productType, manufacturerId, price, isDeleted);
|
||||
|
||||
private static void AssertElement(Product? actual, ProductDataModel expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.Id, Is.EqualTo(expected.Id));
|
||||
Assert.That(actual.ManufacturerId, Is.EqualTo(expected.ManufacturerId));
|
||||
Assert.That(actual.ProductName, Is.EqualTo(expected.ProductName));
|
||||
Assert.That(actual.ProductType, Is.EqualTo(expected.ProductType));
|
||||
Assert.That(actual.Price, Is.EqualTo(expected.Price));
|
||||
Assert.That(actual.IsDeleted, Is.EqualTo(expected.IsDeleted));
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
using CatHasPawsContratcs.DataModels;
|
||||
using CatHasPawsDatabase;
|
||||
using CatHasPawsDatabase.Implementations;
|
||||
using CatHasPawsDatabase.Models;
|
||||
using CatHasPawsTests.Infrastructure;
|
||||
|
||||
namespace CatHasPawsTests.StoragesContracts;
|
||||
|
||||
[TestFixture]
|
||||
internal class SalaryStorageContractTests : BaseStorageContractTest
|
||||
{
|
||||
private SalaryStorageContract _salaryStorageContract;
|
||||
private Worker _worker;
|
||||
|
||||
[SetUp]
|
||||
public void SetUp()
|
||||
{
|
||||
_salaryStorageContract = new SalaryStorageContract(CatHasPawsDbContext);
|
||||
_worker = CatHasPawsDbContext.InsertWorkerToDatabaseAndReturn();
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
CatHasPawsDbContext.RemoveSalariesFromDatabase();
|
||||
CatHasPawsDbContext.RemoveWorkersFromDatabase();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_WhenHaveRecords_Test()
|
||||
{
|
||||
var salary = CatHasPawsDbContext.InsertSalaryToDatabaseAndReturn(_worker.Id, workerSalary: 100);
|
||||
CatHasPawsDbContext.InsertSalaryToDatabaseAndReturn(_worker.Id);
|
||||
CatHasPawsDbContext.InsertSalaryToDatabaseAndReturn(_worker.Id);
|
||||
var list = _salaryStorageContract.GetList(DateTime.UtcNow.AddDays(-10), DateTime.UtcNow.AddDays(10));
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(3));
|
||||
AssertElement(list.Single(x => x.Salary == salary.WorkerSalary), salary);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_WhenNoRecords_Test()
|
||||
{
|
||||
var list = _salaryStorageContract.GetList(DateTime.UtcNow.AddDays(-10), DateTime.UtcNow.AddDays(10));
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Is.Empty);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_OnlyInDatePeriod_Test()
|
||||
{
|
||||
CatHasPawsDbContext.InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate: DateTime.UtcNow.AddDays(-2));
|
||||
CatHasPawsDbContext.InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate: DateTime.UtcNow.AddDays(-1).AddMinutes(-5));
|
||||
CatHasPawsDbContext.InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate: DateTime.UtcNow.AddDays(-1).AddMinutes(5));
|
||||
CatHasPawsDbContext.InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate: DateTime.UtcNow.AddDays(1).AddMinutes(-5));
|
||||
CatHasPawsDbContext.InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate: DateTime.UtcNow.AddDays(1).AddMinutes(5));
|
||||
CatHasPawsDbContext.InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate: DateTime.UtcNow.AddDays(-2));
|
||||
var list = _salaryStorageContract.GetList(DateTime.UtcNow.AddDays(-1), DateTime.UtcNow.AddDays(1));
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(list, Has.Count.EqualTo(2));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_ByWorker_Test()
|
||||
{
|
||||
var worker = CatHasPawsDbContext.InsertWorkerToDatabaseAndReturn(fio: "name 2");
|
||||
CatHasPawsDbContext.InsertSalaryToDatabaseAndReturn(_worker.Id);
|
||||
CatHasPawsDbContext.InsertSalaryToDatabaseAndReturn(_worker.Id);
|
||||
CatHasPawsDbContext.InsertSalaryToDatabaseAndReturn(worker.Id);
|
||||
var list = _salaryStorageContract.GetList(DateTime.UtcNow.AddDays(-1), DateTime.UtcNow.AddDays(1), _worker.Id);
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(list, Has.Count.EqualTo(2));
|
||||
Assert.That(list.All(x => x.WorkerId == _worker.Id));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_ByWorkerOnlyInDatePeriod_Test()
|
||||
{
|
||||
var worker = CatHasPawsDbContext.InsertWorkerToDatabaseAndReturn(fio: "name 2");
|
||||
CatHasPawsDbContext.InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate: DateTime.UtcNow.AddDays(-2));
|
||||
CatHasPawsDbContext.InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate: DateTime.UtcNow.AddDays(-1).AddMinutes(5));
|
||||
CatHasPawsDbContext.InsertSalaryToDatabaseAndReturn(worker.Id, salaryDate: DateTime.UtcNow.AddDays(-1).AddMinutes(5));
|
||||
CatHasPawsDbContext.InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate: DateTime.UtcNow.AddDays(1).AddMinutes(-5));
|
||||
CatHasPawsDbContext.InsertSalaryToDatabaseAndReturn(worker.Id, salaryDate: DateTime.UtcNow.AddDays(1).AddMinutes(-5));
|
||||
CatHasPawsDbContext.InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate: DateTime.UtcNow.AddDays(-2));
|
||||
var list = _salaryStorageContract.GetList(DateTime.UtcNow.AddDays(-1), DateTime.UtcNow.AddDays(1), _worker.Id);
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(list, Has.Count.EqualTo(2));
|
||||
Assert.That(list.All(x => x.WorkerId == _worker.Id));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_Test()
|
||||
{
|
||||
var salary = CreateModel(_worker.Id);
|
||||
_salaryStorageContract.AddElement(salary);
|
||||
AssertElement(CatHasPawsDbContext.GetSalariesFromDatabaseByWorkerId(_worker.Id).First(), salary);
|
||||
}
|
||||
|
||||
private static void AssertElement(SalaryDataModel? actual, Salary expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.WorkerId, Is.EqualTo(expected.WorkerId));
|
||||
Assert.That(actual.Salary, Is.EqualTo(expected.WorkerSalary));
|
||||
});
|
||||
}
|
||||
|
||||
private static SalaryDataModel CreateModel(string workerId, double workerSalary = 1, DateTime? salaryDate = null)
|
||||
=> new(workerId, salaryDate ?? DateTime.UtcNow, workerSalary);
|
||||
|
||||
private static void AssertElement(Salary? actual, SalaryDataModel expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.WorkerId, Is.EqualTo(expected.WorkerId));
|
||||
Assert.That(actual.WorkerSalary, Is.EqualTo(expected.Salary));
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,263 @@
|
||||
using CatHasPawsContratcs.DataModels;
|
||||
using CatHasPawsContratcs.Enums;
|
||||
using CatHasPawsContratcs.Exceptions;
|
||||
using CatHasPawsDatabase.Implementations;
|
||||
using CatHasPawsDatabase.Models;
|
||||
using CatHasPawsTests.Infrastructure;
|
||||
|
||||
namespace CatHasPawsTests.StoragesContracts;
|
||||
|
||||
[TestFixture]
|
||||
internal class SaleStorageContractTests : BaseStorageContractTest
|
||||
{
|
||||
private SaleStorageContract _saletStorageContract;
|
||||
private Buyer _buyer;
|
||||
private Worker _worker;
|
||||
private Manufacturer _manufacturer;
|
||||
private Product _product;
|
||||
|
||||
[SetUp]
|
||||
public void SetUp()
|
||||
{
|
||||
_saletStorageContract = new SaleStorageContract(CatHasPawsDbContext);
|
||||
_manufacturer = CatHasPawsDbContext.InsertManufacturerToDatabaseAndReturn();
|
||||
_buyer = CatHasPawsDbContext.InsertBuyerToDatabaseAndReturn();
|
||||
_worker = CatHasPawsDbContext.InsertWorkerToDatabaseAndReturn();
|
||||
_product = CatHasPawsDbContext.InsertProductToDatabaseAndReturn(_manufacturer.Id);
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
CatHasPawsDbContext.RemoveSalesFromDatabase();
|
||||
CatHasPawsDbContext.RemoveWorkersFromDatabase();
|
||||
CatHasPawsDbContext.RemoveBuyersFromDatabase();
|
||||
CatHasPawsDbContext.RemoveProductsFromDatabase();
|
||||
CatHasPawsDbContext.RemoveManufacturersFromDatabase();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_WhenHaveRecords_Test()
|
||||
{
|
||||
var sale = CatHasPawsDbContext.InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, products: [(_product.Id, 1, 1.2)]);
|
||||
CatHasPawsDbContext.InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, products: [(_product.Id, 5, 1.2)]);
|
||||
CatHasPawsDbContext.InsertSaleToDatabaseAndReturn(_worker.Id, null, products: [(_product.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);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_WhenNoRecords_Test()
|
||||
{
|
||||
var list = _saletStorageContract.GetList();
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Is.Empty);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_ByPeriod_Test()
|
||||
{
|
||||
CatHasPawsDbContext.InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(-3), products: [(_product.Id, 1, 1.2)]);
|
||||
CatHasPawsDbContext.InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(3), products: [(_product.Id, 1, 1.2)]);
|
||||
CatHasPawsDbContext.InsertSaleToDatabaseAndReturn(_worker.Id, null, saleDate: DateTime.UtcNow.AddDays(1).AddMinutes(-3), products: [(_product.Id, 1, 1.2)]);
|
||||
CatHasPawsDbContext.InsertSaleToDatabaseAndReturn(_worker.Id, null, saleDate: DateTime.UtcNow.AddDays(1).AddMinutes(3), products: [(_product.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));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_ByWorkerId_Test()
|
||||
{
|
||||
var worker = CatHasPawsDbContext.InsertWorkerToDatabaseAndReturn(fio: "Other worker");
|
||||
CatHasPawsDbContext.InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, products: [(_product.Id, 1, 1.2)]);
|
||||
CatHasPawsDbContext.InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, products: [(_product.Id, 1, 1.2)]);
|
||||
CatHasPawsDbContext.InsertSaleToDatabaseAndReturn(worker.Id, null, products: [(_product.Id, 1, 1.2)]);
|
||||
var list = _saletStorageContract.GetList(workerId: _worker.Id);
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(2));
|
||||
Assert.That(list.All(x => x.WorkerId == _worker.Id));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_ByBuyerId_Test()
|
||||
{
|
||||
var buyer = CatHasPawsDbContext.InsertBuyerToDatabaseAndReturn(fio: "Other fio", phoneNumber: "+8-888-888-88-88");
|
||||
CatHasPawsDbContext.InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, products: [(_product.Id, 1, 1.2)]);
|
||||
CatHasPawsDbContext.InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, products: [(_product.Id, 1, 1.2)]);
|
||||
CatHasPawsDbContext.InsertSaleToDatabaseAndReturn(_worker.Id, buyer.Id, products: [(_product.Id, 1, 1.2)]);
|
||||
CatHasPawsDbContext.InsertSaleToDatabaseAndReturn(_worker.Id, null, products: [(_product.Id, 1, 1.2)]);
|
||||
var list = _saletStorageContract.GetList(buyerId: _buyer.Id);
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(2));
|
||||
Assert.That(list.All(x => x.BuyerId == _buyer.Id));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_ByProductId_Test()
|
||||
{
|
||||
var product = CatHasPawsDbContext.InsertProductToDatabaseAndReturn(_manufacturer.Id, productName: "Other name");
|
||||
CatHasPawsDbContext.InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, products: [(_product.Id, 5, 1.2)]);
|
||||
CatHasPawsDbContext.InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, products: [(_product.Id, 1, 1.2), (product.Id, 4, 1.2)]);
|
||||
CatHasPawsDbContext.InsertSaleToDatabaseAndReturn(_worker.Id, null, products: [(product.Id, 1, 1.2)]);
|
||||
CatHasPawsDbContext.InsertSaleToDatabaseAndReturn(_worker.Id, null, products: [(product.Id, 1, 1.2), (_product.Id, 1, 1.2)]);
|
||||
var list = _saletStorageContract.GetList(productId: _product.Id);
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(3));
|
||||
Assert.That(list.All(x => x.Products!.Any(y => y.ProductId == _product.Id)));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_ByAllParameters_Test()
|
||||
{
|
||||
var worker = CatHasPawsDbContext.InsertWorkerToDatabaseAndReturn(fio: "Other worker");
|
||||
var buyer = CatHasPawsDbContext.InsertBuyerToDatabaseAndReturn(fio: "Other fio", phoneNumber: "+8-888-888-88-88");
|
||||
var product = CatHasPawsDbContext.InsertProductToDatabaseAndReturn(_manufacturer.Id, productName: "Other name");
|
||||
CatHasPawsDbContext.InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(-3), products: [(_product.Id, 1, 1.2)]);
|
||||
CatHasPawsDbContext.InsertSaleToDatabaseAndReturn(worker.Id, null, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(3), products: [(_product.Id, 1, 1.2)]);
|
||||
CatHasPawsDbContext.InsertSaleToDatabaseAndReturn(worker.Id, _buyer.Id, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(3), products: [(_product.Id, 1, 1.2)]);
|
||||
CatHasPawsDbContext.InsertSaleToDatabaseAndReturn(worker.Id, _buyer.Id, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(3), products: [(product.Id, 1, 1.2)]);
|
||||
CatHasPawsDbContext.InsertSaleToDatabaseAndReturn(_worker.Id, buyer.Id, saleDate: DateTime.UtcNow.AddDays(1).AddMinutes(-3), products: [(_product.Id, 1, 1.2)]);
|
||||
CatHasPawsDbContext.InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, saleDate: DateTime.UtcNow.AddDays(1).AddMinutes(-3), products: [(product.Id, 1, 1.2)]);
|
||||
CatHasPawsDbContext.InsertSaleToDatabaseAndReturn(worker.Id, null, saleDate: DateTime.UtcNow.AddDays(1).AddMinutes(-3), products: [(_product.Id, 1, 1.2)]);
|
||||
var list = _saletStorageContract.GetList(startDate: DateTime.UtcNow.AddDays(-1), endDate: DateTime.UtcNow.AddDays(1), workerId: _worker.Id, buyerId: _buyer.Id, productId: product.Id);
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(1));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenHaveRecord_Test()
|
||||
{
|
||||
var sale = CatHasPawsDbContext.InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, products: [(_product.Id, 1, 1.2)]);
|
||||
AssertElement(_saletStorageContract.GetElementById(sale.Id), sale);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenNoRecord_Test()
|
||||
{
|
||||
CatHasPawsDbContext.InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, products: [(_product.Id, 1, 1.2)]);
|
||||
Assert.That(() => _saletStorageContract.GetElementById(Guid.NewGuid().ToString()), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenRecordHasCanceled_Test()
|
||||
{
|
||||
var sale = CatHasPawsDbContext.InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, products: [(_product.Id, 1, 1.2)], isCancel: true);
|
||||
AssertElement(_saletStorageContract.GetElementById(sale.Id), sale);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_Test()
|
||||
{
|
||||
var sale = CreateModel(Guid.NewGuid().ToString(), _worker.Id, _buyer.Id, DiscountType.RegularCustomer, false, [_product.Id]);
|
||||
_saletStorageContract.AddElement(sale);
|
||||
AssertElement(CatHasPawsDbContext.GetSaleFromDatabaseById(sale.Id), sale);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_WhenIsDeletedIsTrue_Test()
|
||||
{
|
||||
var sale = CreateModel(Guid.NewGuid().ToString(), _worker.Id, _buyer.Id, DiscountType.RegularCustomer, true, [_product.Id]);
|
||||
Assert.That(() => _saletStorageContract.AddElement(sale), Throws.Nothing);
|
||||
AssertElement(CatHasPawsDbContext.GetSaleFromDatabaseById(sale.Id), CreateModel(sale.Id, _worker.Id, _buyer.Id, DiscountType.RegularCustomer, false, [_product.Id]));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_DelElement_Test()
|
||||
{
|
||||
var sale = CatHasPawsDbContext.InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, products: [(_product.Id, 1, 1.2)], isCancel: false);
|
||||
_saletStorageContract.DelElement(sale.Id);
|
||||
var element = CatHasPawsDbContext.GetSaleFromDatabaseById(sale.Id);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(element, Is.Not.Null);
|
||||
Assert.That(element!.IsCancel);
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_DelElement_WhenNoRecordWithThisId_Test()
|
||||
{
|
||||
Assert.That(() => _saletStorageContract.DelElement(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_DelElement_WhenRecordWasCanceled_Test()
|
||||
{
|
||||
var sale = CatHasPawsDbContext.InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, products: [(_product.Id, 1, 1.2)], isCancel: true);
|
||||
Assert.That(() => _saletStorageContract.DelElement(sale.Id), Throws.TypeOf<ElementDeletedException>());
|
||||
}
|
||||
|
||||
private static void AssertElement(SaleDataModel? actual, Sale expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.Id, Is.EqualTo(expected.Id));
|
||||
Assert.That(actual.WorkerId, Is.EqualTo(expected.WorkerId));
|
||||
Assert.That(actual.BuyerId, Is.EqualTo(expected.BuyerId));
|
||||
Assert.That(actual.DiscountType, Is.EqualTo(expected.DiscountType));
|
||||
Assert.That(actual.Discount, Is.EqualTo(expected.Discount));
|
||||
Assert.That(actual.IsCancel, Is.EqualTo(expected.IsCancel));
|
||||
});
|
||||
|
||||
if (expected.SaleProducts is not null)
|
||||
{
|
||||
Assert.That(actual.Products, Is.Not.Null);
|
||||
Assert.That(actual.Products, Has.Count.EqualTo(expected.SaleProducts.Count));
|
||||
for (int i = 0; i < actual.Products.Count; ++i)
|
||||
{
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.Products[i].ProductId, Is.EqualTo(expected.SaleProducts[i].ProductId));
|
||||
Assert.That(actual.Products[i].Count, Is.EqualTo(expected.SaleProducts[i].Count));
|
||||
});
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
Assert.That(actual.Products, Is.Null);
|
||||
}
|
||||
}
|
||||
|
||||
private static SaleDataModel CreateModel(string id, string workerId, string? buyerId, DiscountType discountType, bool isCancel, List<string> productIds)
|
||||
{
|
||||
var products = productIds.Select(x => new SaleProductDataModel(id, x, 1, 1.1)).ToList();
|
||||
return new(id, workerId, buyerId, discountType, isCancel, products);
|
||||
}
|
||||
|
||||
private static void AssertElement(Sale? actual, SaleDataModel expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.Id, Is.EqualTo(expected.Id));
|
||||
Assert.That(actual.WorkerId, Is.EqualTo(expected.WorkerId));
|
||||
Assert.That(actual.BuyerId, Is.EqualTo(expected.BuyerId));
|
||||
Assert.That(actual.DiscountType, Is.EqualTo(expected.DiscountType));
|
||||
Assert.That(actual.Discount, Is.EqualTo(expected.Discount));
|
||||
Assert.That(actual.IsCancel, Is.EqualTo(expected.IsCancel));
|
||||
});
|
||||
|
||||
if (expected.Products is not null)
|
||||
{
|
||||
Assert.That(actual.SaleProducts, Is.Not.Null);
|
||||
Assert.That(actual.SaleProducts, Has.Count.EqualTo(expected.Products.Count));
|
||||
for (int i = 0; i < actual.SaleProducts.Count; ++i)
|
||||
{
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.SaleProducts[i].ProductId, Is.EqualTo(expected.Products[i].ProductId));
|
||||
Assert.That(actual.SaleProducts[i].Count, Is.EqualTo(expected.Products[i].Count));
|
||||
Assert.That(actual.SaleProducts[i].Price, Is.EqualTo(expected.Products[i].Price));
|
||||
});
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
Assert.That(actual.SaleProducts, Is.Null);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,215 @@
|
||||
using CatHasPawsContratcs.DataModels;
|
||||
using CatHasPawsContratcs.Exceptions;
|
||||
using CatHasPawsDatabase.Implementations;
|
||||
using CatHasPawsDatabase.Models;
|
||||
using CatHasPawsTests.Infrastructure;
|
||||
|
||||
namespace CatHasPawsTests.StoragesContracts;
|
||||
|
||||
[TestFixture]
|
||||
internal class WorkerStorageContractTests : BaseStorageContractTest
|
||||
{
|
||||
private WorkerStorageContract _workerStorageContract;
|
||||
|
||||
[SetUp]
|
||||
public void SetUp()
|
||||
{
|
||||
_workerStorageContract = new WorkerStorageContract(CatHasPawsDbContext);
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
CatHasPawsDbContext.RemoveWorkersFromDatabase();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_WhenHaveRecords_Test()
|
||||
{
|
||||
var worker = CatHasPawsDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 1");
|
||||
CatHasPawsDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 2");
|
||||
CatHasPawsDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 3");
|
||||
var list = _workerStorageContract.GetList();
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(3));
|
||||
AssertElement(list.First(x => x.FIO == worker.FIO), worker);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_WhenNoRecords_Test()
|
||||
{
|
||||
var list = _workerStorageContract.GetList();
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Is.Empty);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_ByPostId_Test()
|
||||
{
|
||||
var postId = Guid.NewGuid().ToString();
|
||||
CatHasPawsDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 1", postId: postId);
|
||||
CatHasPawsDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 2", postId: postId);
|
||||
CatHasPawsDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 3");
|
||||
var list = _workerStorageContract.GetList(postId: postId);
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(2));
|
||||
Assert.That(list.All(x => x.PostId == postId));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_ByBirthDate_Test()
|
||||
{
|
||||
CatHasPawsDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 1", birthDate: DateTime.UtcNow.AddYears(-25));
|
||||
CatHasPawsDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 2", birthDate: DateTime.UtcNow.AddYears(-21));
|
||||
CatHasPawsDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 3", birthDate: DateTime.UtcNow.AddYears(-20));
|
||||
CatHasPawsDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 4", birthDate: DateTime.UtcNow.AddYears(-19));
|
||||
var list = _workerStorageContract.GetList(fromBirthDate: DateTime.UtcNow.AddYears(-21).AddMinutes(-1), toBirthDate: DateTime.UtcNow.AddYears(-20).AddMinutes(1));
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(2));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_ByEmploymentDate_Test()
|
||||
{
|
||||
CatHasPawsDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 1", employmentDate: DateTime.UtcNow.AddDays(-2));
|
||||
CatHasPawsDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 2", employmentDate: DateTime.UtcNow.AddDays(-1));
|
||||
CatHasPawsDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 3", employmentDate: DateTime.UtcNow.AddDays(1));
|
||||
CatHasPawsDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 4", employmentDate: DateTime.UtcNow.AddDays(2));
|
||||
var list = _workerStorageContract.GetList(fromEmploymentDate: DateTime.UtcNow.AddDays(-1).AddMinutes(-1), toEmploymentDate: DateTime.UtcNow.AddDays(1).AddMinutes(1));
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(2));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_ByAllParameters_Test()
|
||||
{
|
||||
var postId = Guid.NewGuid().ToString();
|
||||
CatHasPawsDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 1", postId: postId, birthDate: DateTime.UtcNow.AddYears(-25), employmentDate: DateTime.UtcNow.AddDays(-2));
|
||||
CatHasPawsDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 2", postId: postId, birthDate: DateTime.UtcNow.AddYears(-22), employmentDate: DateTime.UtcNow.AddDays(-1));
|
||||
CatHasPawsDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 3", postId: postId, birthDate: DateTime.UtcNow.AddYears(-21), employmentDate: DateTime.UtcNow.AddDays(-1));
|
||||
CatHasPawsDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 4", birthDate: DateTime.UtcNow.AddYears(-20), employmentDate: DateTime.UtcNow.AddDays(1));
|
||||
var list = _workerStorageContract.GetList(postId: postId, fromBirthDate: DateTime.UtcNow.AddYears(-21).AddMinutes(-1), toBirthDate: DateTime.UtcNow.AddYears(-20).AddMinutes(1), fromEmploymentDate: DateTime.UtcNow.AddDays(-1).AddMinutes(-1), toEmploymentDate: DateTime.UtcNow.AddDays(1).AddMinutes(1));
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(1));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenHaveRecord_Test()
|
||||
{
|
||||
var worker = CatHasPawsDbContext.InsertWorkerToDatabaseAndReturn();
|
||||
AssertElement(_workerStorageContract.GetElementById(worker.Id), worker);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenNoRecord_Test()
|
||||
{
|
||||
Assert.That(() => _workerStorageContract.GetElementById(Guid.NewGuid().ToString()), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementByFIO_WhenHaveRecord_Test()
|
||||
{
|
||||
var worker = CatHasPawsDbContext.InsertWorkerToDatabaseAndReturn();
|
||||
AssertElement(_workerStorageContract.GetElementByFIO(worker.FIO), worker);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementByFIO_WhenNoRecord_Test()
|
||||
{
|
||||
Assert.That(() => _workerStorageContract.GetElementByFIO("New Fio"), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_Test()
|
||||
{
|
||||
var worker = CreateModel(Guid.NewGuid().ToString());
|
||||
_workerStorageContract.AddElement(worker);
|
||||
AssertElement(CatHasPawsDbContext.GetWorkerFromDatabaseById(worker.Id), worker);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_WhenHaveRecordWithSameId_Test()
|
||||
{
|
||||
var worker = CreateModel(Guid.NewGuid().ToString());
|
||||
CatHasPawsDbContext.InsertWorkerToDatabaseAndReturn(worker.Id);
|
||||
Assert.That(() => _workerStorageContract.AddElement(worker), Throws.TypeOf<ElementExistsException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_UpdElement_Test()
|
||||
{
|
||||
var worker = CreateModel(Guid.NewGuid().ToString(), "New Fio");
|
||||
CatHasPawsDbContext.InsertWorkerToDatabaseAndReturn(worker.Id);
|
||||
_workerStorageContract.UpdElement(worker);
|
||||
AssertElement(CatHasPawsDbContext.GetWorkerFromDatabaseById(worker.Id), worker);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_UpdElement_WhenNoRecordWithThisId_Test()
|
||||
{
|
||||
Assert.That(() => _workerStorageContract.UpdElement(CreateModel(Guid.NewGuid().ToString())), Throws.TypeOf<ElementNotFoundException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_UpdElement_WhenNoRecordWasDeleted_Test()
|
||||
{
|
||||
var worker = CreateModel(Guid.NewGuid().ToString());
|
||||
CatHasPawsDbContext.InsertWorkerToDatabaseAndReturn(worker.Id, isDeleted: true);
|
||||
Assert.That(() => _workerStorageContract.UpdElement(worker), Throws.TypeOf<ElementNotFoundException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_DelElement_Test()
|
||||
{
|
||||
var worker = CatHasPawsDbContext.InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
_workerStorageContract.DelElement(worker.Id);
|
||||
var element = CatHasPawsDbContext.GetWorkerFromDatabaseById(worker.Id);
|
||||
Assert.That(element, Is.Not.Null);
|
||||
Assert.That(element.IsDeleted);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_DelElement_WhenNoRecordWithThisId_Test()
|
||||
{
|
||||
Assert.That(() => _workerStorageContract.DelElement(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_DelElement_WhenNoRecordWasDeleted_Test()
|
||||
{
|
||||
var worker = CreateModel(Guid.NewGuid().ToString());
|
||||
CatHasPawsDbContext.InsertWorkerToDatabaseAndReturn(worker.Id, isDeleted: true);
|
||||
Assert.That(() => _workerStorageContract.DelElement(worker.Id), Throws.TypeOf<ElementNotFoundException>());
|
||||
}
|
||||
|
||||
private static void AssertElement(WorkerDataModel? actual, Worker expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.Id, Is.EqualTo(expected.Id));
|
||||
Assert.That(actual.PostId, Is.EqualTo(expected.PostId));
|
||||
Assert.That(actual.FIO, Is.EqualTo(expected.FIO));
|
||||
Assert.That(actual.BirthDate, Is.EqualTo(expected.BirthDate));
|
||||
Assert.That(actual.EmploymentDate, Is.EqualTo(expected.EmploymentDate));
|
||||
Assert.That(actual.IsDeleted, Is.EqualTo(expected.IsDeleted));
|
||||
});
|
||||
}
|
||||
|
||||
private static WorkerDataModel CreateModel(string id, string fio = "fio", string? postId = null, DateTime? birthDate = null, DateTime? employmentDate = null, bool isDeleted = false) =>
|
||||
new(id, fio, postId ?? Guid.NewGuid().ToString(), birthDate ?? DateTime.UtcNow.AddYears(-20), employmentDate ?? DateTime.UtcNow, isDeleted);
|
||||
|
||||
private static void AssertElement(Worker? actual, WorkerDataModel expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.Id, Is.EqualTo(expected.Id));
|
||||
Assert.That(actual.PostId, Is.EqualTo(expected.PostId));
|
||||
Assert.That(actual.FIO, Is.EqualTo(expected.FIO));
|
||||
Assert.That(actual.BirthDate, Is.EqualTo(expected.BirthDate));
|
||||
Assert.That(actual.EmploymentDate, Is.EqualTo(expected.EmploymentDate));
|
||||
Assert.That(actual.IsDeleted, Is.EqualTo(expected.IsDeleted));
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
using CatHasPawsDatabase;
|
||||
using CatHasPawsTests.Infrastructure;
|
||||
using Microsoft.AspNetCore.Mvc.Testing;
|
||||
using Microsoft.AspNetCore.TestHost;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Serilog;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace CatHasPawsTests.WebApiControllersTests;
|
||||
|
||||
internal class BaseWebApiControllerTest
|
||||
{
|
||||
private WebApplicationFactory<Program> _webApplication;
|
||||
|
||||
protected HttpClient HttpClient { get; private set; }
|
||||
|
||||
protected CatHasPawsDbContext CatHasPawsDbContext { 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}");
|
||||
|
||||
CatHasPawsDbContext = _webApplication.Services.GetRequiredService<CatHasPawsDbContext>();
|
||||
CatHasPawsDbContext.Database.EnsureDeleted();
|
||||
CatHasPawsDbContext.Database.EnsureCreated();
|
||||
}
|
||||
|
||||
[OneTimeTearDown]
|
||||
public void OneTimeTearDown()
|
||||
{
|
||||
CatHasPawsDbContext?.Database.EnsureDeleted();
|
||||
CatHasPawsDbContext?.Dispose();
|
||||
HttpClient?.Dispose();
|
||||
_webApplication?.Dispose();
|
||||
}
|
||||
|
||||
protected static async Task<T?> GetModelFromResponseAsync<T>(HttpResponseMessage response) =>
|
||||
JsonSerializer.Deserialize<T>(await response.Content.ReadAsStringAsync(), JsonSerializerOptions);
|
||||
|
||||
protected static StringContent MakeContent(object model) =>
|
||||
new(JsonSerializer.Serialize(model), Encoding.UTF8, "application/json");
|
||||
}
|
||||
@@ -0,0 +1,371 @@
|
||||
using CatHasPawsContratcs.BindingModels;
|
||||
using CatHasPawsContratcs.ViewModels;
|
||||
using CatHasPawsDatabase;
|
||||
using CatHasPawsDatabase.Models;
|
||||
using CatHasPawsTests.Infrastructure;
|
||||
using System.Net;
|
||||
|
||||
namespace CatHasPawsTests.WebApiControllersTests;
|
||||
|
||||
[TestFixture]
|
||||
internal class BuyerControllerTests : BaseWebApiControllerTest
|
||||
{
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
CatHasPawsDbContext.RemoveSalesFromDatabase();
|
||||
CatHasPawsDbContext.RemoveWorkersFromDatabase();
|
||||
CatHasPawsDbContext.RemoveBuyersFromDatabase();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_WhenHaveRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var buyer = CatHasPawsDbContext.InsertBuyerToDatabaseAndReturn(phoneNumber: "+5-555-555-55-55");
|
||||
CatHasPawsDbContext.InsertBuyerToDatabaseAndReturn(phoneNumber: "+6-666-666-66-66");
|
||||
CatHasPawsDbContext.InsertBuyerToDatabaseAndReturn(phoneNumber: "+7-777-777-77-77");
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync("/api/buyers");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<BuyerViewModel>>(response);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(3));
|
||||
});
|
||||
AssertElement(data.First(x => x.Id == buyer.Id), buyer);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_WhenNoRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync("/api/buyers");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<BuyerViewModel>>(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 buyer = CatHasPawsDbContext.InsertBuyerToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/buyers/{buyer.Id}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
AssertElement(await GetModelFromResponseAsync<BuyerViewModel>(response), buyer);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ById_WhenNoRecord_ShouldNotFound_Test()
|
||||
{
|
||||
//Arrange
|
||||
CatHasPawsDbContext.InsertBuyerToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/buyers/{Guid.NewGuid()}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ByFIO_WhenHaveRecord_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var buyer = CatHasPawsDbContext.InsertBuyerToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/buyers/{buyer.FIO}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
AssertElement(await GetModelFromResponseAsync<BuyerViewModel>(response), buyer);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ByFIO_WhenNoRecord_ShouldNotFound_Test()
|
||||
{
|
||||
//Arrange
|
||||
CatHasPawsDbContext.InsertBuyerToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/buyers/New%20Fio");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ByPhoneNumber_WhenHaveRecord_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var buyer = CatHasPawsDbContext.InsertBuyerToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/buyers/{buyer.PhoneNumber}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
AssertElement(await GetModelFromResponseAsync<BuyerViewModel>(response), buyer);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ByPhoneNumber_WhenNoRecord_ShouldNotFound_Test()
|
||||
{
|
||||
//Arrange
|
||||
CatHasPawsDbContext.InsertBuyerToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/buyers/+8-888-888-88-88");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
CatHasPawsDbContext.InsertBuyerToDatabaseAndReturn();
|
||||
var buyerModel = CreateBindingModel();
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/buyers", MakeContent(buyerModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
AssertElement(CatHasPawsDbContext.GetBuyerFromDatabase(buyerModel.Id!), buyerModel);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenHaveRecordWithSameId_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var buyerModel = CreateBindingModel();
|
||||
CatHasPawsDbContext.InsertBuyerToDatabaseAndReturn(buyerModel.Id);
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/buyers", MakeContent(buyerModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenHaveRecordWithSamePhoneNumber_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var buyerModel = CreateBindingModel();
|
||||
CatHasPawsDbContext.InsertBuyerToDatabaseAndReturn(phoneNumber: buyerModel.PhoneNumber!);
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/buyers", MakeContent(buyerModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenDataIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var buyerModelWithIdIncorrect = new BuyerBindingModel { Id = "Id", FIO = "fio", PhoneNumber = "+7-111-111-11-11", DiscountSize = 10 };
|
||||
var buyerModelWithFioIncorrect = new BuyerBindingModel { Id = Guid.NewGuid().ToString(), FIO = string.Empty, PhoneNumber = "+7-111-111-11-11", DiscountSize = 10 };
|
||||
var buyerModelWithPhoneNumberIncorrect = new BuyerBindingModel { Id = Guid.NewGuid().ToString(), FIO = "fio", PhoneNumber = "71", DiscountSize = 10 };
|
||||
//Act
|
||||
var responseWithIdIncorrect = await HttpClient.PostAsync($"/api/buyers", MakeContent(buyerModelWithIdIncorrect));
|
||||
var responseWithFioIncorrect = await HttpClient.PostAsync($"/api/buyers", MakeContent(buyerModelWithFioIncorrect));
|
||||
var responseWithPhoneNumberIncorrect = await HttpClient.PostAsync($"/api/buyers", MakeContent(buyerModelWithPhoneNumberIncorrect));
|
||||
//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/buyers", 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/buyers", MakeContent(new { Data = "test", Position = 10 }));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var buyerModel = CreateBindingModel(fio: "new fio");
|
||||
CatHasPawsDbContext.InsertBuyerToDatabaseAndReturn(buyerModel.Id);
|
||||
//Act
|
||||
var response = await HttpClient.PutAsync($"/api/buyers", MakeContent(buyerModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
CatHasPawsDbContext.ChangeTracker.Clear();
|
||||
AssertElement(CatHasPawsDbContext.GetBuyerFromDatabase(buyerModel.Id!), buyerModel);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WhenNoFoundRecord_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var buyerModel = CreateBindingModel(fio: "new fio");
|
||||
CatHasPawsDbContext.InsertBuyerToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.PutAsync($"/api/buyers", MakeContent(buyerModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WhenHaveRecordWithSamePhoneNumber_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var buyerModel = CreateBindingModel(fio: "new fio");
|
||||
CatHasPawsDbContext.InsertBuyerToDatabaseAndReturn(buyerModel.Id);
|
||||
CatHasPawsDbContext.InsertBuyerToDatabaseAndReturn(phoneNumber: buyerModel.PhoneNumber!);
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/buyers", MakeContent(buyerModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WhenDataIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var buyerModelWithIdIncorrect = new BuyerBindingModel { Id = "Id", FIO = "fio", PhoneNumber = "+7-111-111-11-11", DiscountSize = 10 };
|
||||
var buyerModelWithFioIncorrect = new BuyerBindingModel { Id = Guid.NewGuid().ToString(), FIO = string.Empty, PhoneNumber = "+7-111-111-11-11", DiscountSize = 10 };
|
||||
var buyerModelWithPhoneNumberIncorrect = new BuyerBindingModel { Id = Guid.NewGuid().ToString(), FIO = "fio", PhoneNumber = "71", DiscountSize = 10 };
|
||||
//Act
|
||||
var responseWithIdIncorrect = await HttpClient.PutAsync($"/api/buyers", MakeContent(buyerModelWithIdIncorrect));
|
||||
var responseWithFioIncorrect = await HttpClient.PutAsync($"/api/buyers", MakeContent(buyerModelWithFioIncorrect));
|
||||
var responseWithPhoneNumberIncorrect = await HttpClient.PutAsync($"/api/buyers", MakeContent(buyerModelWithPhoneNumberIncorrect));
|
||||
//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/buyers", 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/buyers", MakeContent(new { Data = "test", Position = 10 }));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Delete_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var buyerId = Guid.NewGuid().ToString();
|
||||
CatHasPawsDbContext.InsertBuyerToDatabaseAndReturn(buyerId);
|
||||
//Act
|
||||
var response = await HttpClient.DeleteAsync($"/api/buyers/{buyerId}");
|
||||
//Assert
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
Assert.That(CatHasPawsDbContext.GetBuyerFromDatabase(buyerId), Is.Null);
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Delete_WhenHaveSalesByThisBuyer_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var buyer = CatHasPawsDbContext.InsertBuyerToDatabaseAndReturn();
|
||||
var worker = CatHasPawsDbContext.InsertWorkerToDatabaseAndReturn();
|
||||
CatHasPawsDbContext.InsertSaleToDatabaseAndReturn(worker.Id, buyer.Id);
|
||||
CatHasPawsDbContext.InsertSaleToDatabaseAndReturn(worker.Id, buyer.Id);
|
||||
var salesBeforeDelete = CatHasPawsDbContext.GetSalesByBuyerId(buyer.Id);
|
||||
//Act
|
||||
var response = await HttpClient.DeleteAsync($"/api/buyers/{buyer.Id}");
|
||||
//Assert
|
||||
CatHasPawsDbContext.ChangeTracker.Clear();
|
||||
var element = CatHasPawsDbContext.GetBuyerFromDatabase(buyer.Id);
|
||||
var salesAfterDelete = CatHasPawsDbContext.GetSalesByBuyerId(buyer.Id);
|
||||
var salesNoBuyers = CatHasPawsDbContext.GetSalesByBuyerId(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(salesNoBuyers, Has.Length.EqualTo(2));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Delete_WhenNoFoundRecord_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
CatHasPawsDbContext.InsertBuyerToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.DeleteAsync($"/api/buyers/{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/buyers/id");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
private static void AssertElement(BuyerViewModel? actual, Buyer expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.Id, Is.EqualTo(expected.Id));
|
||||
Assert.That(actual.FIO, Is.EqualTo(expected.FIO));
|
||||
Assert.That(actual.PhoneNumber, Is.EqualTo(expected.PhoneNumber));
|
||||
Assert.That(actual.DiscountSize, Is.EqualTo(expected.DiscountSize));
|
||||
});
|
||||
}
|
||||
|
||||
private static BuyerBindingModel 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(Buyer? actual, BuyerBindingModel expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.Id, Is.EqualTo(expected.Id));
|
||||
Assert.That(actual.FIO, Is.EqualTo(expected.FIO));
|
||||
Assert.That(actual.PhoneNumber, Is.EqualTo(expected.PhoneNumber));
|
||||
Assert.That(actual.DiscountSize, Is.EqualTo(expected.DiscountSize));
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,357 @@
|
||||
using CatHasPawsContratcs.BindingModels;
|
||||
using CatHasPawsContratcs.ViewModels;
|
||||
using CatHasPawsDatabase.Models;
|
||||
using CatHasPawsTests.Infrastructure;
|
||||
using System.Net;
|
||||
|
||||
namespace CatHasPawsTests.WebApiControllersTests;
|
||||
|
||||
[TestFixture]
|
||||
internal class ManufacturerControllerTests : BaseWebApiControllerTest
|
||||
{
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
CatHasPawsDbContext.RemoveProductsFromDatabase();
|
||||
CatHasPawsDbContext.RemoveManufacturersFromDatabase();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_WhenHaveRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var manufacturer = CatHasPawsDbContext.InsertManufacturerToDatabaseAndReturn(manufacturerName: "name 1");
|
||||
CatHasPawsDbContext.InsertManufacturerToDatabaseAndReturn(manufacturerName: "name 2");
|
||||
CatHasPawsDbContext.InsertManufacturerToDatabaseAndReturn(manufacturerName: "name 3");
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync("/api/manufacturers");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<ManufacturerViewModel>>(response);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(3));
|
||||
});
|
||||
AssertElement(data.First(x => x.Id == manufacturer.Id), manufacturer);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_WhenNoRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync("/api/manufacturers");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<ManufacturerViewModel>>(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 manufacturer = CatHasPawsDbContext.InsertManufacturerToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/manufacturers/{manufacturer.Id}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
AssertElement(await GetModelFromResponseAsync<ManufacturerViewModel>(response), manufacturer);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ById_WhenNoRecord_ShouldNotFound_Test()
|
||||
{
|
||||
//Arrange
|
||||
CatHasPawsDbContext.InsertManufacturerToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/manufacturers/{Guid.NewGuid()}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ByName_WhenHaveRecord_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var manufacturer = CatHasPawsDbContext.InsertManufacturerToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/manufacturers/{manufacturer.ManufacturerName}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
AssertElement(await GetModelFromResponseAsync<ManufacturerViewModel>(response), manufacturer);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ByName_WhenNoRecord_ShouldNotFound_Test()
|
||||
{
|
||||
//Arrange
|
||||
CatHasPawsDbContext.InsertManufacturerToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/manufacturers/New%20Name");
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ByOldName_WhenHaveRecord_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var oldName = "old name";
|
||||
var manufacturer = CatHasPawsDbContext.InsertManufacturerToDatabaseAndReturn(prevManufacturerName: oldName);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/manufacturers/{oldName}");
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
AssertElement(await GetModelFromResponseAsync<ManufacturerViewModel>(response), manufacturer);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
CatHasPawsDbContext.InsertManufacturerToDatabaseAndReturn();
|
||||
var manufacturerModel = CreateModel();
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/manufacturers", MakeContent(manufacturerModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
AssertElement(CatHasPawsDbContext.GetManufacturerFromDatabase(manufacturerModel.Id!), manufacturerModel);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenHaveRecordWithSameId_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var manufacturerModel = CreateModel();
|
||||
CatHasPawsDbContext.InsertManufacturerToDatabaseAndReturn(manufacturerModel.Id);
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/manufacturers", MakeContent(manufacturerModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenHaveRecordWithSameName_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var manufacturerModel = CreateModel(manufacturerName: "unique name");
|
||||
CatHasPawsDbContext.InsertManufacturerToDatabaseAndReturn(manufacturerName: manufacturerModel.ManufacturerName!);
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/manufacturers", MakeContent(manufacturerModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenDataIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var manufacturerModelWithIdIncorrect = new ManufacturerBindingModel { Id = "Id", ManufacturerName = "name" };
|
||||
var manufacturerModelWithNameIncorrect = new ManufacturerBindingModel { Id = Guid.NewGuid().ToString(), ManufacturerName = string.Empty };
|
||||
//Act
|
||||
var responseWithIdIncorrect = await HttpClient.PostAsync($"/api/manufacturers", MakeContent(manufacturerModelWithIdIncorrect));
|
||||
var responseWithNameIncorrect = await HttpClient.PostAsync($"/api/manufacturers", MakeContent(manufacturerModelWithNameIncorrect));
|
||||
//Assert
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(responseWithIdIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Id is incorrect");
|
||||
Assert.That(responseWithNameIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Name is incorrect");
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenSendEmptyData_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/manufacturers", 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/manufacturers", MakeContent(new { Data = "test", Position = 10 }));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var manufacturerModel = CreateModel();
|
||||
CatHasPawsDbContext.InsertManufacturerToDatabaseAndReturn(manufacturerModel.Id);
|
||||
//Act
|
||||
var response = await HttpClient.PutAsync($"/api/manufacturers", MakeContent(manufacturerModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
CatHasPawsDbContext.ChangeTracker.Clear();
|
||||
AssertElement(CatHasPawsDbContext.GetManufacturerFromDatabase(manufacturerModel.Id!), manufacturerModel);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_CheckPrevNames_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var manufacturerModel1 = CreateModel(manufacturerName: "name 1");
|
||||
var manufacturerModel2 = CreateModel(id: manufacturerModel1.Id, manufacturerName: "name 2");
|
||||
var manufacturerModel3 = CreateModel(id: manufacturerModel1.Id, manufacturerName: "name 3");
|
||||
CatHasPawsDbContext.InsertManufacturerToDatabaseAndReturn(manufacturerModel1.Id);
|
||||
//Act
|
||||
await HttpClient.PutAsync($"/api/manufacturers", MakeContent(manufacturerModel1));
|
||||
await HttpClient.PutAsync($"/api/manufacturers", MakeContent(manufacturerModel2));
|
||||
await HttpClient.PutAsync($"/api/manufacturers", MakeContent(manufacturerModel3));
|
||||
//Assert
|
||||
CatHasPawsDbContext.ChangeTracker.Clear();
|
||||
var entityModel = CatHasPawsDbContext.GetManufacturerFromDatabase(manufacturerModel1.Id!);
|
||||
Assert.That(entityModel, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(entityModel.ManufacturerName, Is.EqualTo(manufacturerModel3.ManufacturerName));
|
||||
Assert.That(entityModel.PrevManufacturerName, Is.EqualTo(manufacturerModel2.ManufacturerName));
|
||||
Assert.That(entityModel.PrevPrevManufacturerName, Is.EqualTo(manufacturerModel1.ManufacturerName));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WhenNoFoundRecord_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var manufacturerModel = CreateModel();
|
||||
CatHasPawsDbContext.InsertManufacturerToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.PutAsync($"/api/manufacturers", MakeContent(manufacturerModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WhenHaveRecordWithSameName_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var manufacturerModel = CreateModel(manufacturerName: "unique name");
|
||||
CatHasPawsDbContext.InsertManufacturerToDatabaseAndReturn(manufacturerModel.Id);
|
||||
CatHasPawsDbContext.InsertManufacturerToDatabaseAndReturn(manufacturerName: manufacturerModel.ManufacturerName!);
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/manufacturers", MakeContent(manufacturerModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WhenDataIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var manufacturerModelWithIdIncorrect = new ManufacturerBindingModel { Id = "Id", ManufacturerName = "name" };
|
||||
var manufacturerModelWithNameIncorrect = new ManufacturerBindingModel { Id = Guid.NewGuid().ToString(), ManufacturerName = string.Empty };
|
||||
//Act
|
||||
var responseWithIdIncorrect = await HttpClient.PutAsync($"/api/manufacturers", MakeContent(manufacturerModelWithIdIncorrect));
|
||||
var responseWithNameIncorrect = await HttpClient.PutAsync($"/api/manufacturers", MakeContent(manufacturerModelWithNameIncorrect));
|
||||
//Assert
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(responseWithIdIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Id is incorrect");
|
||||
Assert.That(responseWithNameIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Name is incorrect");
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WhenSendEmptyData_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.PutAsync($"/api/manufacturers", 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/manufacturers", MakeContent(new { Data = "test", Position = 10 }));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Delete_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var manufacturerId = Guid.NewGuid().ToString();
|
||||
CatHasPawsDbContext.InsertManufacturerToDatabaseAndReturn(manufacturerId);
|
||||
//Act
|
||||
var response = await HttpClient.DeleteAsync($"/api/manufacturers/{manufacturerId}");
|
||||
//Assert
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
Assert.That(CatHasPawsDbContext.GetManufacturerFromDatabase(manufacturerId), Is.Null);
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Delete_WhenHaveProducts_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var manufacturerId = CatHasPawsDbContext.InsertManufacturerToDatabaseAndReturn().Id;
|
||||
CatHasPawsDbContext.InsertProductToDatabaseAndReturn(manufacturerId);
|
||||
//Act
|
||||
var response = await HttpClient.DeleteAsync($"/api/manufacturers/{manufacturerId}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Delete_WhenNoFoundRecord_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
CatHasPawsDbContext.InsertManufacturerToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.DeleteAsync($"/api/manufacturers/{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/manufacturers/id");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
private static void AssertElement(ManufacturerViewModel? actual, Manufacturer expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.Id, Is.EqualTo(expected.Id));
|
||||
Assert.That(actual.ManufacturerName, Is.EqualTo(expected.ManufacturerName));
|
||||
Assert.That(actual.PrevManufacturerName, Is.EqualTo(expected.PrevManufacturerName));
|
||||
Assert.That(actual.PrevPrevManufacturerName, Is.EqualTo(expected.PrevPrevManufacturerName));
|
||||
});
|
||||
}
|
||||
|
||||
private static ManufacturerBindingModel CreateModel(string? id = null, string manufacturerName = "name")
|
||||
=> new()
|
||||
{
|
||||
Id = id ?? Guid.NewGuid().ToString(),
|
||||
ManufacturerName = manufacturerName
|
||||
};
|
||||
|
||||
private static void AssertElement(Manufacturer? actual, ManufacturerBindingModel expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.Id, Is.EqualTo(expected.Id));
|
||||
Assert.That(actual.ManufacturerName, Is.EqualTo(expected.ManufacturerName));
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,471 @@
|
||||
using CatHasPawsContratcs.BindingModels;
|
||||
using CatHasPawsContratcs.Enums;
|
||||
using CatHasPawsContratcs.ViewModels;
|
||||
using CatHasPawsDatabase.Models;
|
||||
using CatHasPawsTests.Infrastructure;
|
||||
using System.Net;
|
||||
|
||||
namespace CatHasPawsTests.WebApiControllersTests;
|
||||
|
||||
|
||||
[TestFixture]
|
||||
internal class PostControllerTests : BaseWebApiControllerTest
|
||||
{
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
CatHasPawsDbContext.RemovePostsFromDatabase();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetRecords_WhenHaveRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var post = CatHasPawsDbContext.InsertPostToDatabaseAndReturn(postName: "name 1");
|
||||
CatHasPawsDbContext.InsertPostToDatabaseAndReturn(postName: "name 2");
|
||||
CatHasPawsDbContext.InsertPostToDatabaseAndReturn(postName: "name 3");
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync("/api/posts");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<PostViewModel>>(response);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(3));
|
||||
});
|
||||
AssertElement(data.First(x => x.Id == post.PostId), post);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetRecords_WhenNoRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync("/api/posts");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<ManufacturerViewModel>>(response);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(0));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetHistory_WhenHaveRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var postId = Guid.NewGuid().ToString();
|
||||
CatHasPawsDbContext.InsertPostToDatabaseAndReturn(postName: "name 1", isActual: true);
|
||||
var post = CatHasPawsDbContext.InsertPostToDatabaseAndReturn(postId, "name 2", isActual: true);
|
||||
CatHasPawsDbContext.InsertPostToDatabaseAndReturn(postId, "name 2", isActual: false);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/posthistory/{postId}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<PostViewModel>>(response);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(2));
|
||||
});
|
||||
AssertElement(data.First(x => x.Id == post.PostId), post);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetHistory_WhenNoRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var postId = Guid.NewGuid().ToString();
|
||||
CatHasPawsDbContext.InsertPostToDatabaseAndReturn(postName: "name 1", isActual: true);
|
||||
CatHasPawsDbContext.InsertPostToDatabaseAndReturn(postId, "name 2", isActual: true);
|
||||
CatHasPawsDbContext.InsertPostToDatabaseAndReturn(postId, "name 2", isActual: false);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/posthistory/{Guid.NewGuid()}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<PostViewModel>>(response);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(0));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetHistory_WhenWrongData_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/posthistory/id");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ById_WhenHaveRecord_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var post = CatHasPawsDbContext.InsertPostToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/posts/{post.PostId}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
AssertElement(await GetModelFromResponseAsync<PostViewModel>(response), post);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ById_WhenNoRecord_ShouldNotFound_Test()
|
||||
{
|
||||
//Arrange
|
||||
CatHasPawsDbContext.InsertPostToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/posts/{Guid.NewGuid()}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ById_WhenRecordWasDeleted_ShouldNotFound_Test()
|
||||
{
|
||||
//Arrange
|
||||
var post = CatHasPawsDbContext.InsertPostToDatabaseAndReturn(isActual: false);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/posts/{post.PostId}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ByName_WhenHaveRecord_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var post = CatHasPawsDbContext.InsertPostToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/posts/{post.PostName}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
AssertElement(await GetModelFromResponseAsync<PostViewModel>(response), post);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ByName_WhenNoRecord_ShouldNotFound_Test()
|
||||
{
|
||||
//Arrange
|
||||
CatHasPawsDbContext.InsertPostToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/posts/New%20Name");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ByName_WhenRecordWasDeleted_ShouldNotFound_Test()
|
||||
{
|
||||
//Arrange
|
||||
var post = CatHasPawsDbContext.InsertPostToDatabaseAndReturn(isActual: false);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/posts/{post.PostName}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
CatHasPawsDbContext.InsertPostToDatabaseAndReturn();
|
||||
var postModel = CreateModel();
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/posts", MakeContent(postModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
AssertElement(CatHasPawsDbContext.GetPostFromDatabaseByPostId(postModel.Id!), postModel);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenHaveRecordWithSameId_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var postModel = CreateModel();
|
||||
CatHasPawsDbContext.InsertPostToDatabaseAndReturn(postModel.Id);
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/posts", MakeContent(postModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenHaveRecordWithSameName_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var postModel = CreateModel(postName: "unique name");
|
||||
CatHasPawsDbContext.InsertPostToDatabaseAndReturn(postName: postModel.PostName!);
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/posts", MakeContent(postModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenDataIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var postModelWithIdIncorrect = new PostBindingModel { Id = "Id", PostName = "name", PostType = PostType.Assistant.ToString(), Salary = 10 };
|
||||
var postModelWithNameIncorrect = new PostBindingModel { Id = Guid.NewGuid().ToString(), PostName = string.Empty, PostType = PostType.Assistant.ToString(), Salary = 10 };
|
||||
var postModelWithPostTypeIncorrect = new PostBindingModel { Id = Guid.NewGuid().ToString(), PostName = string.Empty, PostType = string.Empty, Salary = 10 };
|
||||
var postModelWithSalaryIncorrect = new PostBindingModel { Id = Guid.NewGuid().ToString(), PostName = string.Empty, PostType = PostType.Assistant.ToString(), Salary = -10 };
|
||||
//Act
|
||||
var responseWithIdIncorrect = await HttpClient.PostAsync($"/api/posts", MakeContent(postModelWithIdIncorrect));
|
||||
var responseWithNameIncorrect = await HttpClient.PostAsync($"/api/posts", MakeContent(postModelWithNameIncorrect));
|
||||
var responseWithPostTypeIncorrect = await HttpClient.PostAsync($"/api/posts", MakeContent(postModelWithPostTypeIncorrect));
|
||||
var responseWithSalaryIncorrect = await HttpClient.PostAsync($"/api/posts", MakeContent(postModelWithSalaryIncorrect));
|
||||
//Assert
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(responseWithIdIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Id is incorrect");
|
||||
Assert.That(responseWithNameIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Name is incorrect");
|
||||
Assert.That(responseWithPostTypeIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Type is incorrect");
|
||||
Assert.That(responseWithSalaryIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Salary is incorrect");
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenSendEmptyData_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/posts", MakeContent(string.Empty));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenSendWrongFormatData_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/posts", MakeContent(new { Data = "test", Position = 10 }));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var postModel = CreateModel();
|
||||
CatHasPawsDbContext.InsertPostToDatabaseAndReturn(postModel.Id);
|
||||
//Act
|
||||
var response = await HttpClient.PutAsync($"/api/posts", MakeContent(postModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
CatHasPawsDbContext.ChangeTracker.Clear();
|
||||
AssertElement(CatHasPawsDbContext.GetPostFromDatabaseByPostId(postModel.Id!), postModel);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WhenNoFoundRecord_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var postModel = CreateModel();
|
||||
CatHasPawsDbContext.InsertPostToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.PutAsync($"/api/posts", MakeContent(postModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WhenRecordWasDeleted_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var postModel = CreateModel();
|
||||
CatHasPawsDbContext.InsertPostToDatabaseAndReturn(postModel.Id, isActual: false);
|
||||
//Act
|
||||
var response = await HttpClient.PutAsync($"/api/posts", MakeContent(postModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WhenHaveRecordWithSameName_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var postModel = CreateModel(postName: "unique name");
|
||||
CatHasPawsDbContext.InsertPostToDatabaseAndReturn(postModel.Id);
|
||||
CatHasPawsDbContext.InsertPostToDatabaseAndReturn(postName: postModel.PostName!);
|
||||
//Act
|
||||
var response = await HttpClient.PutAsync($"/api/posts", MakeContent(postModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WhenDataIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var postModelWithIdIncorrect = new PostBindingModel { Id = "Id", PostName = "name", PostType = PostType.Assistant.ToString(), Salary = 10 };
|
||||
var postModelWithNameIncorrect = new PostBindingModel { Id = Guid.NewGuid().ToString(), PostName = string.Empty, PostType = PostType.Assistant.ToString(), Salary = 10 };
|
||||
var postModelWithPostTypeIncorrect = new PostBindingModel { Id = Guid.NewGuid().ToString(), PostName = string.Empty, PostType = string.Empty, Salary = 10 };
|
||||
var postModelWithSalaryIncorrect = new PostBindingModel { Id = Guid.NewGuid().ToString(), PostName = string.Empty, PostType = PostType.Assistant.ToString(), Salary = -10 };
|
||||
//Act
|
||||
var responseWithIdIncorrect = await HttpClient.PutAsync($"/api/posts", MakeContent(postModelWithIdIncorrect));
|
||||
var responseWithNameIncorrect = await HttpClient.PutAsync($"/api/posts", MakeContent(postModelWithNameIncorrect));
|
||||
var responseWithPostTypeIncorrect = await HttpClient.PutAsync($"/api/posts", MakeContent(postModelWithPostTypeIncorrect));
|
||||
var responseWithSalaryIncorrect = await HttpClient.PutAsync($"/api/posts", MakeContent(postModelWithSalaryIncorrect));
|
||||
//Assert
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(responseWithIdIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Id is incorrect");
|
||||
Assert.That(responseWithNameIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Name is incorrect");
|
||||
Assert.That(responseWithPostTypeIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Type is incorrect");
|
||||
Assert.That(responseWithSalaryIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Salary is incorrect");
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WhenSendEmptyData_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.PutAsync($"/api/posts", MakeContent(string.Empty));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WhenSendWrongFormatData_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.PutAsync($"/api/posts", MakeContent(new { Data = "test", Position = 10 }));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Delete_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var postId = CatHasPawsDbContext.InsertPostToDatabaseAndReturn().PostId;
|
||||
//Act
|
||||
var response = await HttpClient.DeleteAsync($"/api/posts/{postId}");
|
||||
//Assert
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
Assert.That(CatHasPawsDbContext.GetPostFromDatabaseByPostId(postId), Is.Null);
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Delete_WhenNoFoundRecord_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
CatHasPawsDbContext.InsertPostToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.DeleteAsync($"/api/posts/{Guid.NewGuid()}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Delete_WhenRecordWasDeleted_Test()
|
||||
{
|
||||
//Arrange
|
||||
var postId = CatHasPawsDbContext.InsertPostToDatabaseAndReturn(isActual: false).PostId;
|
||||
//Act
|
||||
var response = await HttpClient.DeleteAsync($"/api/posts/{postId}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Delete_WhenSendWrongFormatData_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.DeleteAsync($"/api/posts/id");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Patch_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var postId = CatHasPawsDbContext.InsertPostToDatabaseAndReturn(isActual: false).PostId;
|
||||
//Act
|
||||
var response = await HttpClient.PatchAsync($"/api/posts/{postId}", null);
|
||||
//Assert
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
Assert.That(CatHasPawsDbContext.GetPostFromDatabaseByPostId(postId), Is.Not.Null);
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Patch_WhenNoFoundRecord_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
CatHasPawsDbContext.InsertPostToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.PatchAsync($"/api/posts/{Guid.NewGuid()}", null);
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Patch_WhenRecordNotWasDeleted_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var postId = CatHasPawsDbContext.InsertPostToDatabaseAndReturn().PostId;
|
||||
//Act
|
||||
var response = await HttpClient.PatchAsync($"/api/posts/{postId}", null);
|
||||
//Assert
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
Assert.That(CatHasPawsDbContext.GetPostFromDatabaseByPostId(postId), Is.Not.Null);
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Patch_WhenSendWrongFormatData_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.PatchAsync($"/api/posts/id", null);
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
private static void AssertElement(PostViewModel? actual, Post expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.Id, Is.EqualTo(expected.PostId));
|
||||
Assert.That(actual.PostName, Is.EqualTo(expected.PostName));
|
||||
Assert.That(actual.PostType, Is.EqualTo(expected.PostType.ToString()));
|
||||
Assert.That(actual.Salary, Is.EqualTo(expected.Salary));
|
||||
});
|
||||
}
|
||||
|
||||
private static PostBindingModel CreateModel(string? postId = null, string postName = "name", PostType postType = PostType.Assistant, double salary = 10)
|
||||
=> new()
|
||||
{
|
||||
Id = postId ?? Guid.NewGuid().ToString(),
|
||||
PostName = postName,
|
||||
PostType = postType.ToString(),
|
||||
Salary = salary
|
||||
};
|
||||
|
||||
private static void AssertElement(Post? actual, PostBindingModel expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.PostId, Is.EqualTo(expected.Id));
|
||||
Assert.That(actual.PostName, Is.EqualTo(expected.PostName));
|
||||
Assert.That(actual.PostType.ToString(), Is.EqualTo(expected.PostType));
|
||||
Assert.That(actual.Salary, Is.EqualTo(expected.Salary));
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,536 @@
|
||||
using CatHasPawsContratcs.BindingModels;
|
||||
using CatHasPawsContratcs.Enums;
|
||||
using CatHasPawsContratcs.ViewModels;
|
||||
using CatHasPawsDatabase;
|
||||
using CatHasPawsDatabase.Models;
|
||||
using CatHasPawsTests.Infrastructure;
|
||||
using System.Net;
|
||||
|
||||
namespace CatHasPawsTests.WebApiControllersTests;
|
||||
|
||||
[TestFixture]
|
||||
internal class ProductControllerTests : BaseWebApiControllerTest
|
||||
{
|
||||
private string _manufacturerId;
|
||||
|
||||
[SetUp]
|
||||
public void SetUp()
|
||||
{
|
||||
_manufacturerId = CatHasPawsDbContext.InsertManufacturerToDatabaseAndReturn().Id;
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
CatHasPawsDbContext.RemoveProductsFromDatabase();
|
||||
CatHasPawsDbContext.RemoveManufacturersFromDatabase();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_WhenHaveRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var product = CatHasPawsDbContext.InsertProductToDatabaseAndReturn(_manufacturerId, productName: "name 1");
|
||||
CatHasPawsDbContext.InsertProductToDatabaseAndReturn(_manufacturerId, productName: "name 2");
|
||||
CatHasPawsDbContext.InsertProductToDatabaseAndReturn(_manufacturerId, productName: "name 3");
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync("/api/products/getrecords?includeDeleted=false");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<ProductViewModel>>(response);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(3));
|
||||
});
|
||||
AssertElement(data.First(x => x.Id == product.Id), product);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_WhenNoRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync("/api/products/getrecords?includeDeleted=false");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<ProductViewModel>>(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
|
||||
CatHasPawsDbContext.InsertProductToDatabaseAndReturn(_manufacturerId, productName: "name 1", isDeleted: true);
|
||||
CatHasPawsDbContext.InsertProductToDatabaseAndReturn(_manufacturerId, productName: "name 2", isDeleted: false);
|
||||
CatHasPawsDbContext.InsertProductToDatabaseAndReturn(_manufacturerId, productName: "name 3", isDeleted: false);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync("/api/products/getrecords?includeDeleted=false");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<ProductViewModel>>(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
|
||||
CatHasPawsDbContext.InsertProductToDatabaseAndReturn(_manufacturerId, productName: "name 1", isDeleted: true);
|
||||
CatHasPawsDbContext.InsertProductToDatabaseAndReturn(_manufacturerId, productName: "name 2", isDeleted: true);
|
||||
CatHasPawsDbContext.InsertProductToDatabaseAndReturn(_manufacturerId, productName: "name 3", isDeleted: false);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync("/api/products/getrecords?includeDeleted=true");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<ProductViewModel>>(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_ByManufacturer_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var manufacruer = CatHasPawsDbContext.InsertManufacturerToDatabaseAndReturn(manufacturerName: "name 2");
|
||||
var product = CatHasPawsDbContext.InsertProductToDatabaseAndReturn(_manufacturerId, productName: "name 1", isDeleted: true);
|
||||
CatHasPawsDbContext.InsertProductToDatabaseAndReturn(_manufacturerId, productName: "name 2", isDeleted: false);
|
||||
CatHasPawsDbContext.InsertProductToDatabaseAndReturn(manufacruer.Id, productName: "name 3", isDeleted: false);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/products/getmanufacturerrecords?id={_manufacturerId}&includeDeleted=true");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<ProductViewModel>>(response);
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Has.Count.EqualTo(2));
|
||||
Assert.That(data.All(x => x.ManufacturerId == _manufacturerId));
|
||||
});
|
||||
AssertElement(data.First(x => x.Id == product.Id), product);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_ByManufacturer_WhenOnlyActual_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var manufacruer = CatHasPawsDbContext.InsertManufacturerToDatabaseAndReturn(manufacturerName: "name 2");
|
||||
CatHasPawsDbContext.InsertProductToDatabaseAndReturn(_manufacturerId, productName: "name 1", isDeleted: true);
|
||||
CatHasPawsDbContext.InsertProductToDatabaseAndReturn(_manufacturerId, productName: "name 2", isDeleted: false);
|
||||
CatHasPawsDbContext.InsertProductToDatabaseAndReturn(manufacruer.Id, productName: "name 3", isDeleted: false);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/products/getmanufacturerrecords?id={_manufacturerId}&includeDeleted=false");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<ProductViewModel>>(response);
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Has.Count.EqualTo(1));
|
||||
Assert.That(data.All(x => x.ManufacturerId == _manufacturerId && !x.IsDeleted));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_ByManufacturer_WhenIdIsNotGuid_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/products/getmanufacturerrecords?id=id&includeDeleted=false");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetHistoryByProductId_WhenHaveRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var product = CatHasPawsDbContext.InsertProductToDatabaseAndReturn(_manufacturerId);
|
||||
CatHasPawsDbContext.InsertProductHistoryToDatabaseAndReturn(product.Id, 20, DateTime.UtcNow.AddDays(-1));
|
||||
CatHasPawsDbContext.InsertProductHistoryToDatabaseAndReturn(product.Id, 30, DateTime.UtcNow.AddMinutes(-10));
|
||||
var history = CatHasPawsDbContext.InsertProductHistoryToDatabaseAndReturn(product.Id, 40, DateTime.UtcNow.AddDays(1));
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/products/gethistory?id={product.Id}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<ProductHistoryViewModel>>(response);
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(3));
|
||||
AssertElement(data[0], history);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetHistoryByProductId_WhenNoRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var product = CatHasPawsDbContext.InsertProductToDatabaseAndReturn(_manufacturerId);
|
||||
CatHasPawsDbContext.InsertProductHistoryToDatabaseAndReturn(product.Id, 20, DateTime.UtcNow.AddDays(-1));
|
||||
CatHasPawsDbContext.InsertProductHistoryToDatabaseAndReturn(product.Id, 30, DateTime.UtcNow.AddMinutes(-10));
|
||||
CatHasPawsDbContext.InsertProductHistoryToDatabaseAndReturn(product.Id, 40, DateTime.UtcNow.AddDays(1));
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/products/gethistory?id={Guid.NewGuid()}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<ProductViewModel>>(response);
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(0));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetHistoryByProductId_WhenProductIdIsNotGuid_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/products/gethistory?id=id");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ById_WhenHaveRecord_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var product = CatHasPawsDbContext.InsertProductToDatabaseAndReturn(_manufacturerId);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/products/getrecord/{product.Id}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
AssertElement(await GetModelFromResponseAsync<ProductViewModel>(response), product);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ById_WhenNoRecord_ShouldNotFound_Test()
|
||||
{
|
||||
//Arrange
|
||||
CatHasPawsDbContext.InsertProductToDatabaseAndReturn(_manufacturerId);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/products/getrecord/{Guid.NewGuid()}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ById_WhenRecordWasDeleted_ShouldNotFound_Test()
|
||||
{
|
||||
//Arrange
|
||||
var product = CatHasPawsDbContext.InsertProductToDatabaseAndReturn(_manufacturerId, isDeleted: true);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/products/getrecord/{product.Id}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ByName_WhenHaveRecord_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var product = CatHasPawsDbContext.InsertProductToDatabaseAndReturn(_manufacturerId);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/products/getrecord/{product.ProductName}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
AssertElement(await GetModelFromResponseAsync<ProductViewModel>(response), product);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ByName_WhenNoRecord_ShouldNotFound_Test()
|
||||
{
|
||||
//Arrange
|
||||
CatHasPawsDbContext.InsertProductToDatabaseAndReturn(_manufacturerId);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/products/getrecord/New%20Name");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ByName_WhenRecordWasDeleted_ShouldNotFound_Test()
|
||||
{
|
||||
//Arrange
|
||||
var product = CatHasPawsDbContext.InsertProductToDatabaseAndReturn(_manufacturerId, isDeleted: true);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/products/getrecord/{product.ProductName}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
CatHasPawsDbContext.InsertProductToDatabaseAndReturn(_manufacturerId);
|
||||
var productModel = CreateModel(_manufacturerId);
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/products/register", MakeContent(productModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
AssertElement(CatHasPawsDbContext.GetProductFromDatabaseById(productModel.Id!), productModel);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenHaveRecordWithSameId_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var productModel = CreateModel(_manufacturerId);
|
||||
CatHasPawsDbContext.InsertProductToDatabaseAndReturn(_manufacturerId, productModel.Id);
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/products/register", MakeContent(productModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenHaveRecordWithSameName_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var productModel = CreateModel(_manufacturerId, productName: "unique name");
|
||||
CatHasPawsDbContext.InsertProductToDatabaseAndReturn(_manufacturerId, productName: productModel.ProductName!);
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/products/register", MakeContent(productModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenDataIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var productModelWithIdIncorrect = new ProductBindingModel { Id = "Id", ManufacturerId = _manufacturerId, ProductName = "name", Price = 100, ProductType = ProductType.Toy.ToString() };
|
||||
var productModelWithNameIncorrect = new ProductBindingModel { Id = Guid.NewGuid().ToString(), ManufacturerId = _manufacturerId, ProductName = string.Empty, Price = 100, ProductType = ProductType.Toy.ToString() };
|
||||
var productModelWithProductTypeIncorrect = new ProductBindingModel { Id = Guid.NewGuid().ToString(), ManufacturerId = _manufacturerId, ProductName = "name", Price = 100, ProductType = string.Empty };
|
||||
var productModelWithPriceIncorrect = new ProductBindingModel { Id = Guid.NewGuid().ToString(), ManufacturerId = _manufacturerId, ProductName = "name", Price = 0, ProductType = ProductType.Toy.ToString() };
|
||||
//Act
|
||||
var responseWithIdIncorrect = await HttpClient.PostAsync($"/api/products/register", MakeContent(productModelWithIdIncorrect));
|
||||
var responseWithNameIncorrect = await HttpClient.PostAsync($"/api/products/register", MakeContent(productModelWithNameIncorrect));
|
||||
var responseWithProductTypeIncorrect = await HttpClient.PostAsync($"/api/products/register", MakeContent(productModelWithProductTypeIncorrect));
|
||||
var responseWithPriceIncorrect = await HttpClient.PostAsync($"/api/products/register", MakeContent(productModelWithPriceIncorrect));
|
||||
//Assert
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(responseWithIdIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Id is incorrect");
|
||||
Assert.That(responseWithNameIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Name is incorrect");
|
||||
Assert.That(responseWithProductTypeIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Name is incorrect");
|
||||
Assert.That(responseWithPriceIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Name is incorrect");
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenSendEmptyData_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/products/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/products/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 productModel = CreateModel(_manufacturerId);
|
||||
CatHasPawsDbContext.InsertProductToDatabaseAndReturn(_manufacturerId, productModel.Id);
|
||||
//Act
|
||||
var response = await HttpClient.PutAsync($"/api/products/changeinfo", MakeContent(productModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
CatHasPawsDbContext.ChangeTracker.Clear();
|
||||
AssertElement(CatHasPawsDbContext.GetProductFromDatabaseById(productModel.Id!), productModel);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WhenNoFoundRecord_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var productModel = CreateModel(_manufacturerId);
|
||||
CatHasPawsDbContext.InsertProductToDatabaseAndReturn(_manufacturerId);
|
||||
//Act
|
||||
var response = await HttpClient.PutAsync($"/api/products/changeinfo", MakeContent(productModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WhenHaveRecordWithSameName_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var productModel = CreateModel(_manufacturerId, productName: "unique name");
|
||||
CatHasPawsDbContext.InsertProductToDatabaseAndReturn(_manufacturerId, productModel.Id);
|
||||
CatHasPawsDbContext.InsertProductToDatabaseAndReturn(_manufacturerId, productName: productModel.ProductName!);
|
||||
//Act
|
||||
var response = await HttpClient.PutAsync($"/api/products/changeinfo", MakeContent(productModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WhenRecordWasDeleted_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var productModel = CreateModel(_manufacturerId);
|
||||
CatHasPawsDbContext.InsertProductToDatabaseAndReturn(_manufacturerId, productModel.Id, isDeleted: true);
|
||||
//Act
|
||||
var response = await HttpClient.PutAsync($"/api/products/changeinfo", MakeContent(productModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WhenDataIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var productModelWithIdIncorrect = new ProductBindingModel { Id = "Id", ManufacturerId = _manufacturerId, ProductName = "name", Price = 100, ProductType = ProductType.Toy.ToString() };
|
||||
var productModelWithNameIncorrect = new ProductBindingModel { Id = Guid.NewGuid().ToString(), ManufacturerId = _manufacturerId, ProductName = string.Empty, Price = 100, ProductType = ProductType.Toy.ToString() };
|
||||
var productModelWithProductTypeIncorrect = new ProductBindingModel { Id = Guid.NewGuid().ToString(), ManufacturerId = _manufacturerId, ProductName = "name", Price = 100, ProductType = string.Empty };
|
||||
var productModelWithPriceIncorrect = new ProductBindingModel { Id = Guid.NewGuid().ToString(), ManufacturerId = _manufacturerId, ProductName = "name", Price = 0, ProductType = ProductType.Toy.ToString() };
|
||||
//Act
|
||||
var responseWithIdIncorrect = await HttpClient.PutAsync($"/api/products/changeinfo", MakeContent(productModelWithIdIncorrect));
|
||||
var responseWithNameIncorrect = await HttpClient.PutAsync($"/api/products/changeinfo", MakeContent(productModelWithNameIncorrect));
|
||||
var responseWithProductTypeIncorrect = await HttpClient.PutAsync($"/api/products/changeinfo", MakeContent(productModelWithProductTypeIncorrect));
|
||||
var responseWithPriceIncorrect = await HttpClient.PutAsync($"/api/products/changeinfo", MakeContent(productModelWithPriceIncorrect));
|
||||
//Assert
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(responseWithIdIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Id is incorrect");
|
||||
Assert.That(responseWithNameIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Name is incorrect");
|
||||
Assert.That(responseWithProductTypeIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Name is incorrect");
|
||||
Assert.That(responseWithPriceIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Name is incorrect");
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WhenSendEmptyData_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.PutAsync($"/api/products/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/products/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 productId = Guid.NewGuid().ToString();
|
||||
CatHasPawsDbContext.InsertProductToDatabaseAndReturn(_manufacturerId, productId);
|
||||
//Act
|
||||
var response = await HttpClient.DeleteAsync($"/api/products/delete/{productId}");
|
||||
CatHasPawsDbContext.ChangeTracker.Clear();
|
||||
//Assert
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
Assert.That(CatHasPawsDbContext.GetProductFromDatabaseById(productId)!.IsDeleted);
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Delete_WhenNoFoundRecord_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
CatHasPawsDbContext.InsertProductToDatabaseAndReturn(_manufacturerId);
|
||||
//Act
|
||||
var response = await HttpClient.DeleteAsync($"/api/products/delete/{Guid.NewGuid()}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Delete_WhenRecordWasDeleted_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var productId = CatHasPawsDbContext.InsertProductToDatabaseAndReturn(_manufacturerId, isDeleted: true).Id;
|
||||
//Act
|
||||
var response = await HttpClient.DeleteAsync($"/api/products/delete/{productId}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Delete_WhenSendWrongFormatData_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.DeleteAsync($"/api/products/delete/id");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
private static void AssertElement(ProductViewModel? actual, Product expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.Id, Is.EqualTo(expected.Id));
|
||||
Assert.That(actual.ManufacturerId, Is.EqualTo(expected.ManufacturerId));
|
||||
Assert.That(actual.ProductName, Is.EqualTo(expected.ProductName));
|
||||
Assert.That(actual.ProductType, Is.EqualTo(expected.ProductType.ToString()));
|
||||
Assert.That(actual.Price, Is.EqualTo(expected.Price));
|
||||
Assert.That(actual.IsDeleted, Is.EqualTo(expected.IsDeleted));
|
||||
Assert.That(actual.ManufacturerName, Is.EqualTo(expected.Manufacturer!.ManufacturerName));
|
||||
});
|
||||
}
|
||||
|
||||
private static void AssertElement(ProductHistoryViewModel? actual, ProductHistory expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.ProductName, Is.EqualTo(expected.Product!.ProductName));
|
||||
Assert.That(actual.OldPrice, Is.EqualTo(expected.OldPrice));
|
||||
Assert.That(actual.ChangeDate.ToString(), Is.EqualTo(expected.ChangeDate.ToString()));
|
||||
});
|
||||
}
|
||||
|
||||
private static ProductBindingModel CreateModel(string manufacturerId, string? id = null, string productName = "name", ProductType productType = ProductType.Feed, double price = 1)
|
||||
=> new()
|
||||
{
|
||||
Id = id ?? Guid.NewGuid().ToString(),
|
||||
ManufacturerId = manufacturerId,
|
||||
ProductName = productName,
|
||||
ProductType = productType.ToString(),
|
||||
Price = price
|
||||
};
|
||||
|
||||
private static void AssertElement(Product? actual, ProductBindingModel expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.Id, Is.EqualTo(expected.Id));
|
||||
Assert.That(actual.ManufacturerId, Is.EqualTo(expected.ManufacturerId));
|
||||
Assert.That(actual.ProductName, Is.EqualTo(expected.ProductName));
|
||||
Assert.That(actual.ProductType.ToString(), Is.EqualTo(expected.ProductType));
|
||||
Assert.That(actual.Price, Is.EqualTo(expected.Price));
|
||||
Assert.That(!actual.IsDeleted);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,507 @@
|
||||
using CatHasPawsContratcs.BindingModels;
|
||||
using CatHasPawsContratcs.Enums;
|
||||
using CatHasPawsContratcs.ViewModels;
|
||||
using CatHasPawsDatabase.Models;
|
||||
using CatHasPawsTests.Infrastructure;
|
||||
using System.Net;
|
||||
|
||||
namespace CatHasPawsTests.WebApiControllersTests;
|
||||
|
||||
[TestFixture]
|
||||
internal class SaleControllerTests : BaseWebApiControllerTest
|
||||
{
|
||||
private string _buyerId;
|
||||
private string _workerId;
|
||||
private string _manufacturerId;
|
||||
private string _productId;
|
||||
|
||||
[SetUp]
|
||||
public void SetUp()
|
||||
{
|
||||
_buyerId = CatHasPawsDbContext.InsertBuyerToDatabaseAndReturn().Id;
|
||||
_workerId = CatHasPawsDbContext.InsertWorkerToDatabaseAndReturn().Id;
|
||||
_manufacturerId = CatHasPawsDbContext.InsertManufacturerToDatabaseAndReturn().Id;
|
||||
_productId = CatHasPawsDbContext.InsertProductToDatabaseAndReturn(_manufacturerId).Id;
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
CatHasPawsDbContext.RemoveSalesFromDatabase();
|
||||
CatHasPawsDbContext.RemoveWorkersFromDatabase();
|
||||
CatHasPawsDbContext.RemoveBuyersFromDatabase();
|
||||
CatHasPawsDbContext.RemoveProductsFromDatabase();
|
||||
CatHasPawsDbContext.RemoveManufacturersFromDatabase();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_WhenHaveRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var sale = CatHasPawsDbContext.InsertSaleToDatabaseAndReturn(_workerId, buyerId: _buyerId, sum: 10, products: [(_productId, 10, 1.1)]);
|
||||
CatHasPawsDbContext.InsertSaleToDatabaseAndReturn(_workerId, products: [(_productId, 10, 1.1)]);
|
||||
CatHasPawsDbContext.InsertSaleToDatabaseAndReturn(_workerId, products: [(_productId, 10, 1.1)]);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/sales/getrecords?fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<SaleViewModel>>(response);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(3));
|
||||
});
|
||||
AssertElement(data.First(x => x.Sum == sale.Sum), sale);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_WhenNoRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/sales/getrecords?fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<SaleViewModel>>(response);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(0));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_ByPeriod_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
CatHasPawsDbContext.InsertSaleToDatabaseAndReturn(_workerId, _buyerId, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(-3), products: [(_productId, 1, 1.1)]);
|
||||
CatHasPawsDbContext.InsertSaleToDatabaseAndReturn(_workerId, _buyerId, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(3), products: [(_productId, 1, 1.1)]);
|
||||
CatHasPawsDbContext.InsertSaleToDatabaseAndReturn(_workerId, null, saleDate: DateTime.UtcNow.AddDays(1).AddMinutes(-3), products: [(_productId, 1, 1.1)]);
|
||||
CatHasPawsDbContext.InsertSaleToDatabaseAndReturn(_workerId, null, saleDate: DateTime.UtcNow.AddDays(1).AddMinutes(3), products: [(_productId, 1, 1.1)]);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/sales/getrecords?fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<SaleViewModel>>(response);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(2));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_ByPeriod_WhenDateIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/sales/getrecords?fromDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_ByWorkerId_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var worker = CatHasPawsDbContext.InsertWorkerToDatabaseAndReturn(fio: "Other worker");
|
||||
CatHasPawsDbContext.InsertSaleToDatabaseAndReturn(_workerId, _buyerId, products: [(_productId, 1, 1.1)]);
|
||||
CatHasPawsDbContext.InsertSaleToDatabaseAndReturn(_workerId, _buyerId, products: [(_productId, 1, 1.1)]);
|
||||
CatHasPawsDbContext.InsertSaleToDatabaseAndReturn(worker.Id, null, products: [(_productId, 1, 1.1)]);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/sales/getworkerrecords?id={_workerId}&fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<SaleViewModel>>(response);
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Has.Count.EqualTo(2));
|
||||
Assert.That(data.All(x => x.WorkerId == _workerId));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_ByWorkerId_WhenNoRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var worker = CatHasPawsDbContext.InsertWorkerToDatabaseAndReturn(fio: "Other worker");
|
||||
CatHasPawsDbContext.InsertSaleToDatabaseAndReturn(_workerId, _buyerId, products: [(_productId, 1, 1.1)]);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/sales/getworkerrecords?id={worker.Id}&fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<SaleViewModel>>(response);
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(0));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_ByWorkerId_WhenDateIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/sales/getworkerrecords?id={_workerId}&fromDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_ByWorkerId_WhenIdIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/sales/getworkerrecords?id=Id&fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_ByBuyerId_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var buyer = CatHasPawsDbContext.InsertBuyerToDatabaseAndReturn(fio: "Other fio", phoneNumber: "+8-888-888-88-88");
|
||||
CatHasPawsDbContext.InsertSaleToDatabaseAndReturn(_workerId, _buyerId, products: [(_productId, 1, 1.1)]);
|
||||
CatHasPawsDbContext.InsertSaleToDatabaseAndReturn(_workerId, _buyerId, products: [(_productId, 1, 1.1)]);
|
||||
CatHasPawsDbContext.InsertSaleToDatabaseAndReturn(_workerId, buyer.Id, products: [(_productId, 1, 1.1)]);
|
||||
CatHasPawsDbContext.InsertSaleToDatabaseAndReturn(_workerId, null, products: [(_productId, 1, 1.1)]);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/sales/getbuyerrecords?id={_buyerId}&fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<SaleViewModel>>(response);
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Has.Count.EqualTo(2));
|
||||
Assert.That(data.All(x => x.BuyerId == _buyerId));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_ByBuyerId_WhenNoRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var buyer = CatHasPawsDbContext.InsertBuyerToDatabaseAndReturn(fio: "Other buyer", phoneNumber: "+8-888-888-88-88");
|
||||
CatHasPawsDbContext.InsertSaleToDatabaseAndReturn(_workerId, _buyerId, products: [(_productId, 1, 1.1)]);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/sales/getbuyerrecords?id={buyer.Id}&fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<SaleViewModel>>(response);
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(0));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_ByBuyerId_WhenDateIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/sales/getbuyerrecords?id={_buyerId}&fromDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_ByBuyerId_WhenIdIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/sales/getbuyerrecords?id=Id&fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_ByProductId_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var product = CatHasPawsDbContext.InsertProductToDatabaseAndReturn(_manufacturerId, productName: "Other name");
|
||||
CatHasPawsDbContext.InsertSaleToDatabaseAndReturn(_workerId, _buyerId, products: [(_productId, 5, 1.1)]);
|
||||
CatHasPawsDbContext.InsertSaleToDatabaseAndReturn(_workerId, _buyerId, products: [(_productId, 1, 1.1), (product.Id, 4, 1.1)]);
|
||||
CatHasPawsDbContext.InsertSaleToDatabaseAndReturn(_workerId, null, products: [(product.Id, 1, 1.1)]);
|
||||
CatHasPawsDbContext.InsertSaleToDatabaseAndReturn(_workerId, null, products: [(product.Id, 1, 1.1), (_productId, 1, 1.1)]);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/sales/getproductrecords?id={_productId}&fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<SaleViewModel>>(response);
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Has.Count.EqualTo(3));
|
||||
Assert.That(data.All(x => x.Products.Any(y => y.ProductId == _productId)));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_ByProductId_WhenNoRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var product = CatHasPawsDbContext.InsertProductToDatabaseAndReturn(_manufacturerId, productName: "Other product");
|
||||
CatHasPawsDbContext.InsertSaleToDatabaseAndReturn(_workerId, _buyerId, products: [(_productId, 1, 1.1)]);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/sales/getproductrecords?id={product.Id}&fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<SaleViewModel>>(response);
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(0));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_ByProductId_WhenDateIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/sales/getproductrecords?id={_productId}&fromDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_ByProductId_WhenIdIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/sales/getproductrecords?id=Id&fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ById_WhenHaveRecord_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var sale = CatHasPawsDbContext.InsertSaleToDatabaseAndReturn(_workerId, _buyerId, products: [(_productId, 5, 1.1)]);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/sales/getrecord/{sale.Id}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
AssertElement(await GetModelFromResponseAsync<SaleViewModel>(response), sale);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ById_WhenNoRecord_ShouldNotFound_Test()
|
||||
{
|
||||
//Arrange
|
||||
CatHasPawsDbContext.InsertSaleToDatabaseAndReturn(_workerId, _buyerId, products: [(_productId, 5, 1.1)]);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/sales/getrecord/{Guid.NewGuid()}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ById_WhenRecordHasCanceled_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var sale = CatHasPawsDbContext.InsertSaleToDatabaseAndReturn(_workerId, _buyerId, products: [(_productId, 1, 1.2)], isCancel: true);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/sales/getrecord/{sale.Id}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ById_WhenIdIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/sales/getrecord/Id");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
CatHasPawsDbContext.InsertSaleToDatabaseAndReturn(_workerId, null, products: [(_productId, 5, 1.1)]);
|
||||
var saleModel = CreateModel(_workerId, _buyerId, _productId);
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/sales/sale", MakeContent(saleModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
AssertElement(CatHasPawsDbContext.GetSalesByBuyerId(_buyerId)[0], saleModel);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenNoBuyer_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
CatHasPawsDbContext.InsertSaleToDatabaseAndReturn(_workerId, _buyerId, products: [(_productId, 5, 1.1)]);
|
||||
var saleModel = CreateModel(_workerId, null, _productId);
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/sales/sale", MakeContent(saleModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
AssertElement(CatHasPawsDbContext.GetSalesByBuyerId(null)[0], saleModel);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenDataIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var saleId = Guid.NewGuid().ToString();
|
||||
var saleModelWithIdIncorrect = new SaleBindingModel { Id = "Id", WorkerId = _workerId, BuyerId = _buyerId, DiscountType = 1, Products = [new SaleProductBindingModel { SaleId = saleId, ProductId = _productId, Count = 10, Price = 1.1 }] };
|
||||
var saleModelWithWorkerIdIncorrect = new SaleBindingModel { Id = saleId, WorkerId = "Id", BuyerId = _buyerId, DiscountType = 1, Products = [new SaleProductBindingModel { SaleId = saleId, ProductId = _productId, Count = 10, Price = 1.1 }] };
|
||||
var saleModelWithBuyerIdIncorrect = new SaleBindingModel { Id = saleId, WorkerId = _workerId, BuyerId = "Id", DiscountType = 1, Products = [new SaleProductBindingModel { SaleId = saleId, ProductId = _productId, Count = 10, Price = 1.1 }] };
|
||||
var saleModelWithProductsIncorrect = new SaleBindingModel { Id = saleId, WorkerId = _workerId, BuyerId = _buyerId, DiscountType = 1, Products = null };
|
||||
var saleModelWithProductIdIncorrect = new SaleBindingModel { Id = saleId, WorkerId = _workerId, BuyerId = _buyerId, DiscountType = 1, Products = [new SaleProductBindingModel { SaleId = saleId, ProductId = "Id", Count = 10, Price = 1.1 }] };
|
||||
var saleModelWithCountIncorrect = new SaleBindingModel { Id = saleId, WorkerId = _workerId, BuyerId = _buyerId, DiscountType = 1, Products = [new SaleProductBindingModel { SaleId = saleId, ProductId = _productId, Count = -10, Price = 1.1 }] };
|
||||
var saleModelWithPriceIncorrect = new SaleBindingModel { Id = saleId, WorkerId = _workerId, BuyerId = _buyerId, DiscountType = 1, Products = [new SaleProductBindingModel { SaleId = saleId, ProductId = _productId, Count = 10, Price = -1.1 }] };
|
||||
//Act
|
||||
var responseWithIdIncorrect = await HttpClient.PostAsync($"/api/sales/sale", MakeContent(saleModelWithIdIncorrect));
|
||||
var responseWithWorkerIdIncorrect = await HttpClient.PostAsync($"/api/sales/sale", MakeContent(saleModelWithWorkerIdIncorrect));
|
||||
var responseWithBuyerIdIncorrect = await HttpClient.PostAsync($"/api/sales/sale", MakeContent(saleModelWithBuyerIdIncorrect));
|
||||
var responseWithProductsIncorrect = await HttpClient.PostAsync($"/api/sales/sale", MakeContent(saleModelWithProductsIncorrect));
|
||||
var responseWithProductIdIncorrect = await HttpClient.PostAsync($"/api/sales/sale", MakeContent(saleModelWithProductIdIncorrect));
|
||||
var responseWithCountIncorrect = await HttpClient.PostAsync($"/api/sales/sale", MakeContent(saleModelWithCountIncorrect));
|
||||
var responseWithPriceIncorrect = await HttpClient.PostAsync($"/api/sales/sale", MakeContent(saleModelWithPriceIncorrect));
|
||||
//Assert
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(responseWithIdIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "WorkerId is incorrect");
|
||||
Assert.That(responseWithWorkerIdIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "WorkerId is incorrect");
|
||||
Assert.That(responseWithBuyerIdIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "BuyerId is incorrect");
|
||||
Assert.That(responseWithProductsIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Products is incorrect");
|
||||
Assert.That(responseWithProductIdIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "ProductId is incorrect");
|
||||
Assert.That(responseWithCountIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Count is incorrect");
|
||||
Assert.That(responseWithPriceIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Price is incorrect");
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenSendEmptyData_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/sales/sale", MakeContent(string.Empty));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenSendWrongFormatData_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/sales/sale", MakeContent(new { Data = "test", Position = 10 }));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Delete_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var sale = CatHasPawsDbContext.InsertSaleToDatabaseAndReturn(_workerId, _buyerId, products: [(_productId, 5, 1.1)]);
|
||||
//Act
|
||||
var response = await HttpClient.DeleteAsync($"/api/sales/cancel/{sale.Id}");
|
||||
CatHasPawsDbContext.ChangeTracker.Clear();
|
||||
//Assert
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
Assert.That(CatHasPawsDbContext.GetSaleFromDatabaseById(sale.Id)!.IsCancel);
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Delete_WhenNoFoundRecord_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
CatHasPawsDbContext.InsertSaleToDatabaseAndReturn(_workerId, _buyerId, products: [(_productId, 5, 1.1)]);
|
||||
//Act
|
||||
var response = await HttpClient.DeleteAsync($"/api/sales/cancel/{Guid.NewGuid()}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Delete_WhenIsCanceled_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var sale = CatHasPawsDbContext.InsertSaleToDatabaseAndReturn(_workerId, _buyerId, products: [(_productId, 5, 1.1)], isCancel: true);
|
||||
//Act
|
||||
var response = await HttpClient.DeleteAsync($"/api/sales/cancel/{sale.Id}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Delete_WhenSendWrongFormatData_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.DeleteAsync($"/api/sales/cancel/id");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
private static void AssertElement(SaleViewModel? actual, Sale expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.Id, Is.EqualTo(expected.Id));
|
||||
Assert.That(actual.WorkerFIO, Is.EqualTo(expected.Worker!.FIO));
|
||||
Assert.That(actual.BuyerFIO, Is.EqualTo(expected.Buyer?.FIO));
|
||||
Assert.That(actual.DiscountType, Is.EqualTo(expected.DiscountType.ToString()));
|
||||
Assert.That(actual.Discount, Is.EqualTo(expected.Discount));
|
||||
Assert.That(actual.IsCancel, Is.EqualTo(expected.IsCancel));
|
||||
});
|
||||
|
||||
if (expected.SaleProducts is not null)
|
||||
{
|
||||
Assert.That(actual.Products, Is.Not.Null);
|
||||
Assert.That(actual.Products, Has.Count.EqualTo(expected.SaleProducts.Count));
|
||||
for (int i = 0; i < actual.Products.Count; ++i)
|
||||
{
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.Products[i].ProductName, Is.EqualTo(expected.SaleProducts[i].Product!.ProductName));
|
||||
Assert.That(actual.Products[i].Count, Is.EqualTo(expected.SaleProducts[i].Count));
|
||||
});
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
Assert.That(actual.Products, Is.Null);
|
||||
}
|
||||
}
|
||||
|
||||
private static SaleBindingModel CreateModel(string workerId, string? buyerId, string productId, string? id = null, DiscountType discountType = DiscountType.OnSale, int count = 1, double price = 1.1)
|
||||
{
|
||||
var saleId = id ?? Guid.NewGuid().ToString();
|
||||
return new()
|
||||
{
|
||||
Id = saleId,
|
||||
WorkerId = workerId,
|
||||
BuyerId = buyerId,
|
||||
DiscountType = (int)discountType,
|
||||
Products = [new SaleProductBindingModel { SaleId = saleId, ProductId = productId, Count = count, Price = price }]
|
||||
};
|
||||
}
|
||||
|
||||
private static void AssertElement(Sale? actual, SaleBindingModel expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.WorkerId, Is.EqualTo(expected.WorkerId));
|
||||
Assert.That(actual.BuyerId, Is.EqualTo(expected.BuyerId));
|
||||
Assert.That((int)actual.DiscountType, Is.EqualTo(expected.DiscountType));
|
||||
Assert.That(!actual.IsCancel);
|
||||
});
|
||||
|
||||
if (expected.Products is not null)
|
||||
{
|
||||
Assert.That(actual.SaleProducts, Is.Not.Null);
|
||||
Assert.That(actual.SaleProducts, Has.Count.EqualTo(expected.Products.Count));
|
||||
for (int i = 0; i < actual.SaleProducts.Count; ++i)
|
||||
{
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.SaleProducts[i].ProductId, Is.EqualTo(expected.Products[i].ProductId));
|
||||
Assert.That(actual.SaleProducts[i].Count, Is.EqualTo(expected.Products[i].Count));
|
||||
Assert.That(actual.SaleProducts[i].Price, Is.EqualTo(expected.Products[i].Price));
|
||||
});
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
Assert.That(actual.SaleProducts, Is.Null);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,508 @@
|
||||
using CatHasPawsContratcs.BindingModels;
|
||||
using CatHasPawsContratcs.ViewModels;
|
||||
using CatHasPawsDatabase.Models;
|
||||
using CatHasPawsTests.Infrastructure;
|
||||
using System.Net;
|
||||
|
||||
namespace CatHasPawsTests.WebApiControllersTests;
|
||||
|
||||
[TestFixture]
|
||||
internal class WorkerControllerTests : BaseWebApiControllerTest
|
||||
{
|
||||
private Post _post;
|
||||
|
||||
[SetUp]
|
||||
public void SetUp()
|
||||
{
|
||||
_post = CatHasPawsDbContext.InsertPostToDatabaseAndReturn();
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
CatHasPawsDbContext.RemovePostsFromDatabase();
|
||||
CatHasPawsDbContext.RemoveWorkersFromDatabase();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_WhenHaveRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var worker = CatHasPawsDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 1", postId: _post.PostId)
|
||||
.AddPost(_post);
|
||||
CatHasPawsDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 2", postId: _post.PostId);
|
||||
CatHasPawsDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 3", postId: _post.PostId);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync("/api/workers/getrecords");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<WorkerViewModel>>(response);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(3));
|
||||
});
|
||||
AssertElement(data.First(x => x.Id == worker.Id), worker);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_WhenNoRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync("/api/workers/getrecords");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<WorkerViewModel>>(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
|
||||
CatHasPawsDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 1", postId: _post.PostId, isDeleted: true);
|
||||
CatHasPawsDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 2", postId: _post.PostId, isDeleted: false);
|
||||
CatHasPawsDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 3", postId: _post.PostId, isDeleted: false);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync("/api/workers/getrecords?includeDeleted=false");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<WorkerViewModel>>(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
|
||||
CatHasPawsDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 1", postId: _post.PostId, isDeleted: true);
|
||||
CatHasPawsDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 2", postId: _post.PostId, isDeleted: true);
|
||||
CatHasPawsDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 3", postId: _post.PostId, isDeleted: false);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync("/api/workers/getrecords?includeDeleted=true");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<WorkerViewModel>>(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
|
||||
CatHasPawsDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 1", postId: _post.PostId);
|
||||
CatHasPawsDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 2", postId: _post.PostId);
|
||||
CatHasPawsDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 3", postId: _post.PostId, isDeleted: true);
|
||||
CatHasPawsDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 4");
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/workers/getpostrecords?id={_post.PostId}&includeDeleted=true");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<WorkerViewModel>>(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
|
||||
CatHasPawsDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 1", postId: _post.PostId);
|
||||
CatHasPawsDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 4");
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/workers/getpostrecords?id={Guid.NewGuid()}&includeDeleted=true");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<WorkerViewModel>>(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/workers/getpostrecords?id=id&includeDeleted=true");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_ByBirthDate_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
CatHasPawsDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 1", birthDate: DateTime.UtcNow.AddYears(-25));
|
||||
CatHasPawsDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 2", birthDate: DateTime.UtcNow.AddYears(-21));
|
||||
CatHasPawsDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 3", birthDate: DateTime.UtcNow.AddYears(-20), isDeleted: true);
|
||||
CatHasPawsDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 4", birthDate: DateTime.UtcNow.AddYears(-19));
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/workers/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<WorkerViewModel>>(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/workers/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
|
||||
CatHasPawsDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 1", employmentDate: DateTime.UtcNow.AddDays(-2));
|
||||
CatHasPawsDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 2", employmentDate: DateTime.UtcNow.AddDays(-1));
|
||||
CatHasPawsDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 3", employmentDate: DateTime.UtcNow.AddDays(1), isDeleted: true);
|
||||
CatHasPawsDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 4", employmentDate: DateTime.UtcNow.AddDays(2));
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/workers/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<WorkerViewModel>>(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/workers/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 worker = CatHasPawsDbContext.InsertWorkerToDatabaseAndReturn(postId: _post.PostId).AddPost(_post);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/workers/getrecord/{worker.Id}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
AssertElement(await GetModelFromResponseAsync<WorkerViewModel>(response), worker);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ById_WhenNoRecord_ShouldNotFound_Test()
|
||||
{
|
||||
//Arrange
|
||||
CatHasPawsDbContext.InsertWorkerToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/workers/getrecord/{Guid.NewGuid()}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ById_WhenRecordWasDeleted_ShouldNotFound_Test()
|
||||
{
|
||||
//Arrange
|
||||
var worker = CatHasPawsDbContext.InsertWorkerToDatabaseAndReturn(postId: _post.PostId, isDeleted: true);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/workers/getrecord/{worker.Id}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ByFIO_WhenHaveRecord_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var worker = CatHasPawsDbContext.InsertWorkerToDatabaseAndReturn(postId: _post.PostId).AddPost(_post);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/workers/getrecord/{worker.FIO}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
AssertElement(await GetModelFromResponseAsync<WorkerViewModel>(response), worker);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ByFIO_WhenNoRecord_ShouldNotFound_Test()
|
||||
{
|
||||
//Arrange
|
||||
CatHasPawsDbContext.InsertWorkerToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/workers/getrecord/New%20Fio");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ByFIO_WhenRecordWasDeleted_ShouldNotFound_Test()
|
||||
{
|
||||
//Arrange
|
||||
var worker = CatHasPawsDbContext.InsertWorkerToDatabaseAndReturn(postId: _post.PostId, isDeleted: true);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/workers/getrecord/{worker.FIO}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
CatHasPawsDbContext.InsertWorkerToDatabaseAndReturn();
|
||||
var workerModel = CreateModel(_post.Id);
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/workers/register", MakeContent(workerModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
AssertElement(CatHasPawsDbContext.GetWorkerFromDatabaseById(workerModel.Id!), workerModel);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenHaveRecordWithSameId_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var workerModel = CreateModel(_post.Id);
|
||||
CatHasPawsDbContext.InsertWorkerToDatabaseAndReturn(workerModel.Id);
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/workers/register", MakeContent(workerModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenDataIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var workerModelWithIdIncorrect = new WorkerBindingModel { Id = "Id", FIO = "fio", BirthDate = DateTime.UtcNow.AddYears(-22), EmploymentDate = DateTime.UtcNow.AddDays(-5), PostId = _post.Id };
|
||||
var workerModelWithFioIncorrect = new WorkerBindingModel { Id = Guid.NewGuid().ToString(), FIO = string.Empty, BirthDate = DateTime.UtcNow.AddYears(-22), EmploymentDate = DateTime.UtcNow.AddDays(-5), PostId = _post.Id };
|
||||
var workerModelWithPostIdIncorrect = new WorkerBindingModel { Id = Guid.NewGuid().ToString(), FIO = "fio", BirthDate = DateTime.UtcNow.AddYears(-22), EmploymentDate = DateTime.UtcNow.AddDays(-5), PostId = "Id" };
|
||||
var workerModelWithBirthDateIncorrect = new WorkerBindingModel { 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/workers/register", MakeContent(workerModelWithIdIncorrect));
|
||||
var responseWithFioIncorrect = await HttpClient.PostAsync($"/api/workers/register", MakeContent(workerModelWithFioIncorrect));
|
||||
var responseWithPostIdIncorrect = await HttpClient.PostAsync($"/api/workers/register", MakeContent(workerModelWithPostIdIncorrect));
|
||||
var responseWithBirthDateIncorrect = await HttpClient.PostAsync($"/api/workers/register", MakeContent(workerModelWithBirthDateIncorrect));
|
||||
//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(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/workers/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/workers/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 workerModel = CreateModel(_post.Id);
|
||||
CatHasPawsDbContext.InsertWorkerToDatabaseAndReturn(workerModel.Id);
|
||||
//Act
|
||||
var response = await HttpClient.PutAsync($"/api/workers/changeinfo", MakeContent(workerModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
CatHasPawsDbContext.ChangeTracker.Clear();
|
||||
AssertElement(CatHasPawsDbContext.GetWorkerFromDatabaseById(workerModel.Id!), workerModel);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WhenNoFoundRecord_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var workerModel = CreateModel(_post.Id, fio: "new fio");
|
||||
CatHasPawsDbContext.InsertWorkerToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.PutAsync($"/api/workers/changeinfo", MakeContent(workerModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WhenRecordWasDeleted_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var workerModel = CreateModel(_post.Id, fio: "new fio");
|
||||
CatHasPawsDbContext.InsertWorkerToDatabaseAndReturn(workerModel.Id, isDeleted: true);
|
||||
//Act
|
||||
var response = await HttpClient.PutAsync($"/api/workers/changeinfo", MakeContent(workerModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WhenDataIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var workerModelWithIdIncorrect = new WorkerBindingModel { Id = "Id", FIO = "fio", BirthDate = DateTime.UtcNow.AddYears(-22), EmploymentDate = DateTime.UtcNow.AddDays(-5), PostId = _post.Id };
|
||||
var workerModelWithFioIncorrect = new WorkerBindingModel { Id = Guid.NewGuid().ToString(), FIO = string.Empty, BirthDate = DateTime.UtcNow.AddYears(-22), EmploymentDate = DateTime.UtcNow.AddDays(-5), PostId = _post.Id };
|
||||
var workerModelWithPostIdIncorrect = new WorkerBindingModel { Id = Guid.NewGuid().ToString(), FIO = "fio", BirthDate = DateTime.UtcNow.AddYears(-22), EmploymentDate = DateTime.UtcNow.AddDays(-5), PostId = "Id" };
|
||||
var workerModelWithBirthDateIncorrect = new WorkerBindingModel { Id = Guid.NewGuid().ToString(), FIO = "fio", BirthDate = DateTime.UtcNow.AddYears(-15), EmploymentDate = DateTime.UtcNow.AddDays(-5), PostId = _post.Id };
|
||||
//Act
|
||||
var responseWithIdIncorrect = await HttpClient.PutAsync($"/api/workers/changeinfo", MakeContent(workerModelWithIdIncorrect));
|
||||
var responseWithFioIncorrect = await HttpClient.PutAsync($"/api/workers/changeinfo", MakeContent(workerModelWithFioIncorrect));
|
||||
var responseWithPostIdIncorrect = await HttpClient.PutAsync($"/api/workers/changeinfo", MakeContent(workerModelWithPostIdIncorrect));
|
||||
var responseWithBirthDateIncorrect = await HttpClient.PutAsync($"/api/workers/changeinfo", MakeContent(workerModelWithBirthDateIncorrect));
|
||||
//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(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/workers/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/workers/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 workerId = Guid.NewGuid().ToString();
|
||||
CatHasPawsDbContext.InsertWorkerToDatabaseAndReturn(workerId);
|
||||
//Act
|
||||
var response = await HttpClient.DeleteAsync($"/api/workers/delete/{workerId}");
|
||||
CatHasPawsDbContext.ChangeTracker.Clear();
|
||||
//Assert
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
Assert.That(CatHasPawsDbContext.GetWorkerFromDatabaseById(workerId)!.IsDeleted);
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Delete_WhenNoFoundRecord_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
CatHasPawsDbContext.InsertWorkerToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.DeleteAsync($"/api/workers/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/workers/delete/id");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Delete_WhenRecordWasDeleted_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var workerId = CatHasPawsDbContext.InsertWorkerToDatabaseAndReturn(isDeleted: true).Id;
|
||||
//Act
|
||||
var response = await HttpClient.DeleteAsync($"/api/workers/delete/{workerId}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
private static void AssertElement(WorkerViewModel? actual, Worker expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.Id, Is.EqualTo(expected.Id));
|
||||
Assert.That(actual.PostId, Is.EqualTo(expected.PostId));
|
||||
Assert.That(actual.PostName, Is.EqualTo(expected.Post!.PostName));
|
||||
Assert.That(actual.FIO, Is.EqualTo(expected.FIO));
|
||||
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 WorkerBindingModel CreateModel(string postId, string? id = null, string fio = "fio", DateTime? birthDate = null, DateTime? employmentDate = null)
|
||||
{
|
||||
return new()
|
||||
{
|
||||
Id = id ?? Guid.NewGuid().ToString(),
|
||||
FIO = fio,
|
||||
BirthDate = birthDate ?? DateTime.UtcNow.AddYears(-22),
|
||||
EmploymentDate = employmentDate ?? DateTime.UtcNow.AddDays(-5),
|
||||
PostId = postId
|
||||
};
|
||||
}
|
||||
|
||||
private static void AssertElement(Worker? actual, WorkerBindingModel expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.Id, Is.EqualTo(expected.Id));
|
||||
Assert.That(actual.PostId, Is.EqualTo(expected.PostId));
|
||||
Assert.That(actual.FIO, Is.EqualTo(expected.FIO));
|
||||
Assert.That(actual.BirthDate.ToString(), Is.EqualTo(expected.BirthDate.ToString()));
|
||||
Assert.That(actual.EmploymentDate.ToString(), Is.EqualTo(expected.EmploymentDate.ToString()));
|
||||
Assert.That(!actual.IsDeleted);
|
||||
});
|
||||
}
|
||||
}
|
||||
24
TheCatHasPawsProject/CatHasPawsTests/appsettings.json
Normal file
24
TheCatHasPawsProject/CatHasPawsTests/appsettings.json
Normal file
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
}
|
||||
},
|
||||
"Serilog": {
|
||||
"Using": [ "Serilog.Sinks.File" ],
|
||||
"MinimumLevel": {
|
||||
"Default": "Information"
|
||||
},
|
||||
"WriteTo": [
|
||||
{
|
||||
"Name": "File",
|
||||
"Args": {
|
||||
"path": "../logs/cathaspaws-.log",
|
||||
"rollingInterval": "Day",
|
||||
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} {CorrelationId} {Level:u3} {Username} {Message:lj}{Exception}{NewLine}"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
189
TheCatHasPawsProject/CatHasPawsWebApi/Adapters/BuyerAdapter.cs
Normal file
189
TheCatHasPawsProject/CatHasPawsWebApi/Adapters/BuyerAdapter.cs
Normal file
@@ -0,0 +1,189 @@
|
||||
using AutoMapper;
|
||||
using CatHasPawsContratcs.AdapterContracts;
|
||||
using CatHasPawsContratcs.AdapterContracts.OperationResponses;
|
||||
using CatHasPawsContratcs.BindingModels;
|
||||
using CatHasPawsContratcs.BusinessLogicsContracts;
|
||||
using CatHasPawsContratcs.DataModels;
|
||||
using CatHasPawsContratcs.Exceptions;
|
||||
using CatHasPawsContratcs.ViewModels;
|
||||
|
||||
namespace CatHasPawsWebApi.Adapters;
|
||||
|
||||
public class BuyerAdapter : IBuyerAdapter
|
||||
{
|
||||
private readonly IBuyerBusinessLogicContract _buyerBusinessLogicContract;
|
||||
|
||||
private readonly ILogger _logger;
|
||||
|
||||
private readonly Mapper _mapper;
|
||||
|
||||
public BuyerAdapter(IBuyerBusinessLogicContract buyerBusinessLogicContract, ILogger<BuyerAdapter> logger)
|
||||
{
|
||||
_buyerBusinessLogicContract = buyerBusinessLogicContract;
|
||||
_logger = logger;
|
||||
var config = new MapperConfiguration(cfg =>
|
||||
{
|
||||
cfg.CreateMap<BuyerBindingModel, BuyerDataModel>();
|
||||
cfg.CreateMap<BuyerDataModel, BuyerViewModel>();
|
||||
});
|
||||
_mapper = new Mapper(config);
|
||||
}
|
||||
|
||||
public BuyerOperationResponse GetList()
|
||||
{
|
||||
try
|
||||
{
|
||||
return BuyerOperationResponse.OK([.. _buyerBusinessLogicContract.GetAllBuyers().Select(x => _mapper.Map<BuyerViewModel>(x))]);
|
||||
}
|
||||
catch (NullListException)
|
||||
{
|
||||
_logger.LogError("NullListException");
|
||||
return BuyerOperationResponse.NotFound("The list is not initialized");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return BuyerOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return BuyerOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public BuyerOperationResponse GetElement(string data)
|
||||
{
|
||||
try
|
||||
{
|
||||
return BuyerOperationResponse.OK(_mapper.Map<BuyerViewModel>(_buyerBusinessLogicContract.GetBuyerByData(data)));
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return BuyerOperationResponse.BadRequest("Data is empty");
|
||||
}
|
||||
catch (ElementNotFoundException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementNotFoundException");
|
||||
return BuyerOperationResponse.NotFound($"Not found element by data {data}");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return BuyerOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return BuyerOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public BuyerOperationResponse RegisterBuyer(BuyerBindingModel buyerModel)
|
||||
{
|
||||
try
|
||||
{
|
||||
_buyerBusinessLogicContract.InsertBuyer(_mapper.Map<BuyerDataModel>(buyerModel));
|
||||
return BuyerOperationResponse.NoContent();
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return BuyerOperationResponse.BadRequest("Data is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return BuyerOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (ElementExistsException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementExistsException");
|
||||
return BuyerOperationResponse.BadRequest(ex.Message);
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return BuyerOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return BuyerOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public BuyerOperationResponse ChangeBuyerInfo(BuyerBindingModel buyerModel)
|
||||
{
|
||||
try
|
||||
{
|
||||
_buyerBusinessLogicContract.UpdateBuyer(_mapper.Map<BuyerDataModel>(buyerModel));
|
||||
return BuyerOperationResponse.NoContent();
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return BuyerOperationResponse.BadRequest("Data is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return BuyerOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (ElementNotFoundException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementNotFoundException");
|
||||
return BuyerOperationResponse.BadRequest($"Not found element by Id {buyerModel.Id}");
|
||||
}
|
||||
catch (ElementExistsException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementExistsException");
|
||||
return BuyerOperationResponse.BadRequest(ex.Message);
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return BuyerOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return BuyerOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public BuyerOperationResponse RemoveBuyer(string id)
|
||||
{
|
||||
try
|
||||
{
|
||||
_buyerBusinessLogicContract.DeleteBuyer(id);
|
||||
return BuyerOperationResponse.NoContent();
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return BuyerOperationResponse.BadRequest("Id is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return BuyerOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (ElementNotFoundException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementNotFoundException");
|
||||
return BuyerOperationResponse.BadRequest($"Not found element by id: {id}");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return BuyerOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return BuyerOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
using AutoMapper;
|
||||
using CatHasPawsContratcs.AdapterContracts;
|
||||
using CatHasPawsContratcs.AdapterContracts.OperationResponses;
|
||||
using CatHasPawsContratcs.BindingModels;
|
||||
using CatHasPawsContratcs.BusinessLogicsContracts;
|
||||
using CatHasPawsContratcs.DataModels;
|
||||
using CatHasPawsContratcs.Exceptions;
|
||||
using CatHasPawsContratcs.ViewModels;
|
||||
|
||||
namespace CatHasPawsWebApi.Adapters;
|
||||
|
||||
public class ManufacturerAdapter : IManufacturerAdapter
|
||||
{
|
||||
private readonly IManufacturerBusinessLogicContract _manufacturerBusinessLogicContract;
|
||||
|
||||
private readonly ILogger _logger;
|
||||
|
||||
private readonly Mapper _mapper;
|
||||
|
||||
public ManufacturerAdapter(IManufacturerBusinessLogicContract manufacturerBusinessLogicContract, ILogger<ManufacturerAdapter> logger)
|
||||
{
|
||||
_manufacturerBusinessLogicContract = manufacturerBusinessLogicContract;
|
||||
_logger = logger;
|
||||
var config = new MapperConfiguration(cfg =>
|
||||
{
|
||||
cfg.CreateMap<ManufacturerBindingModel, ManufacturerDataModel>();
|
||||
cfg.CreateMap<ManufacturerDataModel, ManufacturerViewModel>();
|
||||
});
|
||||
_mapper = new Mapper(config);
|
||||
}
|
||||
|
||||
public ManufacturerOperationResponse GetList()
|
||||
{
|
||||
try
|
||||
{
|
||||
return ManufacturerOperationResponse.OK([.. _manufacturerBusinessLogicContract.GetAllManufacturers().Select(x => _mapper.Map<ManufacturerViewModel>(x))]);
|
||||
}
|
||||
catch (NullListException)
|
||||
{
|
||||
_logger.LogError("NullListException");
|
||||
return ManufacturerOperationResponse.NotFound("The list is not initialized");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return ManufacturerOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return ManufacturerOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public ManufacturerOperationResponse GetElement(string data)
|
||||
{
|
||||
try
|
||||
{
|
||||
return ManufacturerOperationResponse.OK(_mapper.Map<ManufacturerViewModel>(_manufacturerBusinessLogicContract.GetManufacturerByData(data)));
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return ManufacturerOperationResponse.BadRequest("Data is empty");
|
||||
}
|
||||
catch (ElementNotFoundException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementNotFoundException");
|
||||
return ManufacturerOperationResponse.NotFound($"Not found element by data {data}");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return ManufacturerOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return ManufacturerOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public ManufacturerOperationResponse RegisterManufacturer(ManufacturerBindingModel manufacturerModel)
|
||||
{
|
||||
try
|
||||
{
|
||||
_manufacturerBusinessLogicContract.InsertManufacturer(_mapper.Map<ManufacturerDataModel>(manufacturerModel));
|
||||
return ManufacturerOperationResponse.NoContent();
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return ManufacturerOperationResponse.BadRequest("Data is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return ManufacturerOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (ElementExistsException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementExistsException");
|
||||
return ManufacturerOperationResponse.BadRequest(ex.Message);
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return ManufacturerOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return ManufacturerOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public ManufacturerOperationResponse ChangeManufacturerInfo(ManufacturerBindingModel manufacturerModel)
|
||||
{
|
||||
try
|
||||
{
|
||||
_manufacturerBusinessLogicContract.UpdateManufacturer(_mapper.Map<ManufacturerDataModel>(manufacturerModel));
|
||||
return ManufacturerOperationResponse.NoContent();
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return ManufacturerOperationResponse.BadRequest("Data is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return ManufacturerOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (ElementNotFoundException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementNotFoundException");
|
||||
return ManufacturerOperationResponse.BadRequest($"Not found element by Id {manufacturerModel.Id}");
|
||||
}
|
||||
catch (ElementExistsException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementExistsException");
|
||||
return ManufacturerOperationResponse.BadRequest(ex.Message);
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return ManufacturerOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return ManufacturerOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public ManufacturerOperationResponse RemoveManufacturer(string id)
|
||||
{
|
||||
try
|
||||
{
|
||||
_manufacturerBusinessLogicContract.DeleteManufacturer(id);
|
||||
return ManufacturerOperationResponse.NoContent();
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return ManufacturerOperationResponse.BadRequest("Id is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return ManufacturerOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (ElementNotFoundException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementNotFoundException");
|
||||
return ManufacturerOperationResponse.BadRequest($"Not found element by id: {id}");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return ManufacturerOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return ManufacturerOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
266
TheCatHasPawsProject/CatHasPawsWebApi/Adapters/PostAdapter.cs
Normal file
266
TheCatHasPawsProject/CatHasPawsWebApi/Adapters/PostAdapter.cs
Normal file
@@ -0,0 +1,266 @@
|
||||
using AutoMapper;
|
||||
using CatHasPawsContratcs.AdapterContracts.OperationResponses;
|
||||
using CatHasPawsContratcs.AdapterContracts;
|
||||
using CatHasPawsContratcs.BindingModels;
|
||||
using CatHasPawsContratcs.BusinessLogicsContracts;
|
||||
using CatHasPawsContratcs.DataModels;
|
||||
using CatHasPawsContratcs.Exceptions;
|
||||
using CatHasPawsContratcs.ViewModels;
|
||||
|
||||
namespace CatHasPawsWebApi.Adapters;
|
||||
|
||||
public class PostAdapter : IPostAdapter
|
||||
{
|
||||
private readonly IPostBusinessLogicContract _postBusinessLogicContract;
|
||||
|
||||
private readonly ILogger _logger;
|
||||
|
||||
private readonly Mapper _mapper;
|
||||
|
||||
public PostAdapter(IPostBusinessLogicContract postBusinessLogicContract, ILogger<PostAdapter> logger)
|
||||
{
|
||||
_postBusinessLogicContract = postBusinessLogicContract;
|
||||
_logger = logger;
|
||||
var config = new MapperConfiguration(cfg =>
|
||||
{
|
||||
cfg.CreateMap<PostBindingModel, PostDataModel>();
|
||||
cfg.CreateMap<PostDataModel, PostViewModel>();
|
||||
});
|
||||
_mapper = new Mapper(config);
|
||||
}
|
||||
|
||||
public PostOperationResponse GetList()
|
||||
{
|
||||
try
|
||||
{
|
||||
return PostOperationResponse.OK([.. _postBusinessLogicContract.GetAllPosts().Select(x => _mapper.Map<PostViewModel>(x))]);
|
||||
}
|
||||
catch (NullListException)
|
||||
{
|
||||
_logger.LogError("NullListException");
|
||||
return PostOperationResponse.NotFound("The list is not initialized");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return PostOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return PostOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public PostOperationResponse GetHistory(string id)
|
||||
{
|
||||
try
|
||||
{
|
||||
return PostOperationResponse.OK([.. _postBusinessLogicContract.GetAllDataOfPost(id).Select(x => _mapper.Map<PostViewModel>(x))]);
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return PostOperationResponse.BadRequest("Data is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return PostOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return PostOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return PostOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public PostOperationResponse GetElement(string data)
|
||||
{
|
||||
try
|
||||
{
|
||||
return PostOperationResponse.OK(_mapper.Map<PostViewModel>(_postBusinessLogicContract.GetPostByData(data)));
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return PostOperationResponse.BadRequest("Data is empty");
|
||||
}
|
||||
catch (ElementNotFoundException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementNotFoundException");
|
||||
return PostOperationResponse.NotFound($"Not found element by data {data}");
|
||||
}
|
||||
catch (ElementDeletedException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementDeletedException");
|
||||
return PostOperationResponse.BadRequest($"Element by data: {data} was deleted");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return PostOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return PostOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public PostOperationResponse RegisterPost(PostBindingModel postModel)
|
||||
{
|
||||
try
|
||||
{
|
||||
_postBusinessLogicContract.InsertPost(_mapper.Map<PostDataModel>(postModel));
|
||||
return PostOperationResponse.NoContent();
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return PostOperationResponse.BadRequest("Data is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return PostOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (ElementExistsException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementExistsException");
|
||||
return PostOperationResponse.BadRequest(ex.Message);
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return PostOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return PostOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public PostOperationResponse ChangePostInfo(PostBindingModel postModel)
|
||||
{
|
||||
try
|
||||
{
|
||||
_postBusinessLogicContract.UpdatePost(_mapper.Map<PostDataModel>(postModel));
|
||||
return PostOperationResponse.NoContent();
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return PostOperationResponse.BadRequest("Data is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return PostOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (ElementNotFoundException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementNotFoundException");
|
||||
return PostOperationResponse.BadRequest($"Not found element by Id {postModel.Id}");
|
||||
}
|
||||
catch (ElementExistsException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementExistsException");
|
||||
return PostOperationResponse.BadRequest(ex.Message);
|
||||
}
|
||||
catch (ElementDeletedException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementDeletedException");
|
||||
return PostOperationResponse.BadRequest($"Element by id: {postModel.Id} was deleted");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return PostOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return PostOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public PostOperationResponse RemovePost(string id)
|
||||
{
|
||||
try
|
||||
{
|
||||
_postBusinessLogicContract.DeletePost(id);
|
||||
return PostOperationResponse.NoContent();
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return PostOperationResponse.BadRequest("Id is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return PostOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (ElementNotFoundException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementNotFoundException");
|
||||
return PostOperationResponse.BadRequest($"Not found element by id: {id}");
|
||||
}
|
||||
catch (ElementDeletedException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementDeletedException");
|
||||
return PostOperationResponse.BadRequest($"Element by id: {id} was deleted");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return PostOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return PostOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public PostOperationResponse RestorePost(string id)
|
||||
{
|
||||
try
|
||||
{
|
||||
_postBusinessLogicContract.RestorePost(id);
|
||||
return PostOperationResponse.NoContent();
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return PostOperationResponse.BadRequest("Id is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return PostOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (ElementNotFoundException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementNotFoundException");
|
||||
return PostOperationResponse.BadRequest($"Not found element by id: {id}");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return PostOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return PostOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
266
TheCatHasPawsProject/CatHasPawsWebApi/Adapters/ProductAdapter.cs
Normal file
266
TheCatHasPawsProject/CatHasPawsWebApi/Adapters/ProductAdapter.cs
Normal file
@@ -0,0 +1,266 @@
|
||||
using AutoMapper;
|
||||
using CatHasPawsContratcs.AdapterContracts.OperationResponses;
|
||||
using CatHasPawsContratcs.AdapterContracts;
|
||||
using CatHasPawsContratcs.BindingModels;
|
||||
using CatHasPawsContratcs.BusinessLogicsContracts;
|
||||
using CatHasPawsContratcs.DataModels;
|
||||
using CatHasPawsContratcs.Exceptions;
|
||||
using CatHasPawsContratcs.ViewModels;
|
||||
|
||||
namespace CatHasPawsWebApi.Adapters;
|
||||
|
||||
public class ProductAdapter : IProductAdapter
|
||||
{
|
||||
private readonly IProductBusinessLogicContract _productBusinessLogicContract;
|
||||
|
||||
private readonly ILogger _logger;
|
||||
|
||||
private readonly Mapper _mapper;
|
||||
|
||||
public ProductAdapter(IProductBusinessLogicContract productBusinessLogicContract, ILogger<ProductAdapter> logger)
|
||||
{
|
||||
_productBusinessLogicContract = productBusinessLogicContract;
|
||||
_logger = logger;
|
||||
var config = new MapperConfiguration(cfg =>
|
||||
{
|
||||
cfg.CreateMap<ProductBindingModel, ProductDataModel>();
|
||||
cfg.CreateMap<ProductDataModel, ProductViewModel>();
|
||||
cfg.CreateMap<ProductHistoryDataModel, ProductHistoryViewModel>();
|
||||
});
|
||||
_mapper = new Mapper(config);
|
||||
}
|
||||
|
||||
public ProductOperationResponse GetList(bool includeDeleted)
|
||||
{
|
||||
try
|
||||
{
|
||||
return ProductOperationResponse.OK([.. _productBusinessLogicContract.GetAllProducts(!includeDeleted).Select(x => _mapper.Map<ProductViewModel>(x))]);
|
||||
}
|
||||
catch (NullListException)
|
||||
{
|
||||
_logger.LogError("NullListException");
|
||||
return ProductOperationResponse.NotFound("The list is not initialized");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return ProductOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return ProductOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public ProductOperationResponse GetManufacturerList(string id, bool includeDeleted)
|
||||
{
|
||||
try
|
||||
{
|
||||
return ProductOperationResponse.OK([.. _productBusinessLogicContract.GetAllProductsByManufacturer(id, !includeDeleted).Select(x => _mapper.Map<ProductViewModel>(x))]);
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return ProductOperationResponse.BadRequest("Data is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return ProductOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (NullListException)
|
||||
{
|
||||
_logger.LogError("NullListException");
|
||||
return ProductOperationResponse.NotFound("The list is not initialized");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return ProductOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return ProductOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public ProductOperationResponse GetHistory(string id)
|
||||
{
|
||||
try
|
||||
{
|
||||
return ProductOperationResponse.OK([.. _productBusinessLogicContract.GetProductHistoryByProduct(id).Select(x => _mapper.Map<ProductHistoryViewModel>(x))]);
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return ProductOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (NullListException)
|
||||
{
|
||||
_logger.LogError("NullListException");
|
||||
return ProductOperationResponse.NotFound("The list is not initialized");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return ProductOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return ProductOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public ProductOperationResponse GetElement(string data)
|
||||
{
|
||||
try
|
||||
{
|
||||
return ProductOperationResponse.OK(_mapper.Map<ProductViewModel>(_productBusinessLogicContract.GetProductByData(data)));
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return ProductOperationResponse.BadRequest("Data is empty");
|
||||
}
|
||||
catch (ElementNotFoundException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementNotFoundException");
|
||||
return ProductOperationResponse.NotFound($"Not found element by data {data}");
|
||||
}
|
||||
catch (ElementDeletedException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementDeletedException");
|
||||
return ProductOperationResponse.BadRequest($"Element by data: {data} was deleted");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return ProductOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return ProductOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public ProductOperationResponse RegisterProduct(ProductBindingModel productModel)
|
||||
{
|
||||
try
|
||||
{
|
||||
_productBusinessLogicContract.InsertProduct(_mapper.Map<ProductDataModel>(productModel));
|
||||
return ProductOperationResponse.NoContent();
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return ProductOperationResponse.BadRequest("Data is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return ProductOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (ElementExistsException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementExistsException");
|
||||
return ProductOperationResponse.BadRequest(ex.Message);
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return ProductOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return ProductOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public ProductOperationResponse ChangeProductInfo(ProductBindingModel productModel)
|
||||
{
|
||||
try
|
||||
{
|
||||
_productBusinessLogicContract.UpdateProduct(_mapper.Map<ProductDataModel>(productModel));
|
||||
return ProductOperationResponse.NoContent();
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return ProductOperationResponse.BadRequest("Data is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return ProductOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (ElementNotFoundException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementNotFoundException");
|
||||
return ProductOperationResponse.BadRequest($"Not found element by Id {productModel.Id}");
|
||||
}
|
||||
catch (ElementExistsException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementExistsException");
|
||||
return ProductOperationResponse.BadRequest(ex.Message);
|
||||
}
|
||||
catch (ElementDeletedException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementDeletedException");
|
||||
return ProductOperationResponse.BadRequest($"Element by id: {productModel.Id} was deleted");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return ProductOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return ProductOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public ProductOperationResponse RemoveProduct(string id)
|
||||
{
|
||||
try
|
||||
{
|
||||
_productBusinessLogicContract.DeleteProduct(id);
|
||||
return ProductOperationResponse.NoContent();
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return ProductOperationResponse.BadRequest("Id is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return ProductOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (ElementNotFoundException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementNotFoundException");
|
||||
return ProductOperationResponse.BadRequest($"Not found element by id: {id}");
|
||||
}
|
||||
catch (ElementDeletedException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementDeletedException");
|
||||
return ProductOperationResponse.BadRequest($"Element by id: {id} was deleted");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return ProductOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return ProductOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
262
TheCatHasPawsProject/CatHasPawsWebApi/Adapters/SaleAdapter.cs
Normal file
262
TheCatHasPawsProject/CatHasPawsWebApi/Adapters/SaleAdapter.cs
Normal file
@@ -0,0 +1,262 @@
|
||||
using AutoMapper;
|
||||
using CatHasPawsContratcs.AdapterContracts;
|
||||
using CatHasPawsContratcs.AdapterContracts.OperationResponses;
|
||||
using CatHasPawsContratcs.BindingModels;
|
||||
using CatHasPawsContratcs.BusinessLogicsContracts;
|
||||
using CatHasPawsContratcs.DataModels;
|
||||
using CatHasPawsContratcs.Exceptions;
|
||||
using CatHasPawsContratcs.ViewModels;
|
||||
|
||||
namespace CatHasPawsWebApi.Adapters;
|
||||
|
||||
public class SaleAdapter : ISaleAdapter
|
||||
{
|
||||
private readonly ISaleBusinessLogicContract _saleBusinessLogicContract;
|
||||
|
||||
private readonly ILogger _logger;
|
||||
|
||||
private readonly Mapper _mapper;
|
||||
|
||||
public SaleAdapter(ISaleBusinessLogicContract saleBusinessLogicContract, ILogger<SaleAdapter> logger)
|
||||
{
|
||||
_saleBusinessLogicContract = saleBusinessLogicContract;
|
||||
_logger = logger;
|
||||
var config = new MapperConfiguration(cfg =>
|
||||
{
|
||||
cfg.CreateMap<SaleBindingModel, SaleDataModel>();
|
||||
cfg.CreateMap<SaleDataModel, SaleViewModel>();
|
||||
cfg.CreateMap<SaleProductBindingModel, SaleProductDataModel>();
|
||||
cfg.CreateMap<SaleProductDataModel, SaleProductViewModel>();
|
||||
});
|
||||
_mapper = new Mapper(config);
|
||||
}
|
||||
|
||||
public SaleOperationResponse GetList(DateTime fromDate, DateTime toDate)
|
||||
{
|
||||
try
|
||||
{
|
||||
return SaleOperationResponse.OK([.. _saleBusinessLogicContract.GetAllSalesByPeriod(fromDate, toDate).Select(x => _mapper.Map<SaleViewModel>(x))]);
|
||||
}
|
||||
catch (IncorrectDatesException ex)
|
||||
{
|
||||
_logger.LogError(ex, "IncorrectDatesException");
|
||||
return SaleOperationResponse.BadRequest($"Incorrect dates: {ex.Message}");
|
||||
}
|
||||
catch (NullListException)
|
||||
{
|
||||
_logger.LogError("NullListException");
|
||||
return SaleOperationResponse.NotFound("The list is not initialized");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return SaleOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return SaleOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public SaleOperationResponse GetWorkerList(string id, DateTime fromDate, DateTime toDate)
|
||||
{
|
||||
try
|
||||
{
|
||||
return SaleOperationResponse.OK([.. _saleBusinessLogicContract.GetAllSalesByWorkerByPeriod(id, fromDate, toDate).Select(x => _mapper.Map<SaleViewModel>(x))]);
|
||||
}
|
||||
catch (IncorrectDatesException ex)
|
||||
{
|
||||
_logger.LogError(ex, "IncorrectDatesException");
|
||||
return SaleOperationResponse.BadRequest($"Incorrect dates: {ex.Message}");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return SaleOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (NullListException)
|
||||
{
|
||||
_logger.LogError("NullListException");
|
||||
return SaleOperationResponse.NotFound("The list is not initialized");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return SaleOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return SaleOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public SaleOperationResponse GetBuyerList(string id, DateTime fromDate, DateTime toDate)
|
||||
{
|
||||
try
|
||||
{
|
||||
return SaleOperationResponse.OK([.. _saleBusinessLogicContract.GetAllSalesByBuyerByPeriod(id, fromDate, toDate).Select(x => _mapper.Map<SaleViewModel>(x))]);
|
||||
}
|
||||
catch (IncorrectDatesException ex)
|
||||
{
|
||||
_logger.LogError(ex, "IncorrectDatesException");
|
||||
return SaleOperationResponse.BadRequest($"Incorrect dates: {ex.Message}");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return SaleOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (NullListException)
|
||||
{
|
||||
_logger.LogError("NullListException");
|
||||
return SaleOperationResponse.NotFound("The list is not initialized");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return SaleOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return SaleOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public SaleOperationResponse GetProductList(string id, DateTime fromDate, DateTime toDate)
|
||||
{
|
||||
try
|
||||
{
|
||||
return SaleOperationResponse.OK([.. _saleBusinessLogicContract.GetAllSalesByProductByPeriod(id, fromDate, toDate).Select(x => _mapper.Map<SaleViewModel>(x))]);
|
||||
}
|
||||
catch (IncorrectDatesException ex)
|
||||
{
|
||||
_logger.LogError(ex, "IncorrectDatesException");
|
||||
return SaleOperationResponse.BadRequest($"Incorrect dates: {ex.Message}");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return SaleOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (NullListException)
|
||||
{
|
||||
_logger.LogError("NullListException");
|
||||
return SaleOperationResponse.NotFound("The list is not initialized");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return SaleOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return SaleOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public SaleOperationResponse GetElement(string id)
|
||||
{
|
||||
try
|
||||
{
|
||||
return SaleOperationResponse.OK(_mapper.Map<SaleViewModel>(_saleBusinessLogicContract.GetSaleByData(id)));
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return SaleOperationResponse.BadRequest("Data is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return SaleOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (ElementNotFoundException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementNotFoundException");
|
||||
return SaleOperationResponse.NotFound($"Not found element by data {id}");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return SaleOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return SaleOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public SaleOperationResponse MakeSale(SaleBindingModel saleModel)
|
||||
{
|
||||
try
|
||||
{
|
||||
var data = _mapper.Map<SaleDataModel>(saleModel);
|
||||
_saleBusinessLogicContract.InsertSale(_mapper.Map<SaleDataModel>(saleModel));
|
||||
return SaleOperationResponse.NoContent();
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return SaleOperationResponse.BadRequest("Data is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return SaleOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return SaleOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return SaleOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public SaleOperationResponse CancelSale(string id)
|
||||
{
|
||||
try
|
||||
{
|
||||
_saleBusinessLogicContract.CancelSale(id);
|
||||
return SaleOperationResponse.NoContent();
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return SaleOperationResponse.BadRequest("Id is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return SaleOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (ElementNotFoundException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementNotFoundException");
|
||||
return SaleOperationResponse.BadRequest($"Not found element by id: {id}");
|
||||
}
|
||||
catch (ElementDeletedException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementDeletedException");
|
||||
return SaleOperationResponse.BadRequest($"Element by id: {id} was deleted");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return SaleOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return SaleOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
278
TheCatHasPawsProject/CatHasPawsWebApi/Adapters/WorkerAdapter.cs
Normal file
278
TheCatHasPawsProject/CatHasPawsWebApi/Adapters/WorkerAdapter.cs
Normal file
@@ -0,0 +1,278 @@
|
||||
using AutoMapper;
|
||||
using CatHasPawsContratcs.AdapterContracts;
|
||||
using CatHasPawsContratcs.AdapterContracts.OperationResponses;
|
||||
using CatHasPawsContratcs.BindingModels;
|
||||
using CatHasPawsContratcs.BusinessLogicsContracts;
|
||||
using CatHasPawsContratcs.DataModels;
|
||||
using CatHasPawsContratcs.Exceptions;
|
||||
using CatHasPawsContratcs.ViewModels;
|
||||
|
||||
namespace CatHasPawsWebApi.Adapters;
|
||||
|
||||
public class WorkerAdapter : IWorkerAdapter
|
||||
{
|
||||
private readonly IWorkerBusinessLogicContract _buyerBusinessLogicContract;
|
||||
|
||||
private readonly ILogger _logger;
|
||||
|
||||
private readonly Mapper _mapper;
|
||||
|
||||
public WorkerAdapter(IWorkerBusinessLogicContract workerBusinessLogicContract, ILogger<WorkerAdapter> logger)
|
||||
{
|
||||
_buyerBusinessLogicContract = workerBusinessLogicContract;
|
||||
_logger = logger;
|
||||
var config = new MapperConfiguration(cfg =>
|
||||
{
|
||||
cfg.CreateMap<WorkerBindingModel, WorkerDataModel>();
|
||||
cfg.CreateMap<WorkerDataModel, WorkerViewModel>();
|
||||
});
|
||||
_mapper = new Mapper(config);
|
||||
}
|
||||
|
||||
public WorkerOperationResponse GetList(bool includeDeleted)
|
||||
{
|
||||
try
|
||||
{
|
||||
return WorkerOperationResponse.OK([.. _buyerBusinessLogicContract.GetAllWorkers(!includeDeleted).Select(x => _mapper.Map<WorkerViewModel>(x))]);
|
||||
}
|
||||
catch (NullListException)
|
||||
{
|
||||
_logger.LogError("NullListException");
|
||||
return WorkerOperationResponse.NotFound("The list is not initialized");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return WorkerOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return WorkerOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public WorkerOperationResponse GetPostList(string id, bool includeDeleted)
|
||||
{
|
||||
try
|
||||
{
|
||||
return WorkerOperationResponse.OK([.. _buyerBusinessLogicContract.GetAllWorkersByPost(id, !includeDeleted).Select(x => _mapper.Map<WorkerViewModel>(x))]);
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return WorkerOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (NullListException)
|
||||
{
|
||||
_logger.LogError("NullListException");
|
||||
return WorkerOperationResponse.NotFound("The list is not initialized");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return WorkerOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return WorkerOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public WorkerOperationResponse GetListByBirthDate(DateTime fromDate, DateTime toDate, bool includeDeleted)
|
||||
{
|
||||
try
|
||||
{
|
||||
return WorkerOperationResponse.OK([.. _buyerBusinessLogicContract.GetAllWorkersByBirthDate(fromDate, toDate, !includeDeleted).Select(x => _mapper.Map<WorkerViewModel>(x))]);
|
||||
}
|
||||
catch (IncorrectDatesException ex)
|
||||
{
|
||||
_logger.LogError(ex, "IncorrectDatesException");
|
||||
return WorkerOperationResponse.BadRequest($"Incorrect dates: {ex.Message}");
|
||||
}
|
||||
catch (NullListException)
|
||||
{
|
||||
_logger.LogError("NullListException");
|
||||
return WorkerOperationResponse.NotFound("The list is not initialized");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return WorkerOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return WorkerOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public WorkerOperationResponse GetListByEmploymentDate(DateTime fromDate, DateTime toDate, bool includeDeleted)
|
||||
{
|
||||
try
|
||||
{
|
||||
return WorkerOperationResponse.OK([.. _buyerBusinessLogicContract.GetAllWorkersByEmploymentDate(fromDate, toDate, !includeDeleted).Select(x => _mapper.Map<WorkerViewModel>(x))]);
|
||||
}
|
||||
catch (IncorrectDatesException ex)
|
||||
{
|
||||
_logger.LogError(ex, "IncorrectDatesException");
|
||||
return WorkerOperationResponse.BadRequest($"Incorrect dates: {ex.Message}");
|
||||
}
|
||||
catch (NullListException)
|
||||
{
|
||||
_logger.LogError("NullListException");
|
||||
return WorkerOperationResponse.NotFound("The list is not initialized");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return WorkerOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return WorkerOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public WorkerOperationResponse GetElement(string data)
|
||||
{
|
||||
try
|
||||
{
|
||||
return WorkerOperationResponse.OK(_mapper.Map<WorkerViewModel>(_buyerBusinessLogicContract.GetWorkerByData(data)));
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return WorkerOperationResponse.BadRequest("Data is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return WorkerOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (ElementNotFoundException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementNotFoundException");
|
||||
return WorkerOperationResponse.NotFound($"Not found element by data {data}");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return WorkerOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return WorkerOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public WorkerOperationResponse RegisterWorker(WorkerBindingModel workerModel)
|
||||
{
|
||||
try
|
||||
{
|
||||
_buyerBusinessLogicContract.InsertWorker(_mapper.Map<WorkerDataModel>(workerModel));
|
||||
return WorkerOperationResponse.NoContent();
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return WorkerOperationResponse.BadRequest("Data is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return WorkerOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (ElementExistsException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementExistsException");
|
||||
return WorkerOperationResponse.BadRequest(ex.Message);
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return WorkerOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return WorkerOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public WorkerOperationResponse ChangeWorkerInfo(WorkerBindingModel workerModel)
|
||||
{
|
||||
try
|
||||
{
|
||||
_buyerBusinessLogicContract.UpdateWorker(_mapper.Map<WorkerDataModel>(workerModel));
|
||||
return WorkerOperationResponse.NoContent();
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return WorkerOperationResponse.BadRequest("Data is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return WorkerOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (ElementNotFoundException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementNotFoundException");
|
||||
return WorkerOperationResponse.BadRequest($"Not found element by Id {workerModel.Id}");
|
||||
}
|
||||
catch (ElementExistsException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementExistsException");
|
||||
return WorkerOperationResponse.BadRequest(ex.Message);
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return WorkerOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return WorkerOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public WorkerOperationResponse RemoveWorker(string id)
|
||||
{
|
||||
try
|
||||
{
|
||||
_buyerBusinessLogicContract.DeleteWorker(id);
|
||||
return WorkerOperationResponse.NoContent();
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return WorkerOperationResponse.BadRequest("Id is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return WorkerOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (ElementNotFoundException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementNotFoundException");
|
||||
return WorkerOperationResponse.BadRequest($"Not found element by id: {id}");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return WorkerOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return WorkerOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
12
TheCatHasPawsProject/CatHasPawsWebApi/AuthOptions.cs
Normal file
12
TheCatHasPawsProject/CatHasPawsWebApi/AuthOptions.cs
Normal file
@@ -0,0 +1,12 @@
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using System.Text;
|
||||
|
||||
namespace CatHasPawsWebApi;
|
||||
|
||||
public class AuthOptions
|
||||
{
|
||||
public const string ISSUER = "CatHasPaws_AuthServer"; // издатель токена
|
||||
public const string AUDIENCE = "CatHasPaws_AuthClient"; // потребитель токена
|
||||
const string KEY = "catsecret_secretsecretsecretkey!123"; // ключ для шифрации
|
||||
public static SymmetricSecurityKey GetSymmetricSecurityKey() => new(Encoding.UTF8.GetBytes(KEY));
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net9.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="9.0.2" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="9.0.2" />
|
||||
<PackageReference Include="Serilog.AspNetCore" Version="9.0.0" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\CatHasPawsBusinessLogic\CatHasPawsBusinessLogic.csproj" />
|
||||
<ProjectReference Include="..\CatHasPawsContratcs\CatHasPawsContratcs.csproj" />
|
||||
<ProjectReference Include="..\CatHasPawsDatabase\CatHasPawsDatabase.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<InternalsVisibleTo Include="CatHasPawsTests" />
|
||||
<InternalsVisibleTo Include="DynamicProxyGenAssembly2" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,6 @@
|
||||
@CatHasPawsWebApi_HostAddress = http://localhost:5037
|
||||
|
||||
GET {{CatHasPawsWebApi_HostAddress}}/weatherforecast/
|
||||
Accept: application/json
|
||||
|
||||
###
|
||||
@@ -0,0 +1,45 @@
|
||||
using CatHasPawsContratcs.AdapterContracts;
|
||||
using CatHasPawsContratcs.BindingModels;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace CatHasPawsWebApi.Controllers;
|
||||
|
||||
[Authorize]
|
||||
[Route("api/[controller]")]
|
||||
[ApiController]
|
||||
[Produces("application/json")]
|
||||
public class BuyersController(IBuyerAdapter adapter) : ControllerBase
|
||||
{
|
||||
private readonly IBuyerAdapter _adapter = adapter;
|
||||
|
||||
[HttpGet]
|
||||
public IActionResult GetAllRecords()
|
||||
{
|
||||
return _adapter.GetList().GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpGet("{data}")]
|
||||
public IActionResult GetRecord(string data)
|
||||
{
|
||||
return _adapter.GetElement(data).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
public IActionResult Register([FromBody] BuyerBindingModel model)
|
||||
{
|
||||
return _adapter.RegisterBuyer(model).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpPut]
|
||||
public IActionResult ChangeInfo([FromBody] BuyerBindingModel model)
|
||||
{
|
||||
return _adapter.ChangeBuyerInfo(model).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpDelete("{id}")]
|
||||
public IActionResult Delete(string id)
|
||||
{
|
||||
return _adapter.RemoveBuyer(id).GetResponse(Request, Response);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
using CatHasPawsContratcs.AdapterContracts;
|
||||
using CatHasPawsContratcs.BindingModels;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace CatHasPawsWebApi.Controllers;
|
||||
|
||||
[Authorize]
|
||||
[Route("api/[controller]")]
|
||||
[ApiController]
|
||||
[Produces("application/json")]
|
||||
public class ManufacturersController(IManufacturerAdapter adapter) : ControllerBase
|
||||
{
|
||||
private readonly IManufacturerAdapter _adapter = adapter;
|
||||
|
||||
[HttpGet]
|
||||
public IActionResult GetAllRecords()
|
||||
{
|
||||
return _adapter.GetList().GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpGet("{data}")]
|
||||
public IActionResult GetRecord(string data)
|
||||
{
|
||||
return _adapter.GetElement(data).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
public IActionResult Register([FromBody] ManufacturerBindingModel model)
|
||||
{
|
||||
return _adapter.RegisterManufacturer(model).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpPut]
|
||||
public IActionResult ChangeInfo([FromBody] ManufacturerBindingModel model)
|
||||
{
|
||||
return _adapter.ChangeManufacturerInfo(model).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpDelete("{id}")]
|
||||
public IActionResult Delete(string id)
|
||||
{
|
||||
return _adapter.RemoveManufacturer(id).GetResponse(Request, Response);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
using CatHasPawsContratcs.AdapterContracts;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace CatHasPawsWebApi.Controllers;
|
||||
|
||||
[Authorize]
|
||||
[Route("api/[controller]")]
|
||||
[ApiController]
|
||||
[Produces("application/json")]
|
||||
public class PostHistoryController(IPostAdapter adapter) : ControllerBase
|
||||
{
|
||||
private readonly IPostAdapter _adapter = adapter;
|
||||
|
||||
[HttpGet("{id}")]
|
||||
public IActionResult GetHistory(string id)
|
||||
{
|
||||
return _adapter.GetHistory(id).GetResponse(Request, Response);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
using CatHasPawsContratcs.AdapterContracts;
|
||||
using CatHasPawsContratcs.BindingModels;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace CatHasPawsWebApi.Controllers;
|
||||
|
||||
[Authorize]
|
||||
[Route("api/[controller]")]
|
||||
[ApiController]
|
||||
[Produces("application/json")]
|
||||
public class PostsController(IPostAdapter adapter) : ControllerBase
|
||||
{
|
||||
private readonly IPostAdapter _adapter = adapter;
|
||||
|
||||
[HttpGet]
|
||||
public IActionResult GetRecords()
|
||||
{
|
||||
return _adapter.GetList().GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpGet("{data}")]
|
||||
public IActionResult GetRecord(string data)
|
||||
{
|
||||
return _adapter.GetElement(data).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
public IActionResult Register([FromBody] PostBindingModel model)
|
||||
{
|
||||
return _adapter.RegisterPost(model).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpPut]
|
||||
public IActionResult ChangeInfo([FromBody] PostBindingModel model)
|
||||
{
|
||||
return _adapter.ChangePostInfo(model).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpDelete("{id}")]
|
||||
public IActionResult Delete(string id)
|
||||
{
|
||||
return _adapter.RemovePost(id).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpPatch("{id}")]
|
||||
public IActionResult Restore(string id)
|
||||
{
|
||||
return _adapter.RestorePost(id).GetResponse(Request, Response);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
using CatHasPawsContratcs.AdapterContracts;
|
||||
using CatHasPawsContratcs.BindingModels;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace CatHasPawsWebApi.Controllers;
|
||||
|
||||
[Authorize]
|
||||
[Route("api/[controller]/[action]")]
|
||||
[ApiController]
|
||||
[Produces("application/json")]
|
||||
public class ProductsController(IProductAdapter adapter) : ControllerBase
|
||||
{
|
||||
private readonly IProductAdapter _adapter = adapter;
|
||||
|
||||
[HttpGet]
|
||||
public IActionResult GetRecords(bool includeDeleted)
|
||||
{
|
||||
return _adapter.GetList(includeDeleted).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
public IActionResult GetManufacturerRecords(string id, bool includeDeleted)
|
||||
{
|
||||
return _adapter.GetManufacturerList(id, includeDeleted).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
public IActionResult GetHistory(string id)
|
||||
{
|
||||
return _adapter.GetHistory(id).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpGet("{data}")]
|
||||
public IActionResult GetRecord(string data)
|
||||
{
|
||||
return _adapter.GetElement(data).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
public IActionResult Register([FromBody] ProductBindingModel model)
|
||||
{
|
||||
return _adapter.RegisterProduct(model).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpPut]
|
||||
public IActionResult ChangeInfo([FromBody] ProductBindingModel model)
|
||||
{
|
||||
return _adapter.ChangeProductInfo(model).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpDelete("{id}")]
|
||||
public IActionResult Delete(string id)
|
||||
{
|
||||
return _adapter.RemoveProduct(id).GetResponse(Request, Response);
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user