5 Commits

99 changed files with 6982 additions and 1014 deletions

View File

@@ -8,11 +8,12 @@
<ItemGroup>
<InternalsVisibleTo Include="TheBlacksmithVakulaTests" />
<InternalsVisibleTo Include="TheBlacksmithVakulaWebApi" />
<InternalsVisibleTo Include="DinamicProxyGenAssembly2" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging" Version="9.0.2" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="9.0.4" />
</ItemGroup>
<ItemGroup>

View File

@@ -11,6 +11,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TheBlacksmithVakulaBusiness
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TheBlacksmithVakulaDatabase", "TheBlacksmithVakulaDatabase\TheBlacksmithVakulaDatabase.csproj", "{A68C4088-F1BD-47E6-8E14-8BCA8AE86B52}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TheBlacksmithVakulaWebApi", "TheBlacksmithVakulaWebApi\TheBlacksmithVakulaWebApi.csproj", "{19350294-4EF7-4476-9418-A119EF83CDE4}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@@ -33,8 +35,15 @@ Global
{A68C4088-F1BD-47E6-8E14-8BCA8AE86B52}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A68C4088-F1BD-47E6-8E14-8BCA8AE86B52}.Release|Any CPU.ActiveCfg = Release|Any CPU
{A68C4088-F1BD-47E6-8E14-8BCA8AE86B52}.Release|Any CPU.Build.0 = Release|Any CPU
{19350294-4EF7-4476-9418-A119EF83CDE4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{19350294-4EF7-4476-9418-A119EF83CDE4}.Debug|Any CPU.Build.0 = Debug|Any CPU
{19350294-4EF7-4476-9418-A119EF83CDE4}.Release|Any CPU.ActiveCfg = Release|Any CPU
{19350294-4EF7-4476-9418-A119EF83CDE4}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {D78097F2-2881-49D7-A49C-DFD5B169283B}
EndGlobalSection
EndGlobal

View File

@@ -0,0 +1,18 @@
using TheBlacksmithVakulaContract.AdapterContracts.OperationResponses;
using TheBlacksmithVakulaContract.BindingModels;
namespace TheBlacksmithVakulaContract.AdapterContracts
{
public interface IBilletAdapter
{
BilletOperationResponse GetList();
BilletOperationResponse GetElement(string data);
BilletOperationResponse RegisterBillet(BilletBindingModel billetModel);
BilletOperationResponse ChangeBilletInfo(BilletBindingModel billetModel);
BilletOperationResponse RemoveBillet(string id);
}
}

View File

@@ -0,0 +1,24 @@
using TheBlacksmithVakulaContract.AdapterContracts.OperationResponses;
using TheBlacksmithVakulaContract.BindingModels;
namespace TheBlacksmithVakulaContract.AdapterContracts
{
public interface IBlacksmithAdapter
{
BlacksmithOperationResponse GetList(bool includeDeleted);
BlacksmithOperationResponse GetRankList(string id, bool includeDeleted);
BlacksmithOperationResponse GetListByBirthDate(DateTime fromDate, DateTime toDate, bool includeDeleted);
BlacksmithOperationResponse GetListByEmploymentDate(DateTime fromDate, DateTime toDate, bool includeDeleted);
BlacksmithOperationResponse GetElement(string data);
BlacksmithOperationResponse RegisterBlacksmith(BlacksmithBindingModel blacksmithModel);
BlacksmithOperationResponse ChangeBlacksmithInfo(BlacksmithBindingModel blacksmithModel);
BlacksmithOperationResponse RemoveBlacksmith(string id);
}
}

View File

@@ -0,0 +1,18 @@
using TheBlacksmithVakulaContract.AdapterContracts.OperationResponses;
using TheBlacksmithVakulaContract.BindingModels;
namespace TheBlacksmithVakulaContract.AdapterContracts
{
public interface IBuyerAdapter
{
BuyerOperationResponse GetList();
BuyerOperationResponse GetElement(string data);
BuyerOperationResponse RegisterBuyer(BuyerBindingModel buyerModel);
BuyerOperationResponse ChangeBuyerInfo(BuyerBindingModel buyerModel);
BuyerOperationResponse RemoveBuyer(string id);
}
}

View File

@@ -0,0 +1,22 @@
using TheBlacksmithVakulaContract.AdapterContracts.OperationResponses;
using TheBlacksmithVakulaContract.BindingModels;
namespace TheBlacksmithVakulaContract.AdapterContracts
{
public interface IOrderAdapter
{
OrderOperationResponse GetList(DateTime fromDate, DateTime toDate);
OrderOperationResponse GetBlacksmithList(string id, DateTime fromDate, DateTime toDate);
OrderOperationResponse GetBuyerList(string id, DateTime fromDate, DateTime toDate);
OrderOperationResponse GetProductList(string id, DateTime fromDate, DateTime toDate);
OrderOperationResponse GetElement(string id);
OrderOperationResponse MakeOrder(OrderBindingModel orderModel);
OrderOperationResponse CancelOrder(string id);
}
}

View File

@@ -0,0 +1,22 @@
using TheBlacksmithVakulaContract.AdapterContracts.OperationResponses;
using TheBlacksmithVakulaContract.BindingModels;
namespace TheBlacksmithVakulaContract.AdapterContracts
{
public interface IProductAdapter
{
ProductOperationResponse GetList(bool includeDeleted);
ProductOperationResponse GetBilletList(string id, bool includeDeleted);
ProductOperationResponse GetHistory(string id);
ProductOperationResponse GetElement(string data);
ProductOperationResponse RegisterProduct(ProductBindingModel productModel);
ProductOperationResponse ChangeProductInfo(ProductBindingModel productModel);
ProductOperationResponse RemoveProduct(string id);
}
}

View File

@@ -0,0 +1,22 @@
using TheBlacksmithVakulaContract.AdapterContracts.OperationResponses;
using TheBlacksmithVakulaContract.BindingModels;
namespace TheBlacksmithVakulaContract.AdapterContracts
{
public interface IRankAdapter
{
RankOperationResponse GetList();
RankOperationResponse GetHistory(string id);
RankOperationResponse GetElement(string data);
RankOperationResponse RegisterRank(RankBindingModel rankModel);
RankOperationResponse ChangeRankInfo(RankBindingModel rankModel);
RankOperationResponse RemoveRank(string id);
RankOperationResponse RestoreRank(string id);
}
}

View File

@@ -0,0 +1,13 @@
using TheBlacksmithVakulaContract.AdapterContracts.OperationResponses;
namespace TheBlacksmithVakulaContract.AdapterContracts
{
public interface ISalaryAdapter
{
SalaryOperationResponse GetListByPeriod(DateTime fromDate, DateTime toDate);
SalaryOperationResponse GetListByPeriodByBlacksmith(DateTime fromDate, DateTime toDate, string blacksmithId);
SalaryOperationResponse CalculateSalary(DateTime date);
}
}

View File

@@ -0,0 +1,20 @@
using TheBlacksmithVakulaContract.Infrastructure;
using TheBlacksmithVakulaContract.ViewModels;
namespace TheBlacksmithVakulaContract.AdapterContracts.OperationResponses
{
public class BilletOperationResponse : OperationResponse
{
public static BilletOperationResponse OK(List<BilletViewModel> data) => OK<BilletOperationResponse, List<BilletViewModel>>(data);
public static BilletOperationResponse OK(BilletViewModel data) => OK<BilletOperationResponse, BilletViewModel>(data);
public static BilletOperationResponse NoContent() => NoContent<BilletOperationResponse>();
public static BilletOperationResponse NotFound(string message) => NotFound<BilletOperationResponse>(message);
public static BilletOperationResponse BadRequest(string message) => BadRequest<BilletOperationResponse>(message);
public static BilletOperationResponse InternalServerError(string message) => InternalServerError<BilletOperationResponse>(message);
}
}

View File

@@ -0,0 +1,20 @@
using TheBlacksmithVakulaContract.Infrastructure;
using TheBlacksmithVakulaContract.ViewModels;
namespace TheBlacksmithVakulaContract.AdapterContracts.OperationResponses
{
public class BlacksmithOperationResponse : OperationResponse
{
public static BlacksmithOperationResponse OK(List<BlacksmithViewModel> data) => OK<BlacksmithOperationResponse, List<BlacksmithViewModel>>(data);
public static BlacksmithOperationResponse OK(BlacksmithViewModel data) => OK<BlacksmithOperationResponse, BlacksmithViewModel>(data);
public static BlacksmithOperationResponse NoContent() => NoContent<BlacksmithOperationResponse>();
public static BlacksmithOperationResponse NotFound(string message) => NotFound<BlacksmithOperationResponse>(message);
public static BlacksmithOperationResponse BadRequest(string message) => BadRequest<BlacksmithOperationResponse>(message);
public static BlacksmithOperationResponse InternalServerError(string message) => InternalServerError<BlacksmithOperationResponse>(message);
}
}

View File

@@ -0,0 +1,20 @@
using TheBlacksmithVakulaContract.Infrastructure;
using TheBlacksmithVakulaContract.ViewModels;
namespace TheBlacksmithVakulaContract.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);
}
}

View File

@@ -0,0 +1,20 @@
using TheBlacksmithVakulaContract.Infrastructure;
using TheBlacksmithVakulaContract.ViewModels;
namespace TheBlacksmithVakulaContract.AdapterContracts.OperationResponses
{
public class OrderOperationResponse : OperationResponse
{
public static OrderOperationResponse OK(List<OrderViewModel> data) => OK<OrderOperationResponse, List<OrderViewModel>>(data);
public static OrderOperationResponse OK(OrderViewModel data) => OK<OrderOperationResponse, OrderViewModel>(data);
public static OrderOperationResponse NoContent() => NoContent<OrderOperationResponse>();
public static OrderOperationResponse NotFound(string message) => NotFound<OrderOperationResponse>(message);
public static OrderOperationResponse BadRequest(string message) => BadRequest<OrderOperationResponse>(message);
public static OrderOperationResponse InternalServerError(string message) => InternalServerError<OrderOperationResponse>(message);
}
}

View File

@@ -0,0 +1,22 @@
using TheBlacksmithVakulaContract.Infrastructure;
using TheBlacksmithVakulaContract.ViewModels;
namespace TheBlacksmithVakulaContract.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);
}
}

View File

@@ -0,0 +1,20 @@
using TheBlacksmithVakulaContract.Infrastructure;
using TheBlacksmithVakulaContract.ViewModels;
namespace TheBlacksmithVakulaContract.AdapterContracts.OperationResponses
{
public class RankOperationResponse : OperationResponse
{
public static RankOperationResponse OK(List<RankViewModel> data) => OK<RankOperationResponse, List<RankViewModel>>(data);
public static RankOperationResponse OK(RankViewModel data) => OK<RankOperationResponse, RankViewModel>(data);
public static RankOperationResponse NoContent() => NoContent<RankOperationResponse>();
public static RankOperationResponse NotFound(string message) => NotFound<RankOperationResponse>(message);
public static RankOperationResponse BadRequest(string message) => BadRequest<RankOperationResponse>(message);
public static RankOperationResponse InternalServerError(string message) => InternalServerError<RankOperationResponse>(message);
}
}

View File

@@ -0,0 +1,18 @@
using TheBlacksmithVakulaContract.Infrastructure;
using TheBlacksmithVakulaContract.ViewModels;
namespace TheBlacksmithVakulaContract.AdapterContracts.OperationResponses
{
public class SalaryOperationResponse : OperationResponse
{
public static SalaryOperationResponse OK(List<SalaryViewModel> data) => OK<SalaryOperationResponse, List<SalaryViewModel>>(data);
public static SalaryOperationResponse NoContent() => NoContent<SalaryOperationResponse>();
public static SalaryOperationResponse NotFound(string message) => NotFound<SalaryOperationResponse>(message);
public static SalaryOperationResponse BadRequest(string message) => BadRequest<SalaryOperationResponse>(message);
public static SalaryOperationResponse InternalServerError(string message) => InternalServerError<SalaryOperationResponse>(message);
}
}

View File

@@ -0,0 +1,9 @@
namespace TheBlacksmithVakulaContract.BindingModels
{
public class BilletBindingModel
{
public string? Id { get; set; }
public string? BilletName { get; set; }
}
}

View File

@@ -0,0 +1,15 @@
namespace TheBlacksmithVakulaContract.BindingModels
{
public class BlacksmithBindingModel
{
public string? Id { get; set; }
public string? FIO { get; set; }
public string? RankId { get; set; }
public DateTime BirthDate { get; set; }
public DateTime EmploymentDate { get; set; }
}
}

View File

@@ -0,0 +1,13 @@
namespace TheBlacksmithVakulaContract.BindingModels
{
public class BuyerBindingModel
{
public string? Id { get; set; }
public string? FIO { get; set; }
public string? PhoneNumber { get; set; }
public double DiscountSize { get; set; }
}
}

View File

@@ -0,0 +1,15 @@
namespace TheBlacksmithVakulaContract.BindingModels
{
public class OrderBindingModel
{
public string? Id { get; set; }
public string? BlacksmithId { get; set; }
public string? BuyerId { get; set; }
public int DiscountType { get; set; }
public List<OrderProductBindingModel>? Products { get; set; }
}
}

View File

@@ -0,0 +1,11 @@
namespace TheBlacksmithVakulaContract.BindingModels
{
public class OrderProductBindingModel
{
public string? OrderId { get; set; }
public string? ProductId { get; set; }
public int Count { get; set; }
}
}

View File

@@ -0,0 +1,15 @@
namespace TheBlacksmithVakulaContract.BindingModels
{
public class ProductBindingModel
{
public string? Id { get; set; }
public string? ProductName { get; set; }
public string? ProductType { get; set; }
public string? BilletId { get; set; }
public double Price { get; set; }
}
}

View File

@@ -0,0 +1,13 @@
namespace TheBlacksmithVakulaContract.BindingModels
{
public class RankBindingModel
{
public string? Id { get; set; }
public string? RankId => Id;
public string? RankName { get; set; }
public string? RankType { get; set; }
}
}

View File

@@ -4,15 +4,17 @@ using TheBlacksmithVakulaContract.Infrastructure;
namespace TheBlacksmithVakulaContract.DataModels
{
public class BilletDataModel(string id, string billetName, string prevBilletName, string prevPrevBilletName) : IValidation
public class BilletDataModel(string id, string billetName, string? prevBilletName, string? prevPrevBilletName) : IValidation
{
public string Id { get; private set; } = id;
public string BilletName { get; private set; } = billetName;
public string PrevBilletName { get; private set; } = prevBilletName;
public string? PrevBilletName { get; private set; } = prevBilletName;
public string PrevPrevBilletName { get; private set; } = prevPrevBilletName;
public string? PrevPrevBilletName { get; private set; } = prevPrevBilletName;
public BilletDataModel(string id, string billetName) : this(id, billetName, null, null) { }
public void Validate()
{

View File

@@ -6,6 +6,8 @@ namespace TheBlacksmithVakulaContract.DataModels
{
public class BlacksmithDataModel(string id, string fio, string rankId, DateTime birthDate, DateTime employmentDate, bool isDeleted) : IValidation
{
private readonly RankDataModel? _rank;
public string Id { get; private set; } = id;
public string FIO { get; private set; } = fio;
@@ -18,6 +20,16 @@ namespace TheBlacksmithVakulaContract.DataModels
public bool IsDeleted { get; private set; } = isDeleted;
public string RankName => _rank?.RankName ?? string.Empty;
public BlacksmithDataModel(string id, string fio, string rankId, DateTime birthDate, DateTime employmentDate, bool isDeleted, RankDataModel rank) : this(id, fio, rankId, birthDate, employmentDate, isDeleted)
{
_rank = rank;
}
public BlacksmithDataModel(string id, string fio, string rankId, DateTime birthDate, DateTime employmentDate) : this(id, fio, rankId, birthDate, employmentDate, false) { }
public void Validate()
{
if (Id.IsEmpty())

View File

@@ -5,26 +5,76 @@ using TheBlacksmithVakulaContract.Infrastructure;
namespace TheBlacksmithVakulaContract.DataModels
{
public class OrderDataModel(string id, string blacksmithId, string? buyerId, double sum, DiscountType discountType,
double discount, bool isCancel, List<OrderProductDataModel> OrderProducts) : IValidation
public class OrderDataModel : IValidation
{
public string Id { get; private set; } = id;
private readonly BuyerDataModel? _buyer;
public string BlacksmithId { get; private set; } = blacksmithId;
private readonly BlacksmithDataModel? _blacksmith;
public string? BuyerId { get; private set; } = buyerId;
public string Id { get; private set; }
public string BlacksmithId { get; private set; }
public string? BuyerId { get; private set; }
public DateTime OrderDate { 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<OrderProductDataModel> Products { get; private set; } = OrderProducts;
public List<OrderProductDataModel> Products { get; private set; }
public string BuyerFIO => _buyer?.FIO ?? string.Empty;
public string BlacksmithFIO => _blacksmith?.FIO ?? string.Empty;
public OrderDataModel(string id, string blacksmithId, string? buyerId, DiscountType discountType, bool isCancel, List<OrderProductDataModel> orderProducts)
{
Id = id;
BlacksmithId = blacksmithId;
BuyerId = buyerId;
DiscountType = discountType;
IsCancel = isCancel;
Products = orderProducts;
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 => 1000 * x.Count) ?? 0;
Discount = Sum * percent;
}
public OrderDataModel(string id, string blacksmithId, string? buyerId, double sum, DiscountType discountType, double discount, bool isCancel, List<OrderProductDataModel> orderProducts, BlacksmithDataModel? blacksmith, BuyerDataModel? buyer) : this(id, blacksmithId, buyerId, discountType, isCancel, orderProducts)
{
Sum = sum;
Discount = discount;
_blacksmith = blacksmith;
_buyer = buyer;
}
public OrderDataModel(string id, string blacksmithId, string? buyerId, int discountType, List<OrderProductDataModel> products) : this(id, blacksmithId, buyerId, (DiscountType)discountType, false, products) { }
public void Validate()
{
@@ -41,7 +91,7 @@ namespace TheBlacksmithVakulaContract.DataModels
if (Sum <= 0)
throw new ValidationException("Field Sum is less than or equal to 0");
if ((Products?.Count ?? 0) == 0)
throw new ValidationException("The sale must include products");
throw new ValidationException("The order must include products");
}
}

View File

@@ -6,12 +6,21 @@ namespace TheBlacksmithVakulaContract.DataModels
{
public class OrderProductDataModel(string orderId, string productId, int count) : IValidation
{
private readonly ProductDataModel? _product;
public string OrderId { get; private set; } = orderId;
public string ProductId { get; private set; } = productId;
public int Count { get; private set; } = count;
public string ProductName => _product?.ProductName ?? string.Empty;
public OrderProductDataModel(string orderId, string productId, int count, ProductDataModel product) : this(orderId, productId, count)
{
_product = product;
}
public void Validate()
{
if (OrderId.IsEmpty())

View File

@@ -8,6 +8,8 @@ namespace TheBlacksmithVakulaContract.DataModels
public class ProductDataModel(string id, string productName, ProductType productType,
string billetId, double price, bool isDeleted) : IValidation
{
private readonly BilletDataModel? _billet;
public string Id { get; private set; } = id;
public string ProductName { get; private set; } = productName;
@@ -20,6 +22,15 @@ namespace TheBlacksmithVakulaContract.DataModels
public bool IsDeleted { get; private set; } = isDeleted;
public string BilletName => _billet?.BilletName ?? string.Empty;
public ProductDataModel(string id, string productName, ProductType productType, string billetId, double price, bool isDeleted, BilletDataModel billet) : this(id, productName, productType, billetId, price, isDeleted)
{
_billet = billet;
}
public ProductDataModel(string id, string productName, ProductType productType, string billetId, double price) : this(id, productName, productType, billetId, price, false) { }
public void Validate()
{
if (Id.IsEmpty())

View File

@@ -6,12 +6,21 @@ namespace TheBlacksmithVakulaContract.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())

View File

@@ -5,7 +5,7 @@ using TheBlacksmithVakulaContract.Infrastructure;
namespace TheBlacksmithVakulaContract.DataModels
{
public class RankDataModel(string rankId, string rankName, RankType rankType, bool isActual, DateTime changeDate) : IValidation
public class RankDataModel(string rankId, string rankName, RankType rankType) : IValidation
{
public string Id { get; private set; } = rankId;
@@ -13,10 +13,6 @@ namespace TheBlacksmithVakulaContract.DataModels
public RankType RankType { get; private set; } = rankType;
public bool IsActual { get; private set; } = isActual;
public DateTime ChangeDate { get; private set; } = changeDate;
public void Validate()
{
if (Id.IsEmpty())

View File

@@ -6,12 +6,21 @@ namespace TheBlacksmithVakulaContract.DataModels
{
public class SalaryDataModel(string blacksmithId, DateTime salaryDate, double blacksmithSalary) : IValidation
{
private readonly BlacksmithDataModel? _blacksmith;
public string BlacksmithId { get; private set; } = blacksmithId;
public DateTime SalaryDate { get; private set; } = salaryDate;
public double Salary { get; private set; } = blacksmithSalary;
public string BlacksmithFIO => _blacksmith?.FIO ?? string.Empty;
public SalaryDataModel(string blacksmithId, DateTime salaryDate, double blacksmithSalary, BlacksmithDataModel blacksmith) : this(blacksmithId, salaryDate, blacksmithSalary)
{
_blacksmith = blacksmith;
}
public void Validate()
{
if (BlacksmithId.IsEmpty())

View File

@@ -0,0 +1,43 @@
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Net;
namespace TheBlacksmithVakulaContract.Infrastructure
{
public class OperationResponse
{
protected HttpStatusCode StatusCode { get; set; }
protected object? Result { get; set; }
public IActionResult GetResponse(HttpRequest request, HttpResponse response)
{
ArgumentNullException.ThrowIfNull(request);
ArgumentNullException.ThrowIfNull(response);
response.StatusCode = (int)StatusCode;
if (Result is null)
{
return new StatusCodeResult((int)StatusCode);
}
return new ObjectResult(Result);
}
protected static TResult OK<TResult, TData>(TData data) where TResult : OperationResponse,
new() => new() { StatusCode = HttpStatusCode.OK, Result = data };
protected static TResult NoContent<TResult>() where TResult : OperationResponse,
new() => new() { StatusCode = HttpStatusCode.NoContent };
protected static TResult BadRequest<TResult>(string? errorMessage = null) where TResult : OperationResponse,
new() => new() { StatusCode = HttpStatusCode.BadRequest, Result = errorMessage };
protected static TResult NotFound<TResult>(string? errorMessage = null) where TResult : OperationResponse,
new() => new() { StatusCode = HttpStatusCode.NotFound, Result = errorMessage };
protected static TResult InternalServerError<TResult>(string? errorMessage = null) where TResult : OperationResponse,
new() => new() { StatusCode = HttpStatusCode.InternalServerError, Result = errorMessage };
}
}

View File

@@ -7,7 +7,10 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging" Version="9.0.2" />
<PackageReference Include="Microsoft.AspNetCore.Http.Abstractions" Version="2.3.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Abstractions" Version="2.3.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Core" Version="2.3.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="9.0.4" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,13 @@
namespace TheBlacksmithVakulaContract.ViewModels
{
public class BilletViewModel
{
public required string Id { get; set; }
public required string BilletName { get; set; }
public string? PrevBilletName { get; set; }
public string? PrevPrevBilletName { get; set; }
}
}

View File

@@ -0,0 +1,19 @@
namespace TheBlacksmithVakulaContract.ViewModels
{
public class BlacksmithViewModel
{
public required string Id { get; set; }
public required string FIO { get; set; }
public required string RankId { get; set; }
public required string RankName { get; set; }
public bool IsDeleted { get; set; }
public DateTime BirthDate { get; set; }
public DateTime EmploymentDate { get; set; }
}
}

View File

@@ -0,0 +1,13 @@
namespace TheBlacksmithVakulaContract.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; }
}
}

View File

@@ -0,0 +1,11 @@
namespace TheBlacksmithVakulaContract.ViewModels
{
public class OrderProductViewModel
{
public required string ProductId { get; set; }
public required string ProductName { get; set; }
public int Count { get; set; }
}
}

View File

@@ -0,0 +1,27 @@
namespace TheBlacksmithVakulaContract.ViewModels
{
public class OrderViewModel
{
public required string Id { get; set; }
public required string BlacksmithId { get; set; }
public required string BlacksmithFIO { get; set; }
public string? BuyerId { get; set; }
public string? BuyerFIO { get; set; }
public DateTime OrderDate { 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<OrderProductViewModel> Products { get; set; }
}
}

View File

@@ -0,0 +1,11 @@
namespace TheBlacksmithVakulaContract.ViewModels
{
public class ProductHistoryViewModel
{
public required string ProductName { get; set; }
public double OldPrice { get; set; }
public DateTime ChangeDate { get; set; }
}
}

View File

@@ -0,0 +1,19 @@
namespace TheBlacksmithVakulaContract.ViewModels
{
public class ProductViewModel
{
public required string Id { get; set; }
public required string ProductName { get; set; }
public required string BilletId { get; set; }
public required string BilletName { get; set; }
public required string ProductType { get; set; }
public double Price { get; set; }
public bool IsDeleted { get; set; }
}
}

View File

@@ -0,0 +1,11 @@
namespace TheBlacksmithVakulaContract.ViewModels
{
public class RankViewModel
{
public required string Id { get; set; }
public required string RankName { get; set; }
public required string RankType { get; set; }
}
}

View File

@@ -0,0 +1,13 @@
namespace TheBlacksmithVakulaContract.ViewModels
{
public class SalaryViewModel
{
public required string BlacksmithId { get; set; }
public required string BlacksmithFIO { get; set; }
public DateTime SalaryDate { get; set; }
public double Salary { get; set; }
}
}

View File

@@ -4,131 +4,147 @@ using TheBlacksmithVakulaContract.Exceptions;
using TheBlacksmithVakulaContract.StoragesContracts;
using TheBlacksmithVakulaDatabase.Models;
namespace TheBlacksmithVakulaDatabase.Implementations
namespace TheBlacksmithVakulaDatabase.Implementations;
internal class BlacksmithStorageContract : IBlacksmithStorageContract
{
internal class BlacksmithStorageContract : IBlacksmithStorageContract
private readonly TheBlacksmithVakulaDbContext _dbContext;
private readonly Mapper _mapper;
public BlacksmithStorageContract(TheBlacksmithVakulaDbContext dbContext)
{
private readonly TheBlacksmithVakulaDbContext _dbContext;
private readonly Mapper _mapper;
public BlacksmithStorageContract(TheBlacksmithVakulaDbContext dbContext)
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Blacksmith, BlacksmithDataModel>();
cfg.CreateMap<BlacksmithDataModel, Blacksmith>();
});
_mapper = new Mapper(config);
}
public List<BlacksmithDataModel> GetList(bool onlyActive = true, string? rankId = null, DateTime? fromBirthDate = null,
DateTime? toBirthDate = null, DateTime? fromEmploymentDate = null, DateTime? toEmploymentDate = null)
{
try
{
var query = _dbContext.Blacksmiths.AsQueryable();
if (onlyActive) query = query.Where(x => !x.IsDeleted);
if (rankId is not null) query = query.Where(x => x.RankId == rankId);
if (fromBirthDate is not null && toBirthDate is not null)
query = query.Where(x => x.BirthDate >= fromBirthDate && x.BirthDate <= toBirthDate);
if (fromEmploymentDate is not null && toEmploymentDate is not null)
query = query.Where(x => x.EmploymentDate >= fromEmploymentDate && x.EmploymentDate <= toEmploymentDate);
return [.. query.Select(x => _mapper.Map<BlacksmithDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public BlacksmithDataModel? GetElementById(string id)
{
try
{
return _mapper.Map<BlacksmithDataModel>(GetBlacksmithById(id));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public BlacksmithDataModel? GetElementByFIO(string fio)
{
try
{
return
_mapper.Map<BlacksmithDataModel>(_dbContext.Blacksmiths.FirstOrDefault(x => x.FIO == fio));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void AddElement(BlacksmithDataModel blacksmithDataModel)
{
try
{
_dbContext.Blacksmiths.Add(_mapper.Map<Blacksmith>(blacksmithDataModel));
_dbContext.SaveChanges();
}
catch (InvalidOperationException ex) when (ex.TargetSite?.Name == "ThrowIdentityConflict")
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("Id", blacksmithDataModel.Id);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void UpdElement(BlacksmithDataModel blacksmithDataModel)
{
try
{
var element = GetBlacksmithById(blacksmithDataModel.Id) ?? throw new ElementNotFoundException(blacksmithDataModel.Id);
_dbContext.Blacksmiths.Update(_mapper.Map(blacksmithDataModel, 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 = GetBlacksmithById(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 Blacksmith? GetBlacksmithById(string id) => _dbContext.Blacksmiths.FirstOrDefault(x => x.Id == id && !x.IsDeleted);
cfg.CreateMap<Rank, RankDataModel>()
.ForMember(x => x.Id, x => x.MapFrom(src => src.RankId));
cfg.CreateMap<Blacksmith, BlacksmithDataModel>();
cfg.CreateMap<BlacksmithDataModel, Blacksmith>();
});
_mapper = new Mapper(config);
}
public List<BlacksmithDataModel> GetList(bool onlyActive = true, string? rankId = null, DateTime? fromBirthDate = null, DateTime? toBirthDate = null, DateTime? fromEmploymentDate = null, DateTime? toEmploymentDate = null)
{
try
{
var query = _dbContext.Blacksmiths.AsQueryable();
if (onlyActive)
{
query = query.Where(x => !x.IsDeleted);
}
if (rankId is not null)
{
query = query.Where(x => x.RankId == rankId);
}
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 [.. JoinRank(query).Select(x => _mapper.Map<BlacksmithDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public BlacksmithDataModel? GetElementById(string id)
{
try
{
return _mapper.Map<BlacksmithDataModel>(GetBlacksmithById(id));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public BlacksmithDataModel? GetElementByFIO(string fio)
{
try
{
return _mapper.Map<BlacksmithDataModel>(AddPost(_dbContext.Blacksmiths.FirstOrDefault(x => x.FIO == fio && !x.IsDeleted)));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void AddElement(BlacksmithDataModel blacksmithDataModel)
{
try
{
_dbContext.Blacksmiths.Add(_mapper.Map<Blacksmith>(blacksmithDataModel));
_dbContext.SaveChanges();
}
catch (InvalidOperationException ex) when (ex.TargetSite?.Name == "ThrowIdentityConflict")
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("Id", blacksmithDataModel.Id);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void UpdElement(BlacksmithDataModel blacksmithDataModel)
{
try
{
var element = GetBlacksmithById(blacksmithDataModel.Id) ?? throw new ElementNotFoundException(blacksmithDataModel.Id);
_dbContext.Blacksmiths.Update(_mapper.Map(blacksmithDataModel, 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 = GetBlacksmithById(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 Blacksmith? GetBlacksmithById(string id) => AddPost(_dbContext.Blacksmiths.FirstOrDefault(x => x.Id == id && !x.IsDeleted));
private IQueryable<Blacksmith> JoinRank(IQueryable<Blacksmith> query)
=> query.GroupJoin(_dbContext.Ranks.Where(x => x.IsActual), x => x.RankId, y => y.RankId, (x, y) => new { Blacksmith = x, Rank = y })
.SelectMany(xy => xy.Rank.DefaultIfEmpty(), (x, y) => x.Blacksmith.AddRank(y));
private Blacksmith? AddPost(Blacksmith? blacksmith)
=> blacksmith?.AddRank(_dbContext.Ranks.FirstOrDefault(x => x.RankId == blacksmith.RankId && x.IsActual));
}

View File

@@ -5,96 +5,113 @@ using TheBlacksmithVakulaContract.Exceptions;
using TheBlacksmithVakulaContract.StoragesContracts;
using TheBlacksmithVakulaDatabase.Models;
namespace TheBlacksmithVakulaDatabase.Implementations
namespace TheBlacksmithVakulaDatabase.Implementations;
internal class OrderStorageContract : IOrderStorageContract
{
internal class OrderStorageContract : IOrderStorageContract
private readonly TheBlacksmithVakulaDbContext _dbContext;
private readonly Mapper _mapper;
public OrderStorageContract(TheBlacksmithVakulaDbContext dbContext)
{
private readonly TheBlacksmithVakulaDbContext _dbContext;
private readonly Mapper _mapper;
public OrderStorageContract(TheBlacksmithVakulaDbContext dbContext)
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<OrderProduct, OrderProductDataModel>();
cfg.CreateMap<OrderProductDataModel, OrderProduct>();
cfg.CreateMap<Order, OrderDataModel>();
cfg.CreateMap<OrderDataModel, Order>()
.ForMember(x => x.IsCancel, x => x.MapFrom(src => false))
.ForMember(x => x.OrderProducts, x => x.MapFrom(src => src.Products));
});
_mapper = new Mapper(config);
}
public List<OrderDataModel> GetList(DateTime? startDate = null, DateTime?
endDate = null, string? blacksmithId = null, string? buyerId = null, string? productId = null)
{
try
{
var query = _dbContext.Orders.Include(x => x.OrderProducts).AsQueryable();
if (startDate is not null && endDate is not null)
query = query.Where(x => x.OrderDate >= startDate && x.OrderDate < endDate);
if (blacksmithId is not null) query = query.Where(x => x.BlacksmithId == blacksmithId);
if (buyerId is not null) query = query.Where(x => x.BuyerId == buyerId);
if (productId is not null) query = query.Where(x => x.OrderProducts!.Any(y => y.ProductId == productId));
return [.. query.Select(x => _mapper.Map<OrderDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public OrderDataModel? GetElementById(string id)
{
try
{
return _mapper.Map<OrderDataModel>(GetOrderById(id));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void AddElement(OrderDataModel saleDataModel)
{
try
{
_dbContext.Orders.Add(_mapper.Map<Order>(saleDataModel));
_dbContext.SaveChanges();
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void DelElement(string id)
{
try
{
var element = GetOrderById(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 Order? GetOrderById(string id) => _dbContext.Orders.FirstOrDefault(x => x.Id == id);
cfg.CreateMap<Billet, BilletDataModel>();
cfg.CreateMap<Buyer, BuyerDataModel>();
cfg.CreateMap<Product, ProductDataModel>();
cfg.CreateMap<Blacksmith, BlacksmithDataModel>();
cfg.CreateMap<OrderProduct, OrderProductDataModel>();
cfg.CreateMap<OrderProductDataModel, OrderProduct>();
cfg.CreateMap<Order, OrderDataModel>();
cfg.CreateMap<OrderDataModel, Order>()
.ForMember(x => x.IsCancel, x => x.MapFrom(src => false))
.ForMember(x => x.OrderProducts, x => x.MapFrom(src => src.Products));
});
_mapper = new Mapper(config);
}
public List<OrderDataModel> GetList(DateTime? startDate = null, DateTime? endDate = null, string? blacksmithId = null, string? buyerId = null, string? productId = null)
{
try
{
var query = _dbContext.Orders.Include(x => x.Buyer).Include(x => x.Blacksmith).Include(x => x.OrderProducts)!.ThenInclude(x => x.Product).AsQueryable();
if (startDate is not null && endDate is not null)
{
query = query.Where(x => x.OrderDate >= startDate && x.OrderDate < endDate);
}
if (blacksmithId is not null)
{
query = query.Where(x => x.BlacksmithId == blacksmithId);
}
if (buyerId is not null)
{
query = query.Where(x => x.BuyerId == buyerId);
}
if (productId is not null)
{
query = query.Where(x => x.OrderProducts!.Any(y => y.ProductId == productId));
}
return [.. query.Select(x => _mapper.Map<OrderDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public OrderDataModel? GetElementById(string id)
{
try
{
return _mapper.Map<OrderDataModel>(GetOrderById(id));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void AddElement(OrderDataModel orderDataModel)
{
try
{
_dbContext.Orders.Add(_mapper.Map<Order>(orderDataModel));
_dbContext.SaveChanges();
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void DelElement(string id)
{
try
{
var element = GetOrderById(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 Order? GetOrderById(string id) => _dbContext.Orders.Include(x => x.Buyer).Include(x => x.Blacksmith)
.Include(x => x.OrderProducts)!.ThenInclude(x => x.Product).FirstOrDefault(x => x.Id == id);
}

View File

@@ -6,168 +6,171 @@ using TheBlacksmithVakulaContract.Exceptions;
using TheBlacksmithVakulaContract.StoragesContracts;
using TheBlacksmithVakulaDatabase.Models;
namespace TheBlacksmithVakulaDatabase.Implementations
namespace TheBlacksmithVakulaDatabase.Implementations;
internal class ProductStorageContract : IProductStorageContract
{
internal class ProductStorageContract : IProductStorageContract
private readonly TheBlacksmithVakulaDbContext _dbContext;
private readonly Mapper _mapper;
public ProductStorageContract(TheBlacksmithVakulaDbContext dbContext)
{
private readonly TheBlacksmithVakulaDbContext _dbContext;
private readonly Mapper _mapper;
public ProductStorageContract(TheBlacksmithVakulaDbContext dbContext)
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
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? billetId = null)
{
try
{
var query = _dbContext.Products.AsQueryable();
if (onlyActive) query = query.Where(x => !x.IsDeleted);
if (billetId is not null) query = query.Where(x => x.BilletId == billetId);
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.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.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.FirstOrDefault(x => x.Id == id && !x.IsDeleted);
cfg.CreateMap<Billet, BilletDataModel>();
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? billetId = null)
{
try
{
var query = _dbContext.Products.Include(x => x.Billet).AsQueryable();
if (onlyActive)
{
query = query.Where(x => !x.IsDeleted);
}
if (billetId is not null)
{
query = query.Where(x => x.BilletId == billetId);
}
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.Billet).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.Billet).FirstOrDefault(x => x.Id == id && !x.IsDeleted);
}

View File

@@ -1,54 +1,59 @@
using AutoMapper;
using Microsoft.EntityFrameworkCore;
using TheBlacksmithVakulaContract.DataModels;
using TheBlacksmithVakulaContract.Exceptions;
using TheBlacksmithVakulaContract.StoragesContracts;
using TheBlacksmithVakulaDatabase.Models;
namespace TheBlacksmithVakulaDatabase.Implementations
namespace TheBlacksmithVakulaDatabase.Implementations;
internal class SalaryStorageContract : ISalaryStorageContract
{
internal class SalaryStorageContract : ISalaryStorageContract
private readonly TheBlacksmithVakulaDbContext _dbContext;
private readonly Mapper _mapper;
public SalaryStorageContract(TheBlacksmithVakulaDbContext dbContext)
{
private readonly TheBlacksmithVakulaDbContext _dbContext;
private readonly Mapper _mapper;
public SalaryStorageContract(TheBlacksmithVakulaDbContext dbContext)
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.AddMaps(typeof(Salary));
cfg.CreateMap<Blacksmith, BlacksmithDataModel>();
cfg.CreateMap<Salary, SalaryDataModel>();
cfg.CreateMap<SalaryDataModel, Salary>()
.ForMember(dest => dest.BlacksmithSalary, opt => opt.MapFrom(src => src.Salary));
});
_mapper = new Mapper(config);
}
});
_mapper = new Mapper(config);
public List<SalaryDataModel> GetList(DateTime startDate, DateTime endDate, string? blacksmithId = null)
{
try
{
var query = _dbContext.Salaries.Include(x => x.Blacksmith).Where(x => x.SalaryDate >= startDate && x.SalaryDate <= endDate);
if (blacksmithId is not null)
{
query = query.Where(x => x.BlacksmithId == blacksmithId);
}
return [.. query.Select(x => _mapper.Map<SalaryDataModel>(x))];
}
public List<SalaryDataModel> GetList(DateTime startDate, DateTime endDate, string? blacksmithId = null)
catch (Exception ex)
{
try
{
var query = _dbContext.Salaries.Where(x => x.SalaryDate >= startDate && x.SalaryDate <= endDate);
if (blacksmithId is not null) query = query.Where(x => x.BlacksmithId == blacksmithId);
return [.. query.Select(x => _mapper.Map<SalaryDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void AddElement(SalaryDataModel salaryDataModel)
public void AddElement(SalaryDataModel salaryDataModel)
{
try
{
try
{
_dbContext.Salaries.Add(_mapper.Map<Salary>(salaryDataModel));
_dbContext.SaveChanges();
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
_dbContext.Salaries.Add(_mapper.Map<Salary>(salaryDataModel));
_dbContext.SaveChanges();
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
}

View File

@@ -16,10 +16,19 @@ namespace TheBlacksmithVakulaDatabase.Models
public bool IsDeleted { get; set; }
[NotMapped]
public Rank? Rank { get; set; }
[ForeignKey("BlacksmithId")]
public List<Rank>? Ranks { get; set; }
public List<Order>? Orders { get; set; }
[ForeignKey("BlacksmithId")]
public List<Salary>? Salaries { get; set; }
public Blacksmith AddRank(Rank? rank)
{
Rank = rank;
return this;
}
}
}

View File

@@ -8,8 +8,8 @@
<ItemGroup>
<PackageReference Include="AutoMapper" Version="14.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="9.0.3" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="9.0.3" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="9.0.4" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="9.0.4" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="9.0.4" />
</ItemGroup>
@@ -19,6 +19,7 @@
<ItemGroup>
<InternalsVisibleTo Include="TheBlacksmithVakulaTests" />
<InternalsVisibleTo Include="TheBlacksmithVakulaWebApi" />
<InternalsVisibleTo Include="DinamicProxyGenAssembly2" />
</ItemGroup>

View File

@@ -4,9 +4,16 @@ using TheBlacksmithVakulaDatabase.Models;
namespace TheBlacksmithVakulaDatabase
{
internal class TheBlacksmithVakulaDbContext(IConfigurationDatabase configurationDatabase) : DbContext
internal class TheBlacksmithVakulaDbContext : DbContext
{
private readonly IConfigurationDatabase? _configurationDatabase = configurationDatabase;
private readonly IConfigurationDatabase? _configurationDatabase;
public TheBlacksmithVakulaDbContext(IConfigurationDatabase configurationDatabase)
{
_configurationDatabase = configurationDatabase;
AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true);
AppContext.SetSwitch("Npgsql.DisableDateTimeInfinityConversions", true);
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
@@ -20,6 +27,11 @@ namespace TheBlacksmithVakulaDatabase
modelBuilder.Entity<Buyer>().HasIndex(x => x.PhoneNumber).IsUnique();
modelBuilder.Entity<Order>()
.HasOne(e => e.Buyer)
.WithMany(e => e.Orders)
.OnDelete(DeleteBehavior.SetNull);
modelBuilder.Entity<Billet>().HasIndex(x => x.BilletName).IsUnique();
modelBuilder.Entity<Rank>()

View File

@@ -35,10 +35,10 @@ namespace TheBlacksmithVakulaTests.BusinessLogicContractTests
var date = DateTime.UtcNow;
var listOriginal = new List<OrderDataModel>()
{
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 OrderProductDataModel(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(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, DiscountType.None, false, []),
};
_orderStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Returns(listOriginal);
@@ -110,10 +110,10 @@ namespace TheBlacksmithVakulaTests.BusinessLogicContractTests
var blacksmithId = Guid.NewGuid().ToString();
var listOriginal = new List<OrderDataModel>()
{
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 OrderProductDataModel(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(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, DiscountType.None, false, []),
};
_orderStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Returns(listOriginal);
@@ -209,10 +209,10 @@ namespace TheBlacksmithVakulaTests.BusinessLogicContractTests
var buyerId = Guid.NewGuid().ToString();
var listOriginal = new List<OrderDataModel>()
{
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 OrderProductDataModel(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(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, DiscountType.None, false, [])
};
_orderStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<string?>(), It.IsAny<string?>(), It.IsAny<string?>())).Returns(listOriginal);
@@ -308,10 +308,10 @@ namespace TheBlacksmithVakulaTests.BusinessLogicContractTests
var productId = Guid.NewGuid().ToString();
var listOriginal = new List<OrderDataModel>()
{
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 OrderProductDataModel(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(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, DiscountType.None, false, []),
};
_orderStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Returns(listOriginal);
@@ -404,7 +404,7 @@ namespace TheBlacksmithVakulaTests.BusinessLogicContractTests
{
//Arrange
var id = Guid.NewGuid().ToString();
var record = new OrderDataModel(id, Guid.NewGuid().ToString(), null, 10, DiscountType.None, 0, false,
var record = new OrderDataModel(id, Guid.NewGuid().ToString(), null, DiscountType.None, false,
[new OrderProductDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]);
_orderStorageContract.Setup(x => x.GetElementById(id)).Returns(record);
//Act
@@ -459,7 +459,7 @@ namespace TheBlacksmithVakulaTests.BusinessLogicContractTests
//Arrange
var flag = false;
var record = new OrderDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(),
Guid.NewGuid().ToString(), 10, DiscountType.None, 10, false,
Guid.NewGuid().ToString(), DiscountType.None, false,
[new OrderProductDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]);
_orderStorageContract.Setup(x => x.AddElement(It.IsAny<OrderDataModel>()))
.Callback((OrderDataModel x) =>
@@ -492,7 +492,7 @@ namespace TheBlacksmithVakulaTests.BusinessLogicContractTests
.Throws(new ElementExistsException("Data", "Data"));
//Act&Assert
Assert.That(() => _orderBusinessLogicContract.InsertOrder(new(Guid.NewGuid().ToString(),
Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 10, DiscountType.None, 10, false,
Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), DiscountType.None, false,
[new OrderProductDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])),
Throws.TypeOf<ElementExistsException>());
_orderStorageContract.Verify(x => x.AddElement(It.IsAny<OrderDataModel>()), Times.Once);
@@ -511,7 +511,7 @@ namespace TheBlacksmithVakulaTests.BusinessLogicContractTests
{
//Act&Assert
Assert.That(() => _orderBusinessLogicContract.InsertOrder(new OrderDataModel("id", Guid.NewGuid().ToString(),
Guid.NewGuid().ToString(), 10, DiscountType.None, 10, false, [])), Throws.TypeOf<ValidationException>());
Guid.NewGuid().ToString(), DiscountType.None, false, [])), Throws.TypeOf<ValidationException>());
_orderStorageContract.Verify(x => x.AddElement(It.IsAny<OrderDataModel>()), Times.Never);
}
@@ -523,7 +523,7 @@ namespace TheBlacksmithVakulaTests.BusinessLogicContractTests
.Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _orderBusinessLogicContract.InsertOrder(new(Guid.NewGuid().ToString(),
Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 10, DiscountType.None, 10, false,
Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), DiscountType.None, false,
[new OrderProductDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])),
Throws.TypeOf<StorageException>());
_orderStorageContract.Verify(x => x.AddElement(It.IsAny<OrderDataModel>()), Times.Once);

View File

@@ -34,9 +34,9 @@ namespace TheBlacksmithVakulaTests.BusinessLogicContractTests
//Arrange
var listOriginal = new List<RankDataModel>()
{
new(Guid.NewGuid().ToString(),"name 1", RankType.Student, true, DateTime.UtcNow),
new(Guid.NewGuid().ToString(), "name 2", RankType.Student, false, DateTime.UtcNow),
new(Guid.NewGuid().ToString(), "name 3", RankType.Student, true, DateTime.UtcNow),
new(Guid.NewGuid().ToString(),"name 1", RankType.Student),
new(Guid.NewGuid().ToString(),"name 2", RankType.Student),
new(Guid.NewGuid().ToString(),"name 3", RankType.Student),
};
_rankStorageContract.Setup(x => x.GetList()).Returns(listOriginal);
//Act
@@ -90,8 +90,8 @@ namespace TheBlacksmithVakulaTests.BusinessLogicContractTests
var rankId = Guid.NewGuid().ToString();
var listOriginal = new List<RankDataModel>()
{
new(rankId, "name 1", RankType.Student, true, DateTime.UtcNow),
new(rankId, "name 2", RankType.Student, false, DateTime.UtcNow)
new(rankId,"name 1", RankType.Student),
new(rankId, "name 2", RankType.Student)
};
_rankStorageContract.Setup(x => x.GetRankWithHistory(It.IsAny<string>())).Returns(listOriginal);
//Act
@@ -158,7 +158,7 @@ namespace TheBlacksmithVakulaTests.BusinessLogicContractTests
{
//Arrange
var id = Guid.NewGuid().ToString();
var record = new RankDataModel(id, "name", RankType.Student, true, DateTime.UtcNow);
var record = new RankDataModel(id, "name", RankType.Student);
_rankStorageContract.Setup(x => x.GetElementById(id)).Returns(record);
//Act
var element = _rankBusinessLogicContract.GetRankByData(id);
@@ -173,7 +173,7 @@ namespace TheBlacksmithVakulaTests.BusinessLogicContractTests
{
//Arrange
var rankName = "name";
var record = new RankDataModel(Guid.NewGuid().ToString(), rankName, RankType.Student, true, DateTime.UtcNow);
var record = new RankDataModel(Guid.NewGuid().ToString(), rankName, RankType.Student);
_rankStorageContract.Setup(x => x.GetElementByName(rankName)).Returns(record);
//Act
var element = _rankBusinessLogicContract.GetRankByData(rankName);
@@ -232,13 +232,12 @@ namespace TheBlacksmithVakulaTests.BusinessLogicContractTests
{
//Arrange
var flag = false;
var record = new RankDataModel(Guid.NewGuid().ToString(), "name", RankType.Student, true, DateTime.UtcNow.AddDays(-1));
var record = new RankDataModel(Guid.NewGuid().ToString(), "name", RankType.Student);
_rankStorageContract.Setup(x => x.AddElement(It.IsAny<RankDataModel>()))
.Callback((RankDataModel x) =>
{
flag = x.Id == record.Id && x.RankName ==
record.RankName && x.RankType == record.RankType &&
x.ChangeDate == record.ChangeDate;
record.RankName && x.RankType == record.RankType;
});
//Act
_rankBusinessLogicContract.InsertRank(record);
@@ -255,7 +254,7 @@ namespace TheBlacksmithVakulaTests.BusinessLogicContractTests
.Throws(new ElementExistsException("Data", "Data"));
//Act&Assert
Assert.That(() =>
_rankBusinessLogicContract.InsertRank(new(Guid.NewGuid().ToString(), "name", RankType.Student, true, DateTime.UtcNow)),
_rankBusinessLogicContract.InsertRank(new(Guid.NewGuid().ToString(), "name", RankType.Student)),
Throws.TypeOf<ElementExistsException>());
_rankStorageContract.Verify(x => x.AddElement(It.IsAny<RankDataModel>()), Times.Once);
}
@@ -273,7 +272,7 @@ namespace TheBlacksmithVakulaTests.BusinessLogicContractTests
{
//Act&Assert
Assert.That(() => _rankBusinessLogicContract
.InsertRank(new RankDataModel("id", "name", RankType.Student, true, DateTime.UtcNow)),
.InsertRank(new RankDataModel("id", "name", RankType.Student)),
Throws.TypeOf<ValidationException>());
_rankStorageContract.Verify(x => x.AddElement(It.IsAny<RankDataModel>()), Times.Never);
}
@@ -286,7 +285,7 @@ namespace TheBlacksmithVakulaTests.BusinessLogicContractTests
.Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _rankBusinessLogicContract
.InsertRank(new(Guid.NewGuid().ToString(), "name", RankType.Student, true, DateTime.UtcNow)),
.InsertRank(new(Guid.NewGuid().ToString(), "name", RankType.Student)),
Throws.TypeOf<StorageException>());
_rankStorageContract.Verify(x => x.AddElement(It.IsAny<RankDataModel>()), Times.Once);
}
@@ -296,13 +295,12 @@ namespace TheBlacksmithVakulaTests.BusinessLogicContractTests
{
//Arrange
var flag = false;
var record = new RankDataModel(Guid.NewGuid().ToString(), "name", RankType.Student, true, DateTime.UtcNow.AddDays(-1));
var record = new RankDataModel(Guid.NewGuid().ToString(), "name", RankType.Student);
_rankStorageContract.Setup(x => x.UpdElement(It.IsAny<RankDataModel>()))
.Callback((RankDataModel x) =>
{
flag = x.Id == record.Id && x.RankName ==
record.RankName && x.RankType == record.RankType &&
x.ChangeDate == record.ChangeDate;
record.RankName && x.RankType == record.RankType;
});
//Act
_rankBusinessLogicContract.UpdateRank(record);
@@ -317,7 +315,7 @@ namespace TheBlacksmithVakulaTests.BusinessLogicContractTests
_rankStorageContract.Setup(x => x.UpdElement(It.IsAny<RankDataModel>())).Throws(new ElementNotFoundException(""));
//Act&Assert
Assert.That(() => _rankBusinessLogicContract
.UpdateRank(new(Guid.NewGuid().ToString(), "name", RankType.Student, true, DateTime.UtcNow)),
.UpdateRank(new(Guid.NewGuid().ToString(), "name 1", RankType.Student)),
Throws.TypeOf<ElementNotFoundException>());
_rankStorageContract.Verify(x => x.UpdElement(It.IsAny<RankDataModel>()), Times.Once);
}
@@ -330,7 +328,7 @@ namespace TheBlacksmithVakulaTests.BusinessLogicContractTests
.Throws(new ElementExistsException("Data", "Data"));
//Act&Assert
Assert.That(() => _rankBusinessLogicContract
.UpdateRank(new(Guid.NewGuid().ToString(), "anme", RankType.Student, true, DateTime.UtcNow)),
.UpdateRank(new(Guid.NewGuid().ToString(), "name", RankType.Student)),
Throws.TypeOf<ElementExistsException>());
_rankStorageContract.Verify(x => x.UpdElement(It.IsAny<RankDataModel>()), Times.Once);
}
@@ -348,7 +346,7 @@ namespace TheBlacksmithVakulaTests.BusinessLogicContractTests
{
//Act&Assert
Assert.That(() => _rankBusinessLogicContract
.UpdateRank(new RankDataModel("id", "name", RankType.Student, true, DateTime.UtcNow)),
.UpdateRank(new RankDataModel("id", "name", RankType.Student)),
Throws.TypeOf<ValidationException>());
_rankStorageContract.Verify(x => x.UpdElement(It.IsAny<RankDataModel>()), Times.Never);
}
@@ -361,7 +359,7 @@ namespace TheBlacksmithVakulaTests.BusinessLogicContractTests
.Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _rankBusinessLogicContract
.UpdateRank(new(Guid.NewGuid().ToString(), "name", RankType.Student, true, DateTime.UtcNow)),
.UpdateRank(new(Guid.NewGuid().ToString(), "name", RankType.Student)),
Throws.TypeOf<StorageException>());
_rankStorageContract.Verify(x => x.UpdElement(It.IsAny<RankDataModel>()), Times.Once);
}

View File

@@ -206,9 +206,7 @@ namespace TheBlacksmithVakulaTests.BusinessLogicContractTests
var orderSum = 2000.0;
_orderStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(),
It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns([new OrderDataModel(Guid.NewGuid().ToString(), blacksmithId, null, orderSum, DiscountType.None, 0, false, [])]);
_rankStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new RankDataModel(Guid.NewGuid().ToString(), "name", RankType.Student, true, DateTime.UtcNow));
.Returns([new OrderDataModel(Guid.NewGuid().ToString(), blacksmithId, null, DiscountType.None, false, [new OrderProductDataModel("110", "22", 2)])]);
_blacksmithStorageContract.Setup(x => x.GetList(It.IsAny<bool>(),
It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Returns([new BlacksmithDataModel(blacksmithId, "Test", Guid.NewGuid().ToString(),
@@ -241,13 +239,13 @@ namespace TheBlacksmithVakulaTests.BusinessLogicContractTests
};
_orderStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(),
It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns([new OrderDataModel(Guid.NewGuid().ToString(), blacksmith1Id, null, 1, DiscountType.None, 0, false, []),
new OrderDataModel(Guid.NewGuid().ToString(), blacksmith1Id, null, 1, DiscountType.None, 0, false, []),
new OrderDataModel(Guid.NewGuid().ToString(), blacksmith2Id, null, 1, DiscountType.None, 0, false, []),
new OrderDataModel(Guid.NewGuid().ToString(), blacksmith3Id, null, 1, DiscountType.None, 0, false, []),
new OrderDataModel(Guid.NewGuid().ToString(), blacksmith3Id, null, 1, DiscountType.None, 0, false, [])]);
.Returns([new OrderDataModel(Guid.NewGuid().ToString(), blacksmith1Id, null, DiscountType.None, false, []),
new OrderDataModel(Guid.NewGuid().ToString(), blacksmith1Id, null, DiscountType.None, false, []),
new OrderDataModel(Guid.NewGuid().ToString(), blacksmith2Id, null, DiscountType.None, false, []),
new OrderDataModel(Guid.NewGuid().ToString(), blacksmith3Id, null, DiscountType.None, false, []),
new OrderDataModel(Guid.NewGuid().ToString(), blacksmith3Id, null, DiscountType.None, false, [])]);
_rankStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new RankDataModel(Guid.NewGuid().ToString(), "name", RankType.Student, true, DateTime.UtcNow));
.Returns(new RankDataModel(Guid.NewGuid().ToString(), "name", RankType.Student));
_blacksmithStorageContract.Setup(x => x.GetList(It.IsAny<bool>(),
It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Returns(list);
@@ -263,7 +261,7 @@ namespace TheBlacksmithVakulaTests.BusinessLogicContractTests
//Arrange
var blacksmithId = Guid.NewGuid().ToString();
_rankStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new RankDataModel(Guid.NewGuid().ToString(), "name", RankType.Student, true, DateTime.UtcNow));
.Returns(new RankDataModel(Guid.NewGuid().ToString(), "name", RankType.Student));
_blacksmithStorageContract.Setup(x => x.GetList(It.IsAny<bool>(),
It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Returns([new BlacksmithDataModel(blacksmithId, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)]);
@@ -278,9 +276,9 @@ namespace TheBlacksmithVakulaTests.BusinessLogicContractTests
var blacksmithId = Guid.NewGuid().ToString();
_orderStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(),
It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns([new OrderDataModel(Guid.NewGuid().ToString(), blacksmithId, null, 200, DiscountType.None, 0, false, [])]);
.Returns([new OrderDataModel(Guid.NewGuid().ToString(), blacksmithId, null, DiscountType.None, false, [])]);
_rankStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new RankDataModel(Guid.NewGuid().ToString(), "name", RankType.Student, true, DateTime.UtcNow));
.Returns(new RankDataModel(Guid.NewGuid().ToString(), "name", RankType.Student));
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow), Throws.TypeOf<NullListException>());
}
@@ -294,7 +292,7 @@ namespace TheBlacksmithVakulaTests.BusinessLogicContractTests
It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
.Throws(new StorageException(new InvalidOperationException()));
_rankStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new RankDataModel(Guid.NewGuid().ToString(), "name", RankType.Student, true, DateTime.UtcNow));
.Returns(new RankDataModel(Guid.NewGuid().ToString(), "name", RankType.Student));
_blacksmithStorageContract.Setup(x => x.GetList(It.IsAny<bool>(),
It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Returns([new BlacksmithDataModel(blacksmithId, "Test", Guid.NewGuid().ToString(),
@@ -310,9 +308,9 @@ namespace TheBlacksmithVakulaTests.BusinessLogicContractTests
var blacksmithId = Guid.NewGuid().ToString();
_orderStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(),
It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns([new OrderDataModel(Guid.NewGuid().ToString(), blacksmithId, null, 200, DiscountType.None, 0, false, [])]);
.Returns([new OrderDataModel(Guid.NewGuid().ToString(), blacksmithId, null, DiscountType.None, false, [])]);
_rankStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new RankDataModel(Guid.NewGuid().ToString(), "name", RankType.Student, true, DateTime.UtcNow));
.Returns(new RankDataModel(Guid.NewGuid().ToString(), "name", RankType.Student));
_blacksmithStorageContract.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()));

View File

@@ -107,7 +107,7 @@ namespace TheBlacksmithVakulaTests.DataModelsTests
private static OrderDataModel CreateDataModel(string? id, string? blacksmithId,
string? buyerId, double sum, DiscountType discountType, double discount, bool
isCancel, List<OrderProductDataModel>? products) =>
new(id, blacksmithId, buyerId, sum, discountType, discount, isCancel, products);
new(id, blacksmithId, buyerId, sum, discountType, discount, isCancel, products, null, null);
private static List<OrderProductDataModel> CreateSubDataModel() =>
[new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 1)];

View File

@@ -10,35 +10,32 @@ namespace TheBlacksmithVakulaTests.DataModelsTests
[Test]
public void IdIsNullOrEmptyTest()
{
var rank = CreateDataModel(null, "name", RankType.Student, true, DateTime.UtcNow);
var rank = CreateDataModel(null, "name", RankType.Student);
Assert.That(() => rank.Validate(), Throws.TypeOf<ValidationException>());
rank = CreateDataModel(string.Empty, "name", RankType.Student, true, DateTime.UtcNow);
rank = CreateDataModel(string.Empty, "name", RankType.Student);
Assert.That(() => rank.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void IdIsNotGuidTest()
{
var post = CreateDataModel("id", "name", RankType.Student, true, DateTime.UtcNow);
var post = CreateDataModel("id", "name", RankType.Student);
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void RankNameIsEmptyTest()
{
var rank = CreateDataModel(Guid.NewGuid().ToString(),
null, RankType.Student, true, DateTime.UtcNow);
var rank = CreateDataModel(Guid.NewGuid().ToString(), null, RankType.Student);
Assert.That(() => rank.Validate(), Throws.TypeOf<ValidationException>());
rank = CreateDataModel(Guid.NewGuid().ToString(),
string.Empty, RankType.Student, true, DateTime.UtcNow);
rank = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, RankType.Student);
Assert.That(() => rank.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void RankTypeIsNoneTest()
{
var rank = CreateDataModel(Guid.NewGuid().ToString(),
"name", RankType.None, true, DateTime.UtcNow);
var rank = CreateDataModel(Guid.NewGuid().ToString(), "name", RankType.None);
Assert.That(() => rank.Validate(), Throws.TypeOf<ValidationException>());
}
@@ -49,22 +46,17 @@ namespace TheBlacksmithVakulaTests.DataModelsTests
var rankId = Guid.NewGuid().ToString();
var rankName = "name";
var rankType = RankType.Student;
var isActual = false;
var changeDate = DateTime.UtcNow.AddDays(-1);
var rank = CreateDataModel(id, rankName, rankType, isActual, changeDate);
var rank = CreateDataModel(id, rankName, rankType);
Assert.That(() => rank.Validate(), Throws.Nothing);
Assert.Multiple(() =>
{
Assert.That(rank.Id, Is.EqualTo(id));
Assert.That(rank.RankName, Is.EqualTo(rankName));
Assert.That(rank.RankType, Is.EqualTo(rankType));
Assert.That(rank.IsActual, Is.EqualTo(isActual));
Assert.That(rank.ChangeDate, Is.EqualTo(changeDate));
});
}
private static RankDataModel CreateDataModel(string? id, string? rankName,
RankType rankType, bool isActual, DateTime changeDate) =>
new (id, rankName, rankType, isActual, changeDate);
private static RankDataModel CreateDataModel(string? id, string? rankName, RankType rankType) =>
new(id, rankName, rankType);
}
}

View File

@@ -0,0 +1,31 @@
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using TheBlacksmithVakulaContract.Infrastructure;
namespace TheBlacksmithVakulaTests.Infrastructure
{
internal class CustomWebApplicationFactory<TProgram> : WebApplicationFactory<TProgram> where TProgram : class
{
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder.ConfigureServices(services =>
{
var databaseConfig = services.SingleOrDefault(x => x.ServiceType == typeof(IConfigurationDatabase));
if (databaseConfig is not null)
services.Remove(databaseConfig);
var loggerFactory = services.SingleOrDefault(x => x.ServiceType == typeof(LoggerFactory));
if (loggerFactory is not null)
services.Remove(loggerFactory);
services.AddSingleton<IConfigurationDatabase, ConfigurationDatabaseTest>();
});
builder.UseEnvironment("Development");
base.ConfigureWebHost(builder);
}
}
}

View File

@@ -0,0 +1,115 @@
using Microsoft.EntityFrameworkCore;
using TheBlacksmithVakulaContract.Enums;
using TheBlacksmithVakulaDatabase;
using TheBlacksmithVakulaDatabase.Models;
namespace TheBlacksmithVakulaTests.Infrastructure
{
internal static class TheBlacksmithVakulaDbContextExtensions
{
public static Buyer InsertBuyerToDatabaseAndReturn(this TheBlacksmithVakulaDbContext 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 Billet InsertBilletToDatabaseAndReturn(this TheBlacksmithVakulaDbContext dbContext, string? id = null, string billetName = "test", string prevBilletName = "prev", string prevPrevBilletName = "prevPrev")
{
var billet = new Billet() { Id = id ?? Guid.NewGuid().ToString(), BilletName = billetName, PrevBilletName = prevBilletName, PrevPrevBilletName = prevPrevBilletName };
dbContext.Billets.Add(billet);
dbContext.SaveChanges();
return billet;
}
public static Rank InsertRankToDatabaseAndReturn(this TheBlacksmithVakulaDbContext dbContext, string? id = null, string rankName = "test", RankType rankType = RankType.Expert, bool isActual = true, DateTime? changeDate = null)
{
var rank = new Rank() { Id = Guid.NewGuid().ToString(), RankId = id ?? Guid.NewGuid().ToString(), RankName = rankName, RankType = rankType, IsActual = isActual, ChangeDate = changeDate ?? DateTime.UtcNow };
dbContext.Ranks.Add(rank);
dbContext.SaveChanges();
return rank;
}
public static Product InsertProductToDatabaseAndReturn(this TheBlacksmithVakulaDbContext dbContext, string billetId, string? id = null, string productName = "test", ProductType productType = ProductType.Jewel, double price = 1, bool isDeleted = false)
{
var product = new Product() { Id = id ?? Guid.NewGuid().ToString(), BilletId = billetId, ProductName = productName, ProductType = productType, Price = price, IsDeleted = isDeleted };
dbContext.Products.Add(product);
dbContext.SaveChanges();
return product;
}
public static ProductHistory InsertProductHistoryToDatabaseAndReturn(this TheBlacksmithVakulaDbContext 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 TheBlacksmithVakulaDbContext dbContext, string blacksmithId, double blacksmithSalary = 1, DateTime? salaryDate = null)
{
var salary = new Salary() { Id = Guid.NewGuid().ToString(), BlacksmithId = blacksmithId, BlacksmithSalary = blacksmithSalary, SalaryDate = salaryDate ?? DateTime.UtcNow };
dbContext.Salaries.Add(salary);
dbContext.SaveChanges();
return salary;
}
public static Order InsertOrderToDatabaseAndReturn(this TheBlacksmithVakulaDbContext dbContext, string blacksmithId, string? buyerId = null, DateTime? orderDate = null, double sum = 1, DiscountType discountType = DiscountType.RegularCustomer, double discount = 0, bool isCancel = false, List<(string, int)>? products = null)
{
var order = new Order() { BlacksmithId = blacksmithId, BuyerId = buyerId, OrderDate = orderDate ?? DateTime.UtcNow, Sum = sum, DiscountType = discountType, Discount = discount, IsCancel = isCancel, OrderProducts = [] };
if (products is not null)
{
foreach (var elem in products)
{
order.OrderProducts.Add(new OrderProduct { ProductId = elem.Item1, OrderId = order.Id, Count = elem.Item2});
}
}
dbContext.Orders.Add(order);
dbContext.SaveChanges();
return order;
}
public static Blacksmith InsertBlacksmithToDatabaseAndReturn(this TheBlacksmithVakulaDbContext dbContext, string? id = null, string fio = "test", string? rankId = null, DateTime? birthDate = null, DateTime? employmentDate = null, bool isDeleted = false)
{
var blacksmith = new Blacksmith() { Id = id ?? Guid.NewGuid().ToString(), FIO = fio, RankId = rankId ?? Guid.NewGuid().ToString(), BirthDate = birthDate ?? DateTime.UtcNow.AddYears(-20), EmploymentDate = employmentDate ?? DateTime.UtcNow, IsDeleted = isDeleted };
dbContext.Blacksmiths.Add(blacksmith);
dbContext.SaveChanges();
return blacksmith;
}
public static Buyer? GetBuyerFromDatabase(this TheBlacksmithVakulaDbContext dbContext, string id) => dbContext.Buyers.FirstOrDefault(x => x.Id == id);
public static Billet? GetBilletFromDatabase(this TheBlacksmithVakulaDbContext dbContext, string id) => dbContext.Billets.FirstOrDefault(x => x.Id == id);
public static Rank? GetRankFromDatabaseByRankId(this TheBlacksmithVakulaDbContext dbContext, string id) => dbContext.Ranks.FirstOrDefault(x => x.RankId == id && x.IsActual);
public static Rank[] GetRanksFromDatabaseByRankId(this TheBlacksmithVakulaDbContext dbContext, string id) => [.. dbContext.Ranks.Where(x => x.RankId == id).OrderByDescending(x => x.ChangeDate)];
public static Product? GetProductFromDatabaseById(this TheBlacksmithVakulaDbContext dbContext, string id) => dbContext.Products.FirstOrDefault(x => x.Id == id);
public static Salary[] GetSalariesFromDatabaseByBlacksmithId(this TheBlacksmithVakulaDbContext dbContext, string id) => [.. dbContext.Salaries.Where(x => x.BlacksmithId == id)];
public static Order? GetOrderFromDatabaseById(this TheBlacksmithVakulaDbContext dbContext, string id) => dbContext.Orders.Include(x => x.OrderProducts).FirstOrDefault(x => x.Id == id);
public static Order[] GetOrdersByBuyerId(this TheBlacksmithVakulaDbContext dbContext, string? buyerId) => [.. dbContext.Orders.Include(x => x.OrderProducts).Where(x => x.BuyerId == buyerId)];
public static Blacksmith? GetBlacksmithFromDatabaseById(this TheBlacksmithVakulaDbContext dbContext, string id) => dbContext.Blacksmiths.FirstOrDefault(x => x.Id == id);
public static void RemoveBuyersFromDatabase(this TheBlacksmithVakulaDbContext dbContext) => dbContext.ExecuteSqlRaw("TRUNCATE \"Buyers\" CASCADE;");
public static void RemoveBilletsFromDatabase(this TheBlacksmithVakulaDbContext dbContext) => dbContext.ExecuteSqlRaw("TRUNCATE \"Billets\" CASCADE;");
public static void RemoveRanksFromDatabase(this TheBlacksmithVakulaDbContext dbContext) => dbContext.ExecuteSqlRaw("TRUNCATE \"Ranks\" CASCADE;");
public static void RemoveProductsFromDatabase(this TheBlacksmithVakulaDbContext dbContext) => dbContext.ExecuteSqlRaw("TRUNCATE \"Products\" CASCADE;");
public static void RemoveSalariesFromDatabase(this TheBlacksmithVakulaDbContext dbContext) => dbContext.ExecuteSqlRaw("TRUNCATE \"Salaries\" CASCADE;");
public static void RemoveOrdersFromDatabase(this TheBlacksmithVakulaDbContext dbContext) => dbContext.ExecuteSqlRaw("TRUNCATE \"Orders\" CASCADE;");
public static void RemoveBlacksmithsFromDatabase(this TheBlacksmithVakulaDbContext dbContext) => dbContext.ExecuteSqlRaw("TRUNCATE \"Blacksmiths\" CASCADE;");
private static void ExecuteSqlRaw(this TheBlacksmithVakulaDbContext dbContext, string command) => dbContext.Database.ExecuteSqlRaw(command);
}
}

View File

@@ -1,8 +1,8 @@
using Microsoft.EntityFrameworkCore;
using TheBlacksmithVakulaContract.Exceptions;
using TheBlacksmithVakulaContract.Exceptions;
using TheBlacksmithVakulaContract.DataModels;
using TheBlacksmithVakulaDatabase.Implementations;
using TheBlacksmithVakulaDatabase.Models;
using TheBlacksmithVakulaTests.Infrastructure;
namespace TheBlacksmithVakulaTests.StrorageContractTests
{
@@ -20,8 +20,8 @@ namespace TheBlacksmithVakulaTests.StrorageContractTests
[TearDown]
public void TearDown()
{
TheBlacksmithVakulaDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Products\"CASCADE; ");
TheBlacksmithVakulaDbContext.Database.ExecuteSqlRaw("TRUNCATE\"Billets\" CASCADE;");
TheBlacksmithVakulaDbContext.RemoveProductsFromDatabase();
TheBlacksmithVakulaDbContext.RemoveBilletsFromDatabase();
}
[Test]
@@ -94,7 +94,7 @@ namespace TheBlacksmithVakulaTests.StrorageContractTests
{
var billet = CreateModel(Guid.NewGuid().ToString());
_billetStorageContract.AddElement(billet);
AssertElement(GetBilletFromDatabase(billet.Id), billet);
AssertElement(TheBlacksmithVakulaDbContext.GetBilletFromDatabase(billet.Id), billet);
}
[Test]
@@ -119,7 +119,7 @@ namespace TheBlacksmithVakulaTests.StrorageContractTests
var billet = CreateModel(Guid.NewGuid().ToString(), "name new", "test", "prev");
InsertBilletToDatabaseAndReturn(billet.Id, billetName: billet.PrevBilletName!, prevBilletName: billet.PrevPrevBilletName!);
_billetStorageContract.UpdElement(CreateModel(billet.Id, "name new", "some name", "some name"));
AssertElement(GetBilletFromDatabase(billet.Id), billet);
AssertElement(TheBlacksmithVakulaDbContext.GetBilletFromDatabase(billet.Id), billet);
}
[Test]
@@ -129,7 +129,7 @@ namespace TheBlacksmithVakulaTests.StrorageContractTests
InsertBilletToDatabaseAndReturn(billet.Id, billetName: billet.BilletName!, prevBilletName: billet.PrevBilletName!,
prevPrevBilletName: billet.PrevPrevBilletName!);
_billetStorageContract.UpdElement(billet);
AssertElement(GetBilletFromDatabase(billet.Id), billet);
AssertElement(TheBlacksmithVakulaDbContext.GetBilletFromDatabase(billet.Id), billet);
}
[Test]
@@ -154,7 +154,7 @@ namespace TheBlacksmithVakulaTests.StrorageContractTests
var billet =
InsertBilletToDatabaseAndReturn(Guid.NewGuid().ToString());
_billetStorageContract.DelElement(billet.Id);
var element = GetBilletFromDatabase(billet.Id);
var element = TheBlacksmithVakulaDbContext.GetBilletFromDatabase(billet.Id);
Assert.That(element, Is.Null);
}
@@ -207,11 +207,9 @@ namespace TheBlacksmithVakulaTests.StrorageContractTests
});
}
private static BilletDataModel CreateModel(string id, string billetName = "test", string prevBilletName = "prev",
private static BilletDataModel CreateModel(string id, string billetName = "test", string prevBilletName = "prev",
string prevPrevBilletName = "prevPrev") => new(id, billetName, prevBilletName, prevPrevBilletName);
private Billet? GetBilletFromDatabase(string id) => TheBlacksmithVakulaDbContext.Billets.FirstOrDefault(x => x.Id == id);
private static void AssertElement(Billet? actual, BilletDataModel expected)
{
Assert.That(actual, Is.Not.Null);

View File

@@ -1,8 +1,8 @@
using Microsoft.EntityFrameworkCore;
using TheBlacksmithVakulaContract.DataModels;
using TheBlacksmithVakulaContract.DataModels;
using TheBlacksmithVakulaContract.Exceptions;
using TheBlacksmithVakulaDatabase.Implementations;
using TheBlacksmithVakulaDatabase.Models;
using TheBlacksmithVakulaTests.Infrastructure;
namespace TheBlacksmithVakulaTests.StrorageContractTests
{
@@ -20,7 +20,7 @@ namespace TheBlacksmithVakulaTests.StrorageContractTests
[TearDown]
public void TearDown()
{
TheBlacksmithVakulaDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Blacksmiths\"CASCADE; ");
TheBlacksmithVakulaDbContext.RemoveBlacksmithsFromDatabase();
}
[Test]
@@ -32,7 +32,6 @@ namespace TheBlacksmithVakulaTests.StrorageContractTests
var list = _blacksmithStorageContract.GetList();
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(3));
AssertElement(list.First(), blacksmith);
}
[Test]
@@ -132,7 +131,7 @@ namespace TheBlacksmithVakulaTests.StrorageContractTests
{
var blacksmith = CreateModel(Guid.NewGuid().ToString());
_blacksmithStorageContract.AddElement(blacksmith);
AssertElement(GetBlacksmithFromDatabase(blacksmith.Id), blacksmith);
AssertElement(TheBlacksmithVakulaDbContext.GetBlacksmithFromDatabaseById(blacksmith.Id), blacksmith);
}
[Test]
@@ -149,7 +148,7 @@ namespace TheBlacksmithVakulaTests.StrorageContractTests
var blacksmith = CreateModel(Guid.NewGuid().ToString(), "New Fio");
InsertBlacksmithToDatabaseAndReturn(blacksmith.Id);
_blacksmithStorageContract.UpdElement(blacksmith);
AssertElement(GetBlacksmithFromDatabase(blacksmith.Id), blacksmith);
AssertElement(TheBlacksmithVakulaDbContext.GetBlacksmithFromDatabaseById(blacksmith.Id), blacksmith);
}
[Test]
@@ -172,7 +171,7 @@ namespace TheBlacksmithVakulaTests.StrorageContractTests
{
var blacksmith = InsertBlacksmithToDatabaseAndReturn(Guid.NewGuid().ToString());
_blacksmithStorageContract.DelElement(blacksmith.Id);
var element = GetBlacksmithFromDatabase(blacksmith.Id);
var element = TheBlacksmithVakulaDbContext.GetBlacksmithFromDatabaseById(blacksmith.Id);
Assert.That(element, Is.Not.Null);
Assert.That(element.IsDeleted);
}
@@ -227,9 +226,6 @@ namespace TheBlacksmithVakulaTests.StrorageContractTests
DateTime? employmentDate = null, bool isDeleted = false) => new(id, fio, rankId ?? Guid.NewGuid().ToString(),
birthDate ?? DateTime.UtcNow.AddYears(-20), employmentDate ?? DateTime.UtcNow, isDeleted);
private Blacksmith? GetBlacksmithFromDatabase(string id) =>
TheBlacksmithVakulaDbContext.Blacksmiths.FirstOrDefault(x => x.Id == id);
private static void AssertElement(Blacksmith? actual, BlacksmithDataModel expected)
{
Assert.That(actual, Is.Not.Null);

View File

@@ -1,9 +1,9 @@
using Microsoft.EntityFrameworkCore;
using TheBlacksmithVakulaContract.DataModels;
using TheBlacksmithVakulaContract.DataModels;
using TheBlacksmithVakulaContract.Enums;
using TheBlacksmithVakulaContract.Exceptions;
using TheBlacksmithVakulaDatabase.Implementations;
using TheBlacksmithVakulaDatabase.Models;
using TheBlacksmithVakulaTests.Infrastructure;
namespace TheBlacksmithVakulaTests.StrorageContractTests
{
@@ -21,17 +21,17 @@ namespace TheBlacksmithVakulaTests.StrorageContractTests
[TearDown]
public void TearDown()
{
TheBlacksmithVakulaDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Orders\"CASCADE; ");
TheBlacksmithVakulaDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Blacksmiths\"CASCADE; ");
TheBlacksmithVakulaDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Buyers\"CASCADE; ");
TheBlacksmithVakulaDbContext.RemoveOrdersFromDatabase();
TheBlacksmithVakulaDbContext.RemoveBlacksmithsFromDatabase();
TheBlacksmithVakulaDbContext.RemoveBuyersFromDatabase();
}
[Test]
public void Try_GetList_WhenHaveRecords_Test()
{
var buyer = InsertBuyerToDatabaseAndReturn(Guid.NewGuid().ToString(), phoneNumber: "+5-555-555-55-55");
InsertBuyerToDatabaseAndReturn(Guid.NewGuid().ToString(), phoneNumber: "+6-666-666-66-66");
InsertBuyerToDatabaseAndReturn(Guid.NewGuid().ToString(), phoneNumber: "+7-777-777-77-77");
var buyer = TheBlacksmithVakulaDbContext.InsertBuyerToDatabaseAndReturn(phoneNumber: "+5-555-555-55-55");
TheBlacksmithVakulaDbContext.InsertBuyerToDatabaseAndReturn(phoneNumber: "+6-666-666-66-66");
TheBlacksmithVakulaDbContext.InsertBuyerToDatabaseAndReturn(phoneNumber: "+7-777-777-77-77");
var list = _buyerStorageContract.GetList();
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(3));
@@ -49,42 +49,42 @@ namespace TheBlacksmithVakulaTests.StrorageContractTests
[Test]
public void Try_GetElementById_WhenHaveRecord_Test()
{
var buyer = InsertBuyerToDatabaseAndReturn(Guid.NewGuid().ToString());
var buyer = TheBlacksmithVakulaDbContext.InsertBuyerToDatabaseAndReturn();
AssertElement(_buyerStorageContract.GetElementById(buyer.Id), buyer);
}
[Test]
public void Try_GetElementById_WhenNoRecord_Test()
{
InsertBuyerToDatabaseAndReturn(Guid.NewGuid().ToString());
TheBlacksmithVakulaDbContext.InsertBuyerToDatabaseAndReturn();
Assert.That(() => _buyerStorageContract.GetElementById(Guid.NewGuid().ToString()), Is.Null);
}
[Test]
public void Try_GetElementByFIO_WhenHaveRecord_Test()
{
var buyer = InsertBuyerToDatabaseAndReturn(Guid.NewGuid().ToString());
var buyer = TheBlacksmithVakulaDbContext.InsertBuyerToDatabaseAndReturn();
AssertElement(_buyerStorageContract.GetElementByFIO(buyer.FIO), buyer);
}
[Test]
public void Try_GetElementByFIO_WhenNoRecord_Test()
{
InsertBuyerToDatabaseAndReturn(Guid.NewGuid().ToString());
TheBlacksmithVakulaDbContext.InsertBuyerToDatabaseAndReturn();
Assert.That(() => _buyerStorageContract.GetElementByFIO("New Fio"), Is.Null);
}
[Test]
public void Try_GetElementByPhoneNumber_WhenHaveRecord_Test()
{
var buyer = InsertBuyerToDatabaseAndReturn(Guid.NewGuid().ToString());
var buyer = TheBlacksmithVakulaDbContext.InsertBuyerToDatabaseAndReturn();
AssertElement(_buyerStorageContract.GetElementByPhoneNumber(buyer.PhoneNumber), buyer);
}
[Test]
public void Try_GetElementByPhoneNumber_WhenNoRecord_Test()
{
InsertBuyerToDatabaseAndReturn(Guid.NewGuid().ToString());
TheBlacksmithVakulaDbContext.InsertBuyerToDatabaseAndReturn();
Assert.That(() => _buyerStorageContract.GetElementByPhoneNumber("+8-888 - 888 - 88 - 88"), Is.Null);
}
@@ -93,14 +93,14 @@ namespace TheBlacksmithVakulaTests.StrorageContractTests
{
var buyer = CreateModel(Guid.NewGuid().ToString());
_buyerStorageContract.AddElement(buyer);
AssertElement(GetBuyerFromDatabase(buyer.Id), buyer);
AssertElement(TheBlacksmithVakulaDbContext.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);
InsertBuyerToDatabaseAndReturn(buyer.Id);
TheBlacksmithVakulaDbContext.InsertBuyerToDatabaseAndReturn(buyer.Id);
Assert.That(() => _buyerStorageContract.AddElement(buyer), Throws.TypeOf<ElementExistsException>());
}
@@ -108,7 +108,7 @@ namespace TheBlacksmithVakulaTests.StrorageContractTests
public void Try_AddElement_WhenHaveRecordWithSamePhoneNumber_Test()
{
var buyer = CreateModel(Guid.NewGuid().ToString(), "New Fio", "+5-555 - 555 - 55 - 55", 500);
InsertBuyerToDatabaseAndReturn(Guid.NewGuid().ToString(), phoneNumber: buyer.PhoneNumber);
TheBlacksmithVakulaDbContext.InsertBuyerToDatabaseAndReturn(phoneNumber: buyer.PhoneNumber);
Assert.That(() => _buyerStorageContract.AddElement(buyer), Throws.TypeOf<ElementExistsException>());
}
@@ -116,9 +116,9 @@ namespace TheBlacksmithVakulaTests.StrorageContractTests
public void Try_UpdElement_Test()
{
var buyer = CreateModel(Guid.NewGuid().ToString(), "New Fio", "+5-555 - 555 - 55 - 55", 500);
InsertBuyerToDatabaseAndReturn(buyer.Id);
TheBlacksmithVakulaDbContext.InsertBuyerToDatabaseAndReturn(buyer.Id);
_buyerStorageContract.UpdElement(buyer);
AssertElement(GetBuyerFromDatabase(buyer.Id), buyer);
AssertElement(TheBlacksmithVakulaDbContext.GetBuyerFromDatabase(buyer.Id), buyer);
}
[Test]
@@ -132,24 +132,24 @@ namespace TheBlacksmithVakulaTests.StrorageContractTests
public void Try_UpdElement_WhenHaveRecordWithSamePhoneNumber_Test()
{
var buyer = CreateModel(Guid.NewGuid().ToString(), "New Fio", "+5-555 - 555 - 55 - 55", 500);
InsertBuyerToDatabaseAndReturn(buyer.Id, phoneNumber: "+7-777-777-77-77");
InsertBuyerToDatabaseAndReturn(Guid.NewGuid().ToString(), phoneNumber: buyer.PhoneNumber);
TheBlacksmithVakulaDbContext.InsertBuyerToDatabaseAndReturn(buyer.Id, phoneNumber: "+7-777-777-77-77");
TheBlacksmithVakulaDbContext.InsertBuyerToDatabaseAndReturn(phoneNumber: buyer.PhoneNumber);
Assert.That(() => _buyerStorageContract.UpdElement(buyer), Throws.TypeOf<ElementExistsException>());
}
[Test]
public void Try_DelElement_Test()
{
var buyer = InsertBuyerToDatabaseAndReturn(Guid.NewGuid().ToString());
var buyer = TheBlacksmithVakulaDbContext.InsertBuyerToDatabaseAndReturn();
_buyerStorageContract.DelElement(buyer.Id);
var element = GetBuyerFromDatabase(buyer.Id);
var element = TheBlacksmithVakulaDbContext.GetBuyerFromDatabase(buyer.Id);
Assert.That(element, Is.Null);
}
[Test]
public void Try_DelElement_WhenHaveOrdersByThisBuyer_Test()
{
var buyer = InsertBuyerToDatabaseAndReturn(Guid.NewGuid().ToString());
var buyer = TheBlacksmithVakulaDbContext.InsertBuyerToDatabaseAndReturn();
var blacksmithId = Guid.NewGuid().ToString();
TheBlacksmithVakulaDbContext.Blacksmiths.Add(new Blacksmith()
{
@@ -178,7 +178,7 @@ namespace TheBlacksmithVakulaTests.StrorageContractTests
TheBlacksmithVakulaDbContext.SaveChanges();
var ordersBeforeDelete = TheBlacksmithVakulaDbContext.Orders.Where(x => x.BuyerId == buyer.Id).ToArray();
_buyerStorageContract.DelElement(buyer.Id);
var element = GetBuyerFromDatabase(buyer.Id);
var element = TheBlacksmithVakulaDbContext.GetBuyerFromDatabase(buyer.Id);
var ordersAfterDelete = TheBlacksmithVakulaDbContext.Orders.Where(x => x.BuyerId == buyer.Id).ToArray();
Assert.Multiple(() =>
{
@@ -195,21 +195,6 @@ namespace TheBlacksmithVakulaTests.StrorageContractTests
Assert.That(() => _buyerStorageContract.DelElement(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
}
private Buyer InsertBuyerToDatabaseAndReturn(string id, string fio = "test",
string phoneNumber = "+7-777-777-77-77", double discountSize = 10)
{
var buyer = new Buyer()
{
Id = id,
FIO = fio,
PhoneNumber = phoneNumber,
DiscountSize = discountSize
};
TheBlacksmithVakulaDbContext.Buyers.Add(buyer);
TheBlacksmithVakulaDbContext.SaveChanges();
return buyer;
}
private static void AssertElement(BuyerDataModel? actual, Buyer expected)
{
Assert.That(actual, Is.Not.Null);
@@ -225,8 +210,6 @@ namespace TheBlacksmithVakulaTests.StrorageContractTests
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 Buyer? GetBuyerFromDatabase(string id) => TheBlacksmithVakulaDbContext.Buyers.FirstOrDefault(x => x.Id == id);
private static void AssertElement(Buyer? actual, BuyerDataModel expected)
{
Assert.That(actual, Is.Not.Null);

View File

@@ -1,9 +1,9 @@
using Microsoft.EntityFrameworkCore;
using TheBlacksmithVakulaContract.Enums;
using TheBlacksmithVakulaContract.Enums;
using TheBlacksmithVakulaContract.Exceptions;
using TheBlacksmithVakulaDatabase.Implementations;
using TheBlacksmithVakulaDatabase.Models;
using TheBlacksmithVakulaContract.DataModels;
using TheBlacksmithVakulaTests.Infrastructure;
namespace TheBlacksmithVakulaTests.StrorageContractTests
{
@@ -20,28 +20,28 @@ namespace TheBlacksmithVakulaTests.StrorageContractTests
public void SetUp()
{
_ordertStorageContract = new OrderStorageContract(TheBlacksmithVakulaDbContext);
_billet = InsertBilletToDatabaseAndReturn();
_buyer = InsertBuyerToDatabaseAndReturn();
_blacksmith = InsertBlacksmithToDatabaseAndReturn();
_product = InsertProductToDatabaseAndReturn();
_billet = TheBlacksmithVakulaDbContext.InsertBilletToDatabaseAndReturn();
_buyer = TheBlacksmithVakulaDbContext.InsertBuyerToDatabaseAndReturn();
_blacksmith = TheBlacksmithVakulaDbContext.InsertBlacksmithToDatabaseAndReturn();
_product = TheBlacksmithVakulaDbContext.InsertProductToDatabaseAndReturn(_billet.Id);
}
[TearDown]
public void TearDown()
{
TheBlacksmithVakulaDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Orders\"CASCADE; ");
TheBlacksmithVakulaDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Buyers\"CASCADE; ");
TheBlacksmithVakulaDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Blacksmiths\"CASCADE; ");
TheBlacksmithVakulaDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Products\"CASCADE; ");
TheBlacksmithVakulaDbContext.Database.ExecuteSqlRaw("TRUNCATE\"Billets\" CASCADE;");
TheBlacksmithVakulaDbContext.RemoveOrdersFromDatabase();
TheBlacksmithVakulaDbContext.RemoveBlacksmithsFromDatabase();
TheBlacksmithVakulaDbContext.RemoveBuyersFromDatabase();
TheBlacksmithVakulaDbContext.RemoveProductsFromDatabase();
TheBlacksmithVakulaDbContext.RemoveBilletsFromDatabase();
}
[Test]
public void Try_GetList_WhenHaveRecords_Test()
{
var order = InsertOrderToDatabaseAndReturn(_blacksmith.Id, _buyer.Id, products: [(_product.Id, 1, 1.2)]);
InsertOrderToDatabaseAndReturn(_blacksmith.Id, _buyer.Id, products: [(_product.Id, 5, 1.2)]);
InsertOrderToDatabaseAndReturn(_blacksmith.Id, null, products: [(_product.Id, 10, 1.2)]);
var order = TheBlacksmithVakulaDbContext.InsertOrderToDatabaseAndReturn(_blacksmith.Id, _buyer.Id, products: [(_product.Id, 1)]);
TheBlacksmithVakulaDbContext.InsertOrderToDatabaseAndReturn(_blacksmith.Id, _buyer.Id, products: [(_product.Id, 5)]);
TheBlacksmithVakulaDbContext.InsertOrderToDatabaseAndReturn(_blacksmith.Id, null, products: [(_product.Id, 10)]);
var list = _ordertStorageContract.GetList();
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(3));
@@ -59,14 +59,14 @@ namespace TheBlacksmithVakulaTests.StrorageContractTests
[Test]
public void Try_GetList_ByPeriod_Test()
{
InsertOrderToDatabaseAndReturn(_blacksmith.Id, _buyer.Id, orderDate:
DateTime.UtcNow.AddDays(-1).AddMinutes(-3), products: [(_product.Id, 1, 1.2)]);
InsertOrderToDatabaseAndReturn(_blacksmith.Id, _buyer.Id, orderDate:
DateTime.UtcNow.AddDays(-1).AddMinutes(3), products: [(_product.Id, 1, 1.2)]);
InsertOrderToDatabaseAndReturn(_blacksmith.Id, null, orderDate:
DateTime.UtcNow.AddDays(1).AddMinutes(-3), products: [(_product.Id, 1, 1.2)]);
InsertOrderToDatabaseAndReturn(_blacksmith.Id, null, orderDate:
DateTime.UtcNow.AddDays(1).AddMinutes(3), products: [(_product.Id, 1, 1.2)]);
TheBlacksmithVakulaDbContext.InsertOrderToDatabaseAndReturn(_blacksmith.Id, _buyer.Id, orderDate:
DateTime.UtcNow.AddDays(-1).AddMinutes(-3), products: [(_product.Id, 1)]);
TheBlacksmithVakulaDbContext.InsertOrderToDatabaseAndReturn(_blacksmith.Id, _buyer.Id, orderDate:
DateTime.UtcNow.AddDays(-1).AddMinutes(3), products: [(_product.Id, 1)]);
TheBlacksmithVakulaDbContext.InsertOrderToDatabaseAndReturn(_blacksmith.Id, null, orderDate:
DateTime.UtcNow.AddDays(1).AddMinutes(-3), products: [(_product.Id, 1)]);
TheBlacksmithVakulaDbContext.InsertOrderToDatabaseAndReturn(_blacksmith.Id, null, orderDate:
DateTime.UtcNow.AddDays(1).AddMinutes(3), products: [(_product.Id, 1)]);
var list = _ordertStorageContract.GetList(startDate:
DateTime.UtcNow.AddDays(-1), endDate: DateTime.UtcNow.AddDays(1));
Assert.That(list, Is.Not.Null);
@@ -76,10 +76,10 @@ namespace TheBlacksmithVakulaTests.StrorageContractTests
[Test]
public void Try_GetList_ByBlacksmithId_Test()
{
var blacksmith = InsertBlacksmithToDatabaseAndReturn("Other blacksmith");
InsertOrderToDatabaseAndReturn(_blacksmith.Id, _buyer.Id, products: [(_product.Id, 1, 1.2)]);
InsertOrderToDatabaseAndReturn(_blacksmith.Id, _buyer.Id, products: [(_product.Id, 1, 1.2)]);
InsertOrderToDatabaseAndReturn(blacksmith.Id, null, products: [(_product.Id, 1, 1.2)]);
var blacksmith = TheBlacksmithVakulaDbContext.InsertBlacksmithToDatabaseAndReturn(fio: "Other blacksmith");
TheBlacksmithVakulaDbContext.InsertOrderToDatabaseAndReturn(_blacksmith.Id, _buyer.Id, products: [(_product.Id, 1)]);
TheBlacksmithVakulaDbContext.InsertOrderToDatabaseAndReturn(_blacksmith.Id, _buyer.Id, products: [(_product.Id, 1)]);
TheBlacksmithVakulaDbContext.InsertOrderToDatabaseAndReturn(blacksmith.Id, null, products: [(_product.Id, 1)]);
var list = _ordertStorageContract.GetList(blacksmithId: _blacksmith.Id);
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(2));
@@ -89,11 +89,11 @@ namespace TheBlacksmithVakulaTests.StrorageContractTests
[Test]
public void Try_GetList_ByBuyerId_Test()
{
var buyer = InsertBuyerToDatabaseAndReturn("Other fio", "+8-888-888-88 - 88");
InsertOrderToDatabaseAndReturn(_blacksmith.Id, _buyer.Id, products: [(_product.Id, 1, 1.2)]);
InsertOrderToDatabaseAndReturn(_blacksmith.Id, _buyer.Id, products: [(_product.Id, 1, 1.2)]);
InsertOrderToDatabaseAndReturn(_blacksmith.Id, buyer.Id, products: [(_product.Id, 1, 1.2)]);
InsertOrderToDatabaseAndReturn(_blacksmith.Id, null, products: [(_product.Id, 1, 1.2)]);
var buyer = TheBlacksmithVakulaDbContext.InsertBuyerToDatabaseAndReturn(fio: "Other fio", phoneNumber: "+8-888-888-88-88");
TheBlacksmithVakulaDbContext.InsertOrderToDatabaseAndReturn(_blacksmith.Id, _buyer.Id, products: [(_product.Id, 1)]);
TheBlacksmithVakulaDbContext.InsertOrderToDatabaseAndReturn(_blacksmith.Id, _buyer.Id, products: [(_product.Id, 1)]);
TheBlacksmithVakulaDbContext.InsertOrderToDatabaseAndReturn(_blacksmith.Id, buyer.Id, products: [(_product.Id, 1)]);
TheBlacksmithVakulaDbContext.InsertOrderToDatabaseAndReturn(_blacksmith.Id, null, products: [(_product.Id, 1)]);
var list = _ordertStorageContract.GetList(buyerId: _buyer.Id);
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(2));
@@ -103,11 +103,11 @@ namespace TheBlacksmithVakulaTests.StrorageContractTests
[Test]
public void Try_GetList_ByProductId_Test()
{
var product = InsertProductToDatabaseAndReturn("Other name");
InsertOrderToDatabaseAndReturn(_blacksmith.Id, _buyer.Id, products: [(_product.Id, 5, 1.2)]);
InsertOrderToDatabaseAndReturn(_blacksmith.Id, _buyer.Id, products: [(_product.Id, 1, 1.2), (product.Id, 4, 1.2)]);
InsertOrderToDatabaseAndReturn(_blacksmith.Id, null, products: [(product.Id, 1, 1.2)]);
InsertOrderToDatabaseAndReturn(_blacksmith.Id, null, products: [(product.Id, 1, 1.2), (_product.Id, 1, 1.2)]);
var product = TheBlacksmithVakulaDbContext.InsertProductToDatabaseAndReturn(_billet.Id, productName: "Other name");
TheBlacksmithVakulaDbContext.InsertOrderToDatabaseAndReturn(_blacksmith.Id, _buyer.Id, products: [(_product.Id, 5)]);
TheBlacksmithVakulaDbContext.InsertOrderToDatabaseAndReturn(_blacksmith.Id, _buyer.Id, products: [(_product.Id, 1), (product.Id, 4)]);
TheBlacksmithVakulaDbContext.InsertOrderToDatabaseAndReturn(_blacksmith.Id, null, products: [(product.Id, 1)]);
TheBlacksmithVakulaDbContext.InsertOrderToDatabaseAndReturn(_blacksmith.Id, null, products: [(product.Id, 1), (_product.Id, 1)]);
var list = _ordertStorageContract.GetList(productId: _product.Id);
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(3));
@@ -117,23 +117,23 @@ namespace TheBlacksmithVakulaTests.StrorageContractTests
[Test]
public void Try_GetList_ByAllParameters_Test()
{
var blacksmith = InsertBlacksmithToDatabaseAndReturn("Other blacksmith");
var buyer = InsertBuyerToDatabaseAndReturn("Other fio", "+8-888-888-88 - 88");
var product = InsertProductToDatabaseAndReturn("Other name");
InsertOrderToDatabaseAndReturn(_blacksmith.Id, _buyer.Id, orderDate:
DateTime.UtcNow.AddDays(-1).AddMinutes(-3), products: [(_product.Id, 1, 1.2)]);
InsertOrderToDatabaseAndReturn(blacksmith.Id, null, orderDate:
DateTime.UtcNow.AddDays(-1).AddMinutes(3), products: [(_product.Id, 1, 1.2)]);
InsertOrderToDatabaseAndReturn(blacksmith.Id, _buyer.Id, orderDate:
DateTime.UtcNow.AddDays(-1).AddMinutes(3), products: [(_product.Id, 1, 1.2)]);
InsertOrderToDatabaseAndReturn(blacksmith.Id, _buyer.Id, orderDate:
DateTime.UtcNow.AddDays(-1).AddMinutes(3), products: [(product.Id, 1, 1.2)]);
InsertOrderToDatabaseAndReturn(_blacksmith.Id, buyer.Id, orderDate:
DateTime.UtcNow.AddDays(1).AddMinutes(-3), products: [(_product.Id, 1, 1.2)]);
InsertOrderToDatabaseAndReturn(_blacksmith.Id, _buyer.Id, orderDate:
DateTime.UtcNow.AddDays(1).AddMinutes(-3), products: [(product.Id, 1, 1.2)]);
InsertOrderToDatabaseAndReturn(blacksmith.Id, null, orderDate:
DateTime.UtcNow.AddDays(1).AddMinutes(-3), products: [(_product.Id, 1, 1.2)]);
var blacksmith = TheBlacksmithVakulaDbContext.InsertBlacksmithToDatabaseAndReturn("Other blacksmith");
var buyer = TheBlacksmithVakulaDbContext.InsertBuyerToDatabaseAndReturn("Other fio", phoneNumber: "+8-888-888-88-88");
var product = TheBlacksmithVakulaDbContext.InsertProductToDatabaseAndReturn(_billet.Id, productName: "Other name");
TheBlacksmithVakulaDbContext.InsertOrderToDatabaseAndReturn(_blacksmith.Id, _buyer.Id, orderDate:
DateTime.UtcNow.AddDays(-1).AddMinutes(-3), products: [(_product.Id, 1)]);
TheBlacksmithVakulaDbContext.InsertOrderToDatabaseAndReturn(blacksmith.Id, null, orderDate:
DateTime.UtcNow.AddDays(-1).AddMinutes(3), products: [(_product.Id, 1)]);
TheBlacksmithVakulaDbContext.InsertOrderToDatabaseAndReturn(blacksmith.Id, _buyer.Id, orderDate:
DateTime.UtcNow.AddDays(-1).AddMinutes(3), products: [(_product.Id, 1)]);
TheBlacksmithVakulaDbContext.InsertOrderToDatabaseAndReturn(blacksmith.Id, _buyer.Id, orderDate:
DateTime.UtcNow.AddDays(-1).AddMinutes(3), products: [(product.Id, 1)]);
TheBlacksmithVakulaDbContext.InsertOrderToDatabaseAndReturn(_blacksmith.Id, buyer.Id, orderDate:
DateTime.UtcNow.AddDays(1).AddMinutes(-3), products: [(_product.Id, 1)]);
TheBlacksmithVakulaDbContext.InsertOrderToDatabaseAndReturn(_blacksmith.Id, _buyer.Id, orderDate:
DateTime.UtcNow.AddDays(1).AddMinutes(-3), products: [(product.Id, 1)]);
TheBlacksmithVakulaDbContext.InsertOrderToDatabaseAndReturn(blacksmith.Id, null, orderDate:
DateTime.UtcNow.AddDays(1).AddMinutes(-3), products: [(_product.Id, 1)]);
var list = _ordertStorageContract.GetList(startDate:
DateTime.UtcNow.AddDays(-1), endDate: DateTime.UtcNow.AddDays(1), blacksmithId:
_blacksmith.Id, buyerId: _buyer.Id, productId: product.Id);
@@ -144,21 +144,21 @@ namespace TheBlacksmithVakulaTests.StrorageContractTests
[Test]
public void Try_GetElementById_WhenHaveRecord_Test()
{
var order = InsertOrderToDatabaseAndReturn(_blacksmith.Id, _buyer.Id, products: [(_product.Id, 1, 1.2)]);
var order = TheBlacksmithVakulaDbContext.InsertOrderToDatabaseAndReturn(_blacksmith.Id, _buyer.Id, products: [(_product.Id, 1)]);
AssertElement(_ordertStorageContract.GetElementById(order.Id), order);
}
[Test]
public void Try_GetElementById_WhenNoRecord_Test()
{
InsertOrderToDatabaseAndReturn(_blacksmith.Id, _buyer.Id, products: [(_product.Id, 1, 1.2)]);
TheBlacksmithVakulaDbContext.InsertOrderToDatabaseAndReturn(_blacksmith.Id, _buyer.Id, products: [(_product.Id, 1)]);
Assert.That(() => _ordertStorageContract.GetElementById(Guid.NewGuid().ToString()), Is.Null);
}
[Test]
public void Try_GetElementById_WhenRecordHasCanceled_Test()
{
var order = InsertOrderToDatabaseAndReturn(_blacksmith.Id, _buyer.Id, products: [(_product.Id, 1, 1.2)], isCancel: true);
var order = TheBlacksmithVakulaDbContext.InsertOrderToDatabaseAndReturn(_blacksmith.Id, _buyer.Id, products: [(_product.Id, 1)], isCancel: true);
AssertElement(_ordertStorageContract.GetElementById(order.Id), order);
}
@@ -168,7 +168,7 @@ namespace TheBlacksmithVakulaTests.StrorageContractTests
var order = CreateModel(Guid.NewGuid().ToString(), _blacksmith.Id, _buyer.Id, DiscountType.RegularCustomer,
false, [_product.Id]);
_ordertStorageContract.AddElement(order);
AssertElement(GetOrderFromDatabaseById(order.Id), order);
AssertElement(TheBlacksmithVakulaDbContext.GetOrderFromDatabaseById(order.Id), order);
}
[Test]
@@ -177,16 +177,16 @@ namespace TheBlacksmithVakulaTests.StrorageContractTests
var order = CreateModel(Guid.NewGuid().ToString(), _blacksmith.Id, _buyer.Id, DiscountType.RegularCustomer,
true, [_product.Id]);
Assert.That(() => _ordertStorageContract.AddElement(order), Throws.Nothing);
AssertElement(GetOrderFromDatabaseById(order.Id), CreateModel(order.Id, _blacksmith.Id, _buyer.Id,
AssertElement(TheBlacksmithVakulaDbContext.GetOrderFromDatabaseById(order.Id), CreateModel(order.Id, _blacksmith.Id, _buyer.Id,
DiscountType.RegularCustomer, false, [_product.Id]));
}
[Test]
public void Try_DelElement_Test()
{
var order = InsertOrderToDatabaseAndReturn(_blacksmith.Id, _buyer.Id, products: [(_product.Id, 1, 1.2)], isCancel: false);
var order = TheBlacksmithVakulaDbContext.InsertOrderToDatabaseAndReturn(_blacksmith.Id, _buyer.Id, products: [(_product.Id, 1)], isCancel: false);
_ordertStorageContract.DelElement(order.Id);
var element = GetOrderFromDatabaseById(order.Id);
var element = TheBlacksmithVakulaDbContext.GetOrderFromDatabaseById(order.Id);
Assert.Multiple(() =>
{
Assert.That(element, Is.Not.Null);
@@ -203,98 +203,10 @@ namespace TheBlacksmithVakulaTests.StrorageContractTests
[Test]
public void Try_DelElement_WhenRecordWasCanceled_Test()
{
var order = InsertOrderToDatabaseAndReturn(_blacksmith.Id, _buyer.Id, products: [(_product.Id, 1, 1.2)], isCancel: true);
var order = TheBlacksmithVakulaDbContext.InsertOrderToDatabaseAndReturn(_blacksmith.Id, _buyer.Id, products: [(_product.Id, 1)], isCancel: true);
Assert.That(() => _ordertStorageContract.DelElement(order.Id), Throws.TypeOf<ElementDeletedException>());
}
private Buyer InsertBuyerToDatabaseAndReturn(string fio = "test", string phoneNumber = "+7-777-777-77-77")
{
var buyer = new Buyer()
{
Id = Guid.NewGuid().ToString(),
FIO = fio,
PhoneNumber = phoneNumber,
DiscountSize = 10
};
TheBlacksmithVakulaDbContext.Buyers.Add(buyer);
TheBlacksmithVakulaDbContext.SaveChanges();
return buyer;
}
private Blacksmith InsertBlacksmithToDatabaseAndReturn(string fio = "test")
{
var blacksmith = new Blacksmith()
{
Id = Guid.NewGuid().ToString(),
FIO = fio,
RankId = Guid.NewGuid().ToString()
};
TheBlacksmithVakulaDbContext.Blacksmiths.Add(blacksmith);
TheBlacksmithVakulaDbContext.SaveChanges();
return blacksmith;
}
private Billet InsertBilletToDatabaseAndReturn()
{
var manufacrurer = new Billet()
{
Id = Guid.NewGuid().ToString(),
BilletName = "name"
};
TheBlacksmithVakulaDbContext.Billets.Add(manufacrurer);
TheBlacksmithVakulaDbContext.SaveChanges();
return manufacrurer;
}
private Product InsertProductToDatabaseAndReturn(string productName = "test", ProductType productType = ProductType.Tool,
double price = 1, bool isDeleted = false)
{
var product = new Product()
{
Id = Guid.NewGuid().ToString(),
BilletId = _billet.Id,
ProductName = productName,
ProductType = productType,
Price = price,
IsDeleted = isDeleted
};
TheBlacksmithVakulaDbContext.Products.Add(product);
TheBlacksmithVakulaDbContext.SaveChanges();
return product;
}
private Order InsertOrderToDatabaseAndReturn(string blacksmithId, string? buyerId, DateTime? orderDate = null, double sum = 1,
DiscountType discountType = DiscountType.Certificate, double discount = 0, bool isCancel = false,
List<(string, int, double)>? products = null)
{
var order = new Order()
{
BlacksmithId = blacksmithId,
BuyerId = buyerId,
OrderDate = orderDate ?? DateTime.UtcNow,
Sum = sum,
DiscountType = discountType,
Discount = discount,
IsCancel = isCancel,
OrderProducts = []
};
if (products is not null)
{
foreach (var elem in products)
{
order.OrderProducts.Add(new OrderProduct
{
ProductId = elem.Item1,
OrderId = order.Id,
Count = elem.Item2
});
}
}
TheBlacksmithVakulaDbContext.Orders.Add(order);
TheBlacksmithVakulaDbContext.SaveChanges();
return order;
}
private static void AssertElement(OrderDataModel? actual, Order expected)
{
Assert.That(actual, Is.Not.Null);
@@ -330,12 +242,9 @@ namespace TheBlacksmithVakulaTests.StrorageContractTests
bool isCancel, List<string> productIds)
{
var products = productIds.Select(x => new OrderProductDataModel(id, x, 1)).ToList();
return new(id, blacksmithId, buyerId, 50, discountType, 0, isCancel, products);
return new(id, blacksmithId, buyerId, discountType, isCancel, products);
}
private Order? GetOrderFromDatabaseById(string id) =>
TheBlacksmithVakulaDbContext.Orders.Include(x => x.OrderProducts).FirstOrDefault(x => x.Id == id);
private static void AssertElement(Order? actual, OrderDataModel expected)
{
Assert.That(actual, Is.Not.Null);

View File

@@ -1,9 +1,9 @@
using Microsoft.EntityFrameworkCore;
using TheBlacksmithVakulaContract.DataModels;
using TheBlacksmithVakulaContract.DataModels;
using TheBlacksmithVakulaContract.Enums;
using TheBlacksmithVakulaContract.Exceptions;
using TheBlacksmithVakulaDatabase.Implementations;
using TheBlacksmithVakulaDatabase.Models;
using TheBlacksmithVakulaTests.Infrastructure;
namespace TheBlacksmithVakulaTests.StrorageContractTests
{
@@ -17,22 +17,22 @@ namespace TheBlacksmithVakulaTests.StrorageContractTests
public void SetUp()
{
_productStorageContract = new ProductStorageContract(TheBlacksmithVakulaDbContext);
_billet = InsertBilletToDatabaseAndReturn();
_billet = TheBlacksmithVakulaDbContext.InsertBilletToDatabaseAndReturn();
}
[TearDown]
public void TearDown()
{
TheBlacksmithVakulaDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Products\"CASCADE;");
TheBlacksmithVakulaDbContext.Database.ExecuteSqlRaw("TRUNCATE\"Billets\" CASCADE;");
TheBlacksmithVakulaDbContext.RemoveProductsFromDatabase();
TheBlacksmithVakulaDbContext.RemoveBilletsFromDatabase();
}
[Test]
public void Try_GetList_WhenHaveRecords_Test()
{
var product = InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), _billet.Id, "name 1");
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), _billet.Id, "name 2");
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), _billet.Id, "name 3");
var product = TheBlacksmithVakulaDbContext.InsertProductToDatabaseAndReturn(_billet.Id, productName: "name 1");
TheBlacksmithVakulaDbContext.InsertProductToDatabaseAndReturn(_billet.Id, productName: "name 2");
TheBlacksmithVakulaDbContext.InsertProductToDatabaseAndReturn(_billet.Id, productName: "name 3");
var list = _productStorageContract.GetList();
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(3));
@@ -50,9 +50,9 @@ namespace TheBlacksmithVakulaTests.StrorageContractTests
[Test]
public void Try_GetList_OnlyActual_Test()
{
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), _billet.Id, "name 1", isDeleted: true);
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), _billet.Id, "name 2", isDeleted: false);
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), _billet.Id, "name 3", isDeleted: false);
TheBlacksmithVakulaDbContext.InsertProductToDatabaseAndReturn(_billet.Id, productName: "name 1", isDeleted: true);
TheBlacksmithVakulaDbContext.InsertProductToDatabaseAndReturn(_billet.Id, productName: "name 2", isDeleted: false);
TheBlacksmithVakulaDbContext.InsertProductToDatabaseAndReturn(_billet.Id, productName: "name 3", isDeleted: false);
var list = _productStorageContract.GetList(onlyActive: true);
Assert.That(list, Is.Not.Null);
Assert.Multiple(() =>
@@ -65,9 +65,9 @@ namespace TheBlacksmithVakulaTests.StrorageContractTests
[Test]
public void Try_GetList_IncludeNoActual_Test()
{
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), _billet.Id, "name 1", isDeleted: true);
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), _billet.Id, "name 2", isDeleted: true);
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), _billet.Id, "name 3", isDeleted: false);
TheBlacksmithVakulaDbContext.InsertProductToDatabaseAndReturn(_billet.Id, productName: "name 1", isDeleted: true);
TheBlacksmithVakulaDbContext.InsertProductToDatabaseAndReturn(_billet.Id, productName: "name 2", isDeleted: true);
TheBlacksmithVakulaDbContext.InsertProductToDatabaseAndReturn(_billet.Id, productName: "name 3", isDeleted: false);
var list = _productStorageContract.GetList(onlyActive: false);
Assert.That(list, Is.Not.Null);
Assert.Multiple(() =>
@@ -81,10 +81,10 @@ namespace TheBlacksmithVakulaTests.StrorageContractTests
[Test]
public void Try_GetList_ByBillet_Test()
{
var manufacruer = InsertBilletToDatabaseAndReturn("name 2");
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), _billet.Id, "name 1", isDeleted: true);
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), _billet.Id, "name 2", isDeleted: false);
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), manufacruer.Id, "name 3", isDeleted: false);
var billet = TheBlacksmithVakulaDbContext.InsertBilletToDatabaseAndReturn(billetName: "name 2");
TheBlacksmithVakulaDbContext.InsertProductToDatabaseAndReturn(_billet.Id, productName: "name 1", isDeleted: true);
TheBlacksmithVakulaDbContext.InsertProductToDatabaseAndReturn(_billet.Id, productName: "name 2", isDeleted: false);
TheBlacksmithVakulaDbContext.InsertProductToDatabaseAndReturn(billet.Id, productName: "name 3", isDeleted: false);
var list = _productStorageContract.GetList(billetId: _billet.Id, onlyActive: false);
Assert.That(list, Is.Not.Null);
Assert.Multiple(() =>
@@ -97,10 +97,10 @@ namespace TheBlacksmithVakulaTests.StrorageContractTests
[Test]
public void Try_GetList_ByBilletOnlyActual_Test()
{
var manufacruer = InsertBilletToDatabaseAndReturn("name 2");
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), _billet.Id, "name 1", isDeleted: true);
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), _billet.Id, "name 2", isDeleted: false);
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), manufacruer.Id, "name 3", isDeleted: false);
var billet = TheBlacksmithVakulaDbContext.InsertBilletToDatabaseAndReturn(billetName: "name 2");
TheBlacksmithVakulaDbContext.InsertProductToDatabaseAndReturn(_billet.Id, productName: "name 1", isDeleted: true);
TheBlacksmithVakulaDbContext.InsertProductToDatabaseAndReturn(_billet.Id, productName: "name 2", isDeleted: false);
TheBlacksmithVakulaDbContext.InsertProductToDatabaseAndReturn(billet.Id, productName: "name 3", isDeleted: false);
var list = _productStorageContract.GetList(billetId: _billet.Id, onlyActive: true);
Assert.That(list, Is.Not.Null);
Assert.Multiple(() =>
@@ -113,10 +113,10 @@ namespace TheBlacksmithVakulaTests.StrorageContractTests
[Test]
public void Try_GetHistoryByProductId_WhenHaveRecords_Test()
{
var product = InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), _billet.Id, "name 1");
InsertProductHistoryToDatabaseAndReturn(product.Id, 20, DateTime.UtcNow.AddDays(-1));
InsertProductHistoryToDatabaseAndReturn(product.Id, 30, DateTime.UtcNow.AddMinutes(-10));
InsertProductHistoryToDatabaseAndReturn(product.Id, 40, DateTime.UtcNow.AddDays(1));
var product = TheBlacksmithVakulaDbContext.InsertProductToDatabaseAndReturn(_billet.Id, productName: "name 1");
TheBlacksmithVakulaDbContext.InsertProductHistoryToDatabaseAndReturn(product.Id, 20, DateTime.UtcNow.AddDays(-1));
TheBlacksmithVakulaDbContext.InsertProductHistoryToDatabaseAndReturn(product.Id, 30, DateTime.UtcNow.AddMinutes(-10));
TheBlacksmithVakulaDbContext.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));
@@ -125,10 +125,10 @@ namespace TheBlacksmithVakulaTests.StrorageContractTests
[Test]
public void Try_GetHistoryByProductId_WhenNoRecords_Test()
{
var product = InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), _billet.Id, "name 1");
InsertProductHistoryToDatabaseAndReturn(product.Id, 20, DateTime.UtcNow.AddDays(-1));
InsertProductHistoryToDatabaseAndReturn(product.Id, 30, DateTime.UtcNow.AddMinutes(-10));
InsertProductHistoryToDatabaseAndReturn(product.Id, 40, DateTime.UtcNow.AddDays(1));
var product = TheBlacksmithVakulaDbContext.InsertProductToDatabaseAndReturn(_billet.Id, productName: "name 1");
TheBlacksmithVakulaDbContext.InsertProductHistoryToDatabaseAndReturn(product.Id, 20, DateTime.UtcNow.AddDays(-1));
TheBlacksmithVakulaDbContext.InsertProductHistoryToDatabaseAndReturn(product.Id, 30, DateTime.UtcNow.AddMinutes(-10));
TheBlacksmithVakulaDbContext.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));
@@ -137,42 +137,42 @@ namespace TheBlacksmithVakulaTests.StrorageContractTests
[Test]
public void Try_GetElementById_WhenHaveRecord_Test()
{
var product = InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), _billet.Id);
var product = TheBlacksmithVakulaDbContext.InsertProductToDatabaseAndReturn(_billet.Id, _billet.Id);
AssertElement(_productStorageContract.GetElementById(product.Id), product);
}
[Test]
public void Try_GetElementById_WhenNoRecord_Test()
{
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), _billet.Id);
TheBlacksmithVakulaDbContext.InsertProductToDatabaseAndReturn(_billet.Id, _billet.Id);
Assert.That(() => _productStorageContract.GetElementById(Guid.NewGuid().ToString()), Is.Null);
}
[Test]
public void Try_GetElementById_WhenRecordHasDeleted_Test()
{
var product = InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), _billet.Id, isDeleted: true);
var product = TheBlacksmithVakulaDbContext.InsertProductToDatabaseAndReturn(_billet.Id, isDeleted: true);
Assert.That(() => _productStorageContract.GetElementById(product.Id), Is.Null);
}
[Test]
public void Try_GetElementByName_WhenHaveRecord_Test()
{
var product = InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), _billet.Id);
var product = TheBlacksmithVakulaDbContext.InsertProductToDatabaseAndReturn(_billet.Id, _billet.Id);
AssertElement(_productStorageContract.GetElementByName(product.ProductName), product);
}
[Test]
public void Try_GetElementByName_WhenNoRecord_Test()
{
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), _billet.Id);
TheBlacksmithVakulaDbContext.InsertProductToDatabaseAndReturn(_billet.Id, _billet.Id);
Assert.That(() => _productStorageContract.GetElementByName("name"), Is.Null);
}
[Test]
public void Try_GetElementByName_WhenRecordHasDeleted_Test()
{
var product = InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), _billet.Id, isDeleted: true);
var product = TheBlacksmithVakulaDbContext.InsertProductToDatabaseAndReturn(_billet.Id, isDeleted: true);
Assert.That(() => _productStorageContract.GetElementById(product.ProductName), Is.Null);
}
@@ -181,7 +181,7 @@ namespace TheBlacksmithVakulaTests.StrorageContractTests
{
var product = CreateModel(Guid.NewGuid().ToString(), _billet.Id, isDeleted: false);
_productStorageContract.AddElement(product);
AssertElement(GetProductFromDatabaseById(product.Id), product);
AssertElement(TheBlacksmithVakulaDbContext.GetProductFromDatabaseById(product.Id), product);
}
[Test]
@@ -189,7 +189,7 @@ namespace TheBlacksmithVakulaTests.StrorageContractTests
{
var product = CreateModel(Guid.NewGuid().ToString(), _billet.Id, isDeleted: true);
Assert.That(() => _productStorageContract.AddElement(product), Throws.Nothing);
AssertElement(GetProductFromDatabaseById(product.Id),
AssertElement(TheBlacksmithVakulaDbContext.GetProductFromDatabaseById(product.Id),
CreateModel(product.Id, _billet.Id, isDeleted: false));
}
@@ -197,7 +197,7 @@ namespace TheBlacksmithVakulaTests.StrorageContractTests
public void Try_AddElement_WhenHaveRecordWithSameId_Test()
{
var product = CreateModel(Guid.NewGuid().ToString(), _billet.Id);
InsertProductToDatabaseAndReturn(product.Id, _billet.Id, productName: "name unique");
TheBlacksmithVakulaDbContext.InsertProductToDatabaseAndReturn(_billet.Id, id: product.Id, productName: "name unique");
Assert.That(() => _productStorageContract.AddElement(product), Throws.TypeOf<ElementExistsException>());
}
@@ -205,7 +205,7 @@ namespace TheBlacksmithVakulaTests.StrorageContractTests
public void Try_AddElement_WhenHaveRecordWithSameName_Test()
{
var product = CreateModel(Guid.NewGuid().ToString(), _billet.Id, "name unique", isDeleted: false);
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), _billet.Id, productName: product.ProductName, isDeleted: false);
TheBlacksmithVakulaDbContext.InsertProductToDatabaseAndReturn(_billet.Id, productName: product.ProductName, isDeleted: false);
Assert.That(() => _productStorageContract.AddElement(product), Throws.TypeOf<ElementExistsException>());
}
@@ -213,7 +213,7 @@ namespace TheBlacksmithVakulaTests.StrorageContractTests
public void Try_AddElement_WhenHaveRecordWithSameNameButOneWasDeleted_Test()
{
var product = CreateModel(Guid.NewGuid().ToString(), _billet.Id, "name unique", isDeleted: false);
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), _billet.Id, productName: product.ProductName, isDeleted: true);
TheBlacksmithVakulaDbContext.InsertProductToDatabaseAndReturn(_billet.Id, productName: product.ProductName, isDeleted: true);
Assert.That(() => _productStorageContract.AddElement(product), Throws.Nothing);
}
@@ -221,18 +221,18 @@ namespace TheBlacksmithVakulaTests.StrorageContractTests
public void Try_UpdElement_Test()
{
var product = CreateModel(Guid.NewGuid().ToString(), _billet.Id, isDeleted: false);
InsertProductToDatabaseAndReturn(product.Id, _billet.Id, isDeleted: false);
TheBlacksmithVakulaDbContext.InsertProductToDatabaseAndReturn(_billet.Id, id: product.Id, isDeleted: false);
_productStorageContract.UpdElement(product);
AssertElement(GetProductFromDatabaseById(product.Id), product);
AssertElement(TheBlacksmithVakulaDbContext.GetProductFromDatabaseById(product.Id), product);
}
[Test]
public void Try_UpdElement_WhenIsDeletedIsTrue_Test()
{
var product = CreateModel(Guid.NewGuid().ToString(), _billet.Id, isDeleted: true);
InsertProductToDatabaseAndReturn(product.Id, _billet.Id, isDeleted: false);
TheBlacksmithVakulaDbContext.InsertProductToDatabaseAndReturn(_billet.Id, id: product.Id, isDeleted: false);
_productStorageContract.UpdElement(product);
AssertElement(GetProductFromDatabaseById(product.Id),
AssertElement(TheBlacksmithVakulaDbContext.GetProductFromDatabaseById(product.Id),
CreateModel(product.Id, _billet.Id, isDeleted: false));
}
@@ -247,8 +247,8 @@ namespace TheBlacksmithVakulaTests.StrorageContractTests
public void Try_UpdElement_WhenHaveRecordWithSameName_Test()
{
var product = CreateModel(Guid.NewGuid().ToString(), _billet.Id, "name unique", isDeleted: false);
InsertProductToDatabaseAndReturn(product.Id, _billet.Id, productName: "name");
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), _billet.Id, productName: product.ProductName);
TheBlacksmithVakulaDbContext.InsertProductToDatabaseAndReturn(_billet.Id, id: product.Id, productName: "name");
TheBlacksmithVakulaDbContext.InsertProductToDatabaseAndReturn(_billet.Id, productName: product.ProductName);
Assert.That(() => _productStorageContract.UpdElement(product), Throws.TypeOf<ElementExistsException>());
}
@@ -257,8 +257,8 @@ namespace TheBlacksmithVakulaTests.StrorageContractTests
Try_UpdElement_WhenHaveRecordWithSameNameButOneWasDeleted_Test()
{
var product = CreateModel(Guid.NewGuid().ToString(), _billet.Id, "name unique", isDeleted: false);
InsertProductToDatabaseAndReturn(product.Id, _billet.Id, productName: "name");
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), _billet.Id, productName: product.ProductName, isDeleted: true);
TheBlacksmithVakulaDbContext.InsertProductToDatabaseAndReturn(_billet.Id, id: product.Id, productName: "name");
TheBlacksmithVakulaDbContext.InsertProductToDatabaseAndReturn(_billet.Id, productName: product.ProductName, isDeleted: true);
Assert.That(() => _productStorageContract.UpdElement(product), Throws.Nothing);
}
@@ -266,16 +266,16 @@ namespace TheBlacksmithVakulaTests.StrorageContractTests
public void Try_UpdElement_WhenRecordWasDeleted_Test()
{
var product = CreateModel(Guid.NewGuid().ToString(), _billet.Id);
InsertProductToDatabaseAndReturn(product.Id, _billet.Id, isDeleted: true);
TheBlacksmithVakulaDbContext.InsertProductToDatabaseAndReturn(_billet.Id, id: product.Id, isDeleted: true);
Assert.That(() => _productStorageContract.UpdElement(product), Throws.TypeOf<ElementNotFoundException>());
}
[Test]
public void Try_DelElement_Test()
{
var product = InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), _billet.Id, isDeleted: false);
var product = TheBlacksmithVakulaDbContext.InsertProductToDatabaseAndReturn(_billet.Id, isDeleted: false);
_productStorageContract.DelElement(product.Id);
var element = GetProductFromDatabaseById(product.Id);
var element = TheBlacksmithVakulaDbContext.GetProductFromDatabaseById(product.Id);
Assert.Multiple(() =>
{
Assert.That(element, Is.Not.Null);
@@ -292,53 +292,10 @@ namespace TheBlacksmithVakulaTests.StrorageContractTests
[Test]
public void Try_DelElement_WhenRecordWasDeleted_Test()
{
var product = InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), _billet.Id, isDeleted: true);
var product = TheBlacksmithVakulaDbContext.InsertProductToDatabaseAndReturn(_billet.Id, isDeleted: true);
Assert.That(() => _productStorageContract.DelElement(product.Id), Throws.TypeOf<ElementNotFoundException>());
}
private Billet InsertBilletToDatabaseAndReturn(string billetName = "name")
{
var manufacrurer = new Billet()
{
Id = Guid.NewGuid().ToString(),
BilletName = billetName
};
TheBlacksmithVakulaDbContext.Billets.Add(manufacrurer);
TheBlacksmithVakulaDbContext.SaveChanges();
return manufacrurer;
}
private Product InsertProductToDatabaseAndReturn(string id, string billetId, string productName = "test",
ProductType productType = ProductType.Tool, double price = 1, bool isDeleted = false)
{
var product = new Product()
{
Id = id,
BilletId = billetId,
ProductName = productName,
ProductType = productType,
Price = price,
IsDeleted = isDeleted
};
TheBlacksmithVakulaDbContext.Products.Add(product);
TheBlacksmithVakulaDbContext.SaveChanges();
return product;
}
private ProductHistory InsertProductHistoryToDatabaseAndReturn(string productId, double price, DateTime changeDate)
{
var productHistory = new ProductHistory()
{
Id = Guid.NewGuid().ToString(),
ProductId = productId,
OldPrice = price,
ChangeDate = changeDate
};
TheBlacksmithVakulaDbContext.ProductHistories.Add(productHistory);
TheBlacksmithVakulaDbContext.SaveChanges();
return productHistory;
}
private static void AssertElement(ProductDataModel? actual, Product expected)
{
Assert.That(actual, Is.Not.Null);
@@ -357,8 +314,6 @@ namespace TheBlacksmithVakulaTests.StrorageContractTests
ProductType productType = ProductType.Tool, double price = 1, bool isDeleted = false)
=> new(id, productName, productType, billetId, price, isDeleted);
private Product? GetProductFromDatabaseById(string id) => TheBlacksmithVakulaDbContext.Products.FirstOrDefault(x => x.Id == id);
private static void AssertElement(Product? actual, ProductDataModel expected)
{
Assert.That(actual, Is.Not.Null);

View File

@@ -1,9 +1,9 @@
using Microsoft.EntityFrameworkCore;
using TheBlacksmithVakulaContract.Exceptions;
using TheBlacksmithVakulaContract.Exceptions;
using TheBlacksmithVakulaDatabase.Implementations;
using TheBlacksmithVakulaContract.DataModels;
using TheBlacksmithVakulaDatabase.Models;
using TheBlacksmithVakulaContract.Enums;
using TheBlacksmithVakulaTests.Infrastructure;
namespace TheBlacksmithVakulaTests.StrorageContractTests
{
@@ -21,15 +21,15 @@ namespace TheBlacksmithVakulaTests.StrorageContractTests
[TearDown]
public void TearDown()
{
TheBlacksmithVakulaDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Ranks\"CASCADE; ");
TheBlacksmithVakulaDbContext.RemoveRanksFromDatabase();
}
[Test]
public void Try_GetList_WhenHaveRecords_Test()
{
var rank = InsertRankToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 1");
InsertRankToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 2");
InsertRankToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 3");
var rank = TheBlacksmithVakulaDbContext.InsertRankToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 1");
TheBlacksmithVakulaDbContext.InsertRankToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 2");
TheBlacksmithVakulaDbContext.InsertRankToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 3");
var list = _rankStorageContract.GetList();
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(3));
@@ -48,9 +48,9 @@ namespace TheBlacksmithVakulaTests.StrorageContractTests
public void Try_GetRankWithHistory_WhenHaveRecords_Test()
{
var rankId = Guid.NewGuid().ToString();
InsertRankToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 1", isActual: true);
InsertRankToDatabaseAndReturn(rankId, "name 2", isActual: true);
InsertRankToDatabaseAndReturn(rankId, "name 2", isActual: false);
TheBlacksmithVakulaDbContext.InsertRankToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 1", isActual: true);
TheBlacksmithVakulaDbContext.InsertRankToDatabaseAndReturn(rankId, "name 2", isActual: true);
TheBlacksmithVakulaDbContext.InsertRankToDatabaseAndReturn(rankId, "name 2", isActual: false);
var list = _rankStorageContract.GetRankWithHistory(rankId);
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(2));
@@ -60,9 +60,9 @@ namespace TheBlacksmithVakulaTests.StrorageContractTests
public void Try_GetRankWithHistory_WhenNoRecords_Test()
{
var rankId = Guid.NewGuid().ToString();
InsertRankToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 1", isActual: true);
InsertRankToDatabaseAndReturn(rankId, "name 2", isActual: true);
InsertRankToDatabaseAndReturn(rankId, "name 2", isActual: false);
TheBlacksmithVakulaDbContext.InsertRankToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 1", isActual: true);
TheBlacksmithVakulaDbContext.InsertRankToDatabaseAndReturn(rankId, "name 2", isActual: true);
TheBlacksmithVakulaDbContext.InsertRankToDatabaseAndReturn(rankId, "name 2", isActual: false);
var list = _rankStorageContract.GetRankWithHistory(Guid.NewGuid().ToString());
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
@@ -71,49 +71,49 @@ namespace TheBlacksmithVakulaTests.StrorageContractTests
[Test]
public void Try_GetElementById_WhenHaveRecord_Test()
{
var rank = InsertRankToDatabaseAndReturn(Guid.NewGuid().ToString());
var rank = TheBlacksmithVakulaDbContext.InsertRankToDatabaseAndReturn(Guid.NewGuid().ToString());
AssertElement(_rankStorageContract.GetElementById(rank.RankId), rank);
}
[Test]
public void Try_GetElementById_WhenNoRecord_Test()
{
InsertRankToDatabaseAndReturn(Guid.NewGuid().ToString());
TheBlacksmithVakulaDbContext.InsertRankToDatabaseAndReturn(Guid.NewGuid().ToString());
Assert.That(() => _rankStorageContract.GetElementById(Guid.NewGuid().ToString()), Is.Null);
}
[Test]
public void Try_GetElementById_WhenRecordHasDeleted_Test()
{
var rank = InsertRankToDatabaseAndReturn(Guid.NewGuid().ToString(), isActual: false);
var rank = TheBlacksmithVakulaDbContext.InsertRankToDatabaseAndReturn(Guid.NewGuid().ToString(), isActual: false);
Assert.That(() => _rankStorageContract.GetElementById(rank.RankId), Is.Null);
}
[Test]
public void Try_GetElementById_WhenTrySearchById_Test()
{
var rank = InsertRankToDatabaseAndReturn(Guid.NewGuid().ToString());
var rank = TheBlacksmithVakulaDbContext.InsertRankToDatabaseAndReturn(Guid.NewGuid().ToString());
Assert.That(() => _rankStorageContract.GetElementById(rank.Id), Is.Null);
}
[Test]
public void Try_GetElementByName_WhenHaveRecord_Test()
{
var rank = InsertRankToDatabaseAndReturn(Guid.NewGuid().ToString());
var rank = TheBlacksmithVakulaDbContext.InsertRankToDatabaseAndReturn(Guid.NewGuid().ToString());
AssertElement(_rankStorageContract.GetElementByName(rank.RankName), rank);
}
[Test]
public void Try_GetElementByName_WhenNoRecord_Test()
{
InsertRankToDatabaseAndReturn(Guid.NewGuid().ToString());
TheBlacksmithVakulaDbContext.InsertRankToDatabaseAndReturn(Guid.NewGuid().ToString());
Assert.That(() => _rankStorageContract.GetElementByName("name"), Is.Null);
}
[Test]
public void Try_GetElementByName_WhenRecordHasDeleted_Test()
{
var rank = InsertRankToDatabaseAndReturn(Guid.NewGuid().ToString(), isActual: false);
var rank = TheBlacksmithVakulaDbContext.InsertRankToDatabaseAndReturn(Guid.NewGuid().ToString(), isActual: false);
Assert.That(() => _rankStorageContract.GetElementById(rank.RankName), Is.Null);
}
@@ -122,14 +122,14 @@ namespace TheBlacksmithVakulaTests.StrorageContractTests
{
var rank = CreateModel(Guid.NewGuid().ToString());
_rankStorageContract.AddElement(rank);
AssertElement(GetRankFromDatabaseByRankId(rank.Id), rank);
AssertElement(TheBlacksmithVakulaDbContext.GetRankFromDatabaseByRankId(rank.Id), rank);
}
[Test]
public void Try_AddElement_WhenHaveRecordWithSameName_Test()
{
var rank = CreateModel(Guid.NewGuid().ToString(), "name unique");
InsertRankToDatabaseAndReturn(Guid.NewGuid().ToString(), rankName: rank.RankName, isActual: true);
TheBlacksmithVakulaDbContext.InsertRankToDatabaseAndReturn(Guid.NewGuid().ToString(), rankName: rank.RankName, isActual: true);
Assert.That(() => _rankStorageContract.AddElement(rank), Throws.TypeOf<ElementExistsException>());
}
@@ -137,7 +137,7 @@ namespace TheBlacksmithVakulaTests.StrorageContractTests
public void Try_AddElement_WhenHaveRecordWithSameRankId_Test()
{
var rank = CreateModel(Guid.NewGuid().ToString());
InsertRankToDatabaseAndReturn(rank.Id, isActual: true);
TheBlacksmithVakulaDbContext.InsertRankToDatabaseAndReturn(rank.Id, isActual: true);
Assert.That(() => _rankStorageContract.AddElement(rank), Throws.TypeOf<ElementExistsException>());
}
@@ -145,7 +145,7 @@ namespace TheBlacksmithVakulaTests.StrorageContractTests
public void Try_UpdElement_Test()
{
var rank = CreateModel(Guid.NewGuid().ToString());
InsertRankToDatabaseAndReturn(rank.Id, isActual: true);
TheBlacksmithVakulaDbContext.InsertRankToDatabaseAndReturn(rank.Id, isActual: true);
_rankStorageContract.UpdElement(rank);
var ranks = TheBlacksmithVakulaDbContext.Ranks.Where(x => x.RankId == rank.Id).OrderByDescending(x => x.ChangeDate);
Assert.That(ranks.Count(), Is.EqualTo(2));
@@ -164,8 +164,8 @@ namespace TheBlacksmithVakulaTests.StrorageContractTests
public void Try_UpdElement_WhenHaveRecordWithSameName_Test()
{
var rank = CreateModel(Guid.NewGuid().ToString(), "New Name");
InsertRankToDatabaseAndReturn(rank.Id, rankName: "name");
InsertRankToDatabaseAndReturn(Guid.NewGuid().ToString(), rankName: rank.RankName);
TheBlacksmithVakulaDbContext.InsertRankToDatabaseAndReturn(rank.Id, rankName: "name");
TheBlacksmithVakulaDbContext.InsertRankToDatabaseAndReturn(Guid.NewGuid().ToString(), rankName: rank.RankName);
Assert.That(() => _rankStorageContract.UpdElement(rank), Throws.TypeOf<ElementExistsException>());
}
@@ -173,21 +173,17 @@ namespace TheBlacksmithVakulaTests.StrorageContractTests
public void Try_UpdElement_WhenRecordWasDeleted_Test()
{
var rank = CreateModel(Guid.NewGuid().ToString());
InsertRankToDatabaseAndReturn(rank.Id, isActual: false);
TheBlacksmithVakulaDbContext.InsertRankToDatabaseAndReturn(rank.Id, isActual: false);
Assert.That(() => _rankStorageContract.UpdElement(rank), Throws.TypeOf<ElementDeletedException>());
}
[Test]
public void Try_DelElement_Test()
{
var rank = InsertRankToDatabaseAndReturn(Guid.NewGuid().ToString(), isActual: true);
var rank = TheBlacksmithVakulaDbContext.InsertRankToDatabaseAndReturn(Guid.NewGuid().ToString(), isActual: true);
_rankStorageContract.DelElement(rank.RankId);
var element = GetRankFromDatabaseByRankId(rank.RankId);
Assert.Multiple(() =>
{
Assert.That(element, Is.Not.Null);
Assert.That(!element!.IsActual);
});
var element = TheBlacksmithVakulaDbContext.GetRankFromDatabaseByRankId(rank.RankId);
Assert.That(element, Is.Null);
}
[Test]
@@ -199,16 +195,16 @@ namespace TheBlacksmithVakulaTests.StrorageContractTests
[Test]
public void Try_DelElement_WhenRecordWasDeleted_Test()
{
var rank = InsertRankToDatabaseAndReturn(Guid.NewGuid().ToString(), isActual: false);
var rank = TheBlacksmithVakulaDbContext.InsertRankToDatabaseAndReturn(Guid.NewGuid().ToString(), isActual: false);
Assert.That(() => _rankStorageContract.DelElement(rank.RankId), Throws.TypeOf<ElementDeletedException>());
}
[Test]
public void Try_ResElement_Test()
{
var rank = InsertRankToDatabaseAndReturn(Guid.NewGuid().ToString(), isActual: false);
var rank = TheBlacksmithVakulaDbContext.InsertRankToDatabaseAndReturn(Guid.NewGuid().ToString(), isActual: false);
_rankStorageContract.ResElement(rank.RankId);
var element = GetRankFromDatabaseByRankId(rank.RankId);
var element = TheBlacksmithVakulaDbContext.GetRankFromDatabaseByRankId(rank.RankId);
Assert.Multiple(() =>
{
Assert.That(element, Is.Not.Null);
@@ -225,27 +221,10 @@ namespace TheBlacksmithVakulaTests.StrorageContractTests
[Test]
public void Try_ResElement_WhenRecordNotWasDeleted_Test()
{
var rank = InsertRankToDatabaseAndReturn(Guid.NewGuid().ToString(), isActual: true);
var rank = TheBlacksmithVakulaDbContext.InsertRankToDatabaseAndReturn(Guid.NewGuid().ToString(), isActual: true);
Assert.That(() => _rankStorageContract.ResElement(rank.RankId), Throws.Nothing);
}
private Rank InsertRankToDatabaseAndReturn(string id, string rankName = "test", RankType rankType = RankType.Student,
double salary = 10, bool isActual = true, DateTime? changeDate = null)
{
var rank = new Rank()
{
Id = Guid.NewGuid().ToString(),
RankId = id,
RankName = rankName,
RankType = rankType,
IsActual = isActual,
ChangeDate = changeDate ?? DateTime.UtcNow
};
TheBlacksmithVakulaDbContext.Ranks.Add(rank);
TheBlacksmithVakulaDbContext.SaveChanges();
return rank;
}
private static void AssertElement(RankDataModel? actual, Rank expected)
{
Assert.That(actual, Is.Not.Null);
@@ -257,11 +236,8 @@ namespace TheBlacksmithVakulaTests.StrorageContractTests
});
}
private static RankDataModel CreateModel(string rankId, string rankName = "test", RankType rankType = RankType.Student)
=> new(rankId, rankName, rankType, true, DateTime.UtcNow);
private Rank? GetRankFromDatabaseByRankId(string id) => TheBlacksmithVakulaDbContext.Ranks.Where(x => x.RankId == id)
.OrderByDescending(x => x.ChangeDate).FirstOrDefault();
private static RankDataModel CreateModel(string rankId, string rankName = "test", RankType rankType = RankType.Expert)
=> new(rankId, rankName, rankType);
private static void AssertElement(Rank? actual, RankDataModel expected)
{

View File

@@ -1,157 +1,130 @@
using Microsoft.EntityFrameworkCore;
using TheBlacksmithVakulaContract.DataModels;
using TheBlacksmithVakulaContract.DataModels;
using TheBlacksmithVakulaDatabase.Implementations;
using TheBlacksmithVakulaDatabase.Models;
using TheBlacksmithVakulaTests.Infrastructure;
namespace TheBlacksmithVakulaTests.StrorageContractTests
namespace TheBlacksmithVakulaTests.StrorageContractTests;
[TestFixture]
internal class SalaryStorageContractTests : BaseStorageContractTest
{
[TestFixture]
internal class SalaryStorageContractTests : BaseStorageContractTest
private SalaryStorageContract _salaryStorageContract;
private Blacksmith _blacksmith;
[SetUp]
public void SetUp()
{
private SalaryStorageContract _salaryStorageContract;
private Blacksmith _blacksmith;
_salaryStorageContract = new SalaryStorageContract(TheBlacksmithVakulaDbContext);
_blacksmith = TheBlacksmithVakulaDbContext.InsertBlacksmithToDatabaseAndReturn();
}
[SetUp]
public void SetUp()
{
_salaryStorageContract = new SalaryStorageContract(TheBlacksmithVakulaDbContext);
_blacksmith = InsertBlacksmithToDatabaseAndReturn();
}
[TearDown]
public void TearDown()
{
TheBlacksmithVakulaDbContext.RemoveSalariesFromDatabase();
TheBlacksmithVakulaDbContext.RemoveBlacksmithsFromDatabase();
}
[TearDown]
public void TearDown()
{
TheBlacksmithVakulaDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Salaries\"CASCADE; ");
TheBlacksmithVakulaDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Blacksmiths\"CASCADE; ");
}
[Test]
public void Try_GetList_WhenHaveRecords_Test()
{
var salary = TheBlacksmithVakulaDbContext.InsertSalaryToDatabaseAndReturn(_blacksmith.Id, blacksmithSalary: 100);
TheBlacksmithVakulaDbContext.InsertSalaryToDatabaseAndReturn(_blacksmith.Id);
TheBlacksmithVakulaDbContext.InsertSalaryToDatabaseAndReturn(_blacksmith.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.BlacksmithSalary), salary);
}
[Test]
public void Try_GetList_WhenHaveRecords_Test()
{
var salary = InsertSalaryToDatabaseAndReturn(_blacksmith.Id, blacksmithSalary: 100);
InsertSalaryToDatabaseAndReturn(_blacksmith.Id);
InsertSalaryToDatabaseAndReturn(_blacksmith.Id);
var list = _salaryStorageContract.GetList(DateTime.UtcNow.AddDays(-10), DateTime.UtcNow.AddDays(10));
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(3));
AssertElement(list.First(), salary);
}
[Test]
public void Try_GetList_WhenNoRecords_Test()
{
var list = _salaryStorageContract.GetList(DateTime.UtcNow.AddDays(-10), DateTime.UtcNow.AddDays(10));
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.Empty);
}
[Test]
public void Try_GetList_WhenNoRecords_Test()
[Test]
public void Try_GetList_OnlyInDatePeriod_Test()
{
TheBlacksmithVakulaDbContext.InsertSalaryToDatabaseAndReturn(_blacksmith.Id, salaryDate: DateTime.UtcNow.AddDays(-2));
TheBlacksmithVakulaDbContext.InsertSalaryToDatabaseAndReturn(_blacksmith.Id, salaryDate: DateTime.UtcNow.AddDays(-1).AddMinutes(-5));
TheBlacksmithVakulaDbContext.InsertSalaryToDatabaseAndReturn(_blacksmith.Id, salaryDate: DateTime.UtcNow.AddDays(-1).AddMinutes(5));
TheBlacksmithVakulaDbContext.InsertSalaryToDatabaseAndReturn(_blacksmith.Id, salaryDate: DateTime.UtcNow.AddDays(1).AddMinutes(-5));
TheBlacksmithVakulaDbContext.InsertSalaryToDatabaseAndReturn(_blacksmith.Id, salaryDate: DateTime.UtcNow.AddDays(1).AddMinutes(5));
TheBlacksmithVakulaDbContext.InsertSalaryToDatabaseAndReturn(_blacksmith.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(() =>
{
var list = _salaryStorageContract.GetList(DateTime.UtcNow.AddDays(-10), DateTime.UtcNow.AddDays(10));
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.Empty);
}
[Test]
public void Try_GetList_OnlyInDatePeriod_Test()
{
InsertSalaryToDatabaseAndReturn(_blacksmith.Id, salaryDate: DateTime.UtcNow.AddDays(-2));
InsertSalaryToDatabaseAndReturn(_blacksmith.Id, salaryDate: DateTime.UtcNow.AddDays(-1).AddMinutes(-5));
InsertSalaryToDatabaseAndReturn(_blacksmith.Id, salaryDate: DateTime.UtcNow.AddDays(-1).AddMinutes(5));
InsertSalaryToDatabaseAndReturn(_blacksmith.Id, salaryDate: DateTime.UtcNow.AddDays(1).AddMinutes(-5));
InsertSalaryToDatabaseAndReturn(_blacksmith.Id, salaryDate: DateTime.UtcNow.AddDays(1).AddMinutes(5));
InsertSalaryToDatabaseAndReturn(_blacksmith.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.That(list, Has.Count.EqualTo(2));
}
});
}
[Test]
public void Try_GetList_ByBlacksmith_Test()
[Test]
public void Try_GetList_ByBlacksmith_Test()
{
var blacksmith = TheBlacksmithVakulaDbContext.InsertBlacksmithToDatabaseAndReturn(fio: "name 2");
TheBlacksmithVakulaDbContext.InsertSalaryToDatabaseAndReturn(_blacksmith.Id);
TheBlacksmithVakulaDbContext.InsertSalaryToDatabaseAndReturn(_blacksmith.Id);
TheBlacksmithVakulaDbContext.InsertSalaryToDatabaseAndReturn(blacksmith.Id);
var list = _salaryStorageContract.GetList(DateTime.UtcNow.AddDays(-1), DateTime.UtcNow.AddDays(1), _blacksmith.Id);
Assert.That(list, Is.Not.Null);
Assert.Multiple(() =>
{
var blacksmith = InsertBlacksmithToDatabaseAndReturn("name 2");
InsertSalaryToDatabaseAndReturn(_blacksmith.Id);
InsertSalaryToDatabaseAndReturn(_blacksmith.Id);
InsertSalaryToDatabaseAndReturn(blacksmith.Id);
var list = _salaryStorageContract.GetList(DateTime.UtcNow.AddDays(-1), DateTime.UtcNow.AddDays(1), _blacksmith.Id);
Assert.That(list, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(list, Has.Count.EqualTo(2));
Assert.That(list.All(x => x.BlacksmithId == _blacksmith.Id));
});
}
Assert.That(list, Has.Count.EqualTo(2));
Assert.That(list.All(x => x.BlacksmithId == _blacksmith.Id));
});
}
[Test]
public void Try_GetList_ByBlacksmithOnlyInDatePeriod_Test()
[Test]
public void Try_GetList_ByBlacksmithOnlyInDatePeriod_Test()
{
var blacksmith = TheBlacksmithVakulaDbContext.InsertBlacksmithToDatabaseAndReturn(fio: "name 2");
TheBlacksmithVakulaDbContext.InsertSalaryToDatabaseAndReturn(_blacksmith.Id, salaryDate: DateTime.UtcNow.AddDays(-2));
TheBlacksmithVakulaDbContext.InsertSalaryToDatabaseAndReturn(_blacksmith.Id, salaryDate: DateTime.UtcNow.AddDays(-1).AddMinutes(5));
TheBlacksmithVakulaDbContext.InsertSalaryToDatabaseAndReturn(blacksmith.Id, salaryDate: DateTime.UtcNow.AddDays(-1).AddMinutes(5));
TheBlacksmithVakulaDbContext.InsertSalaryToDatabaseAndReturn(_blacksmith.Id, salaryDate: DateTime.UtcNow.AddDays(1).AddMinutes(-5));
TheBlacksmithVakulaDbContext.InsertSalaryToDatabaseAndReturn(blacksmith.Id, salaryDate: DateTime.UtcNow.AddDays(1).AddMinutes(-5));
TheBlacksmithVakulaDbContext.InsertSalaryToDatabaseAndReturn(_blacksmith.Id, salaryDate: DateTime.UtcNow.AddDays(-2));
var list = _salaryStorageContract.GetList(DateTime.UtcNow.AddDays(-1), DateTime.UtcNow.AddDays(1), _blacksmith.Id);
Assert.That(list, Is.Not.Null);
Assert.Multiple(() =>
{
var blacksmith = InsertBlacksmithToDatabaseAndReturn("name 2");
InsertSalaryToDatabaseAndReturn(_blacksmith.Id, salaryDate: DateTime.UtcNow.AddDays(-2));
InsertSalaryToDatabaseAndReturn(_blacksmith.Id, salaryDate: DateTime.UtcNow.AddDays(-1).AddMinutes(5));
InsertSalaryToDatabaseAndReturn(blacksmith.Id, salaryDate: DateTime.UtcNow.AddDays(-1).AddMinutes(5));
InsertSalaryToDatabaseAndReturn(_blacksmith.Id, salaryDate: DateTime.UtcNow.AddDays(1).AddMinutes(-5));
InsertSalaryToDatabaseAndReturn(blacksmith.Id, salaryDate: DateTime.UtcNow.AddDays(1).AddMinutes(-5));
InsertSalaryToDatabaseAndReturn(_blacksmith.Id, salaryDate: DateTime.UtcNow.AddDays(-2));
var list = _salaryStorageContract.GetList(DateTime.UtcNow.AddDays(-1), DateTime.UtcNow.AddDays(1), _blacksmith.Id);
Assert.That(list, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(list, Has.Count.EqualTo(2));
Assert.That(list.All(x => x.BlacksmithId == _blacksmith.Id));
});
}
Assert.That(list, Has.Count.EqualTo(2));
Assert.That(list.All(x => x.BlacksmithId == _blacksmith.Id));
});
}
[Test]
public void Try_AddElement_Test()
[Test]
public void Try_AddElement_Test()
{
var salary = CreateModel(_blacksmith.Id);
_salaryStorageContract.AddElement(salary);
AssertElement(TheBlacksmithVakulaDbContext.GetSalariesFromDatabaseByBlacksmithId(_blacksmith.Id).First(), salary);
}
private static void AssertElement(SalaryDataModel? actual, Salary expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
var salary = CreateModel(_blacksmith.Id);
_salaryStorageContract.AddElement(salary);
AssertElement(GetSalaryFromDatabaseByBlacksmithId(_blacksmith.Id), salary);
}
Assert.That(actual.BlacksmithId, Is.EqualTo(expected.BlacksmithId));
Assert.That(actual.Salary, Is.EqualTo(expected.BlacksmithSalary));
});
}
private Blacksmith InsertBlacksmithToDatabaseAndReturn(string blacksmithFIO = "fio")
private static SalaryDataModel CreateModel(string blacksmithId, double blacksmithSalary = 1, DateTime? salaryDate = null)
=> new(blacksmithId, salaryDate ?? DateTime.UtcNow, blacksmithSalary);
private static void AssertElement(Salary? actual, SalaryDataModel expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
var blacksmith = new Blacksmith()
{
Id = Guid.NewGuid().ToString(),
RankId = Guid.NewGuid().ToString(),
FIO = blacksmithFIO,
IsDeleted = false
};
TheBlacksmithVakulaDbContext.Blacksmiths.Add(blacksmith);
TheBlacksmithVakulaDbContext.SaveChanges();
return blacksmith;
}
private Salary InsertSalaryToDatabaseAndReturn(string blacksmithId, double blacksmithSalary = 1, DateTime? salaryDate = null)
{
var salary = new Salary()
{
BlacksmithId = blacksmithId,
BlacksmithSalary = blacksmithSalary,
SalaryDate = salaryDate ?? DateTime.UtcNow
};
TheBlacksmithVakulaDbContext.Salaries.Add(salary);
TheBlacksmithVakulaDbContext.SaveChanges();
return salary;
}
private static void AssertElement(SalaryDataModel? actual, Salary expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.BlacksmithId, Is.EqualTo(expected.BlacksmithId));
Assert.That(actual.Salary, Is.EqualTo(expected.BlacksmithSalary));
});
}
private static SalaryDataModel CreateModel(string blacksmithId, double blacksmithSalary = 1, DateTime? salaryDate = null)
=> new(blacksmithId, salaryDate ?? DateTime.UtcNow, blacksmithSalary);
private Salary? GetSalaryFromDatabaseByBlacksmithId(string id)
=> TheBlacksmithVakulaDbContext.Salaries.FirstOrDefault(x => x.BlacksmithId == id);
private static void AssertElement(Salary? actual, SalaryDataModel expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.BlacksmithId, Is.EqualTo(expected.BlacksmithId));
Assert.That(actual.BlacksmithSalary, Is.EqualTo(expected.Salary));
});
}
Assert.That(actual.BlacksmithId, Is.EqualTo(expected.BlacksmithId));
Assert.That(actual.BlacksmithSalary, Is.EqualTo(expected.Salary));
});
}
}

View File

@@ -8,16 +8,25 @@
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<Content Include="WebApiControllersTests\appsettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<ExcludeFromSingleFile>true</ExcludeFromSingleFile>
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
</Content>
</ItemGroup>
<ItemGroup>
<PackageReference Include="coverlet.collector" Version="6.0.4">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.Extensions.Logging" Version="9.0.3" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="9.0.4" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="9.0.4" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.13.0" />
<PackageReference Include="Moq" Version="4.20.72" />
<PackageReference Include="NUnit" Version="4.3.2" />
<PackageReference Include="NUnit.Analyzers" Version="4.6.0">
<PackageReference Include="NUnit.Analyzers" Version="4.7.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
@@ -28,6 +37,7 @@
<ProjectReference Include="..\TheBlacksmithVakulaBuisnessLogic\TheBlacksmithVakulaBusinessLogic.csproj" />
<ProjectReference Include="..\TheBlacksmithVakulaContract\TheBlacksmithVakulaContract.csproj" />
<ProjectReference Include="..\TheBlacksmithVakulaDatabase\TheBlacksmithVakulaDatabase.csproj" />
<ProjectReference Include="..\TheBlacksmithVakulaWebApi\TheBlacksmithVakulaWebApi.csproj" />
</ItemGroup>
<ItemGroup>

View File

@@ -0,0 +1,68 @@
using Microsoft.AspNetCore.TestHost;
using System.Text.Json;
using System.Text;
using TheBlacksmithVakulaDatabase;
using TheBlacksmithVakulaTests.Infrastructure;
using Microsoft.Extensions.Logging;
using Serilog;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace TheBlacksmithVakulaTests.WebApiControllersTests
{
internal class BaseWebApiControllerTest
{
private CustomWebApplicationFactory<Program> _webApplication;
protected HttpClient HttpClient { get; private set; }
protected TheBlacksmithVakulaDbContext TheBlacksmithVakulaDbContext { 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}");
TheBlacksmithVakulaDbContext = _webApplication.Services.GetRequiredService<TheBlacksmithVakulaDbContext>();
TheBlacksmithVakulaDbContext.Database.EnsureDeleted();
TheBlacksmithVakulaDbContext.Database.EnsureCreated();
}
[OneTimeTearDown]
public void OneTimeTearDown()
{
TheBlacksmithVakulaDbContext?.Database.EnsureDeleted();
TheBlacksmithVakulaDbContext?.Dispose();
HttpClient?.Dispose();
_webApplication?.Dispose();
}
protected static async Task<T?> GetModelFromResponseAsync<T>(HttpResponseMessage response) =>
JsonSerializer.Deserialize<T>(await response.Content.ReadAsStringAsync(), JsonSerializerOptions);
protected static StringContent MakeContent(object model) =>
new(JsonSerializer.Serialize(model), Encoding.UTF8, "application/json");
}
}

View File

@@ -0,0 +1,358 @@
using System.Net;
using TheBlacksmithVakulaContract.BindingModels;
using TheBlacksmithVakulaContract.ViewModels;
using TheBlacksmithVakulaDatabase.Models;
using TheBlacksmithVakulaTests.Infrastructure;
namespace TheBlacksmithVakulaTests.WebApiControllersTests
{
[TestFixture]
internal class BilletControllerTests : BaseWebApiControllerTest
{
[TearDown]
public void TearDown()
{
TheBlacksmithVakulaDbContext.RemoveProductsFromDatabase();
TheBlacksmithVakulaDbContext.RemoveBilletsFromDatabase();
}
[Test]
public async Task GetList_WhenHaveRecords_ShouldSuccess_Test()
{
//Arrange
var billet = TheBlacksmithVakulaDbContext.InsertBilletToDatabaseAndReturn(billetName: "name 1");
TheBlacksmithVakulaDbContext.InsertBilletToDatabaseAndReturn(billetName: "name 2");
TheBlacksmithVakulaDbContext.InsertBilletToDatabaseAndReturn(billetName: "name 3");
//Act
var response = await HttpClient.GetAsync("/api/billets");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
var data = await GetModelFromResponseAsync<List<BilletViewModel>>(response);
Assert.Multiple(() =>
{
Assert.That(data, Is.Not.Null);
Assert.That(data, Has.Count.EqualTo(3));
});
AssertElement(data.First(x => x.Id == billet.Id), billet);
}
[Test]
public async Task GetList_WhenNoRecords_ShouldSuccess_Test()
{
//Act
var response = await HttpClient.GetAsync("/api/billets");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
var data = await GetModelFromResponseAsync<List<BilletViewModel>>(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 billet = TheBlacksmithVakulaDbContext.InsertBilletToDatabaseAndReturn();
//Act
var response = await HttpClient.GetAsync($"/api/billets/{billet.Id}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
AssertElement(await GetModelFromResponseAsync<BilletViewModel>(response), billet);
}
[Test]
public async Task GetElement_ById_WhenNoRecord_ShouldNotFound_Test()
{
//Arrange
TheBlacksmithVakulaDbContext.InsertBilletToDatabaseAndReturn();
//Act
var response = await HttpClient.GetAsync($"/api/billets/{Guid.NewGuid()}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
}
[Test]
public async Task GetElement_ByName_WhenHaveRecord_ShouldSuccess_Test()
{
//Arrange
var billet = TheBlacksmithVakulaDbContext.InsertBilletToDatabaseAndReturn();
//Act
var response = await HttpClient.GetAsync($"/api/billets/{billet.BilletName}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
AssertElement(await GetModelFromResponseAsync<BilletViewModel>(response), billet);
}
[Test]
public async Task GetElement_ByName_WhenNoRecord_ShouldNotFound_Test()
{
//Arrange
TheBlacksmithVakulaDbContext.InsertBilletToDatabaseAndReturn();
//Act
var response = await HttpClient.GetAsync($"/api/billets/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 billet = TheBlacksmithVakulaDbContext.InsertBilletToDatabaseAndReturn(prevBilletName: oldName);
//Act
var response = await HttpClient.GetAsync($"/api/billets/{oldName}");
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
AssertElement(await GetModelFromResponseAsync<BilletViewModel>(response), billet);
}
[Test]
public async Task Post_ShouldSuccess_Test()
{
//Arrange
TheBlacksmithVakulaDbContext.InsertBilletToDatabaseAndReturn();
var billetModel = CreateModel();
//Act
var response = await HttpClient.PostAsync($"/api/billets", MakeContent(billetModel));
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
AssertElement(TheBlacksmithVakulaDbContext.GetBilletFromDatabase(billetModel.Id!), billetModel);
}
[Test]
public async Task Post_WhenHaveRecordWithSameId_ShouldBadRequest_Test()
{
//Arrange
var billetModel = CreateModel();
TheBlacksmithVakulaDbContext.InsertBilletToDatabaseAndReturn(billetModel.Id);
//Act
var response = await HttpClient.PostAsync($"/api/billets", MakeContent(billetModel));
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}
[Test]
public async Task Post_WhenHaveRecordWithSameName_ShouldBadRequest_Test()
{
//Arrange
var billetModel = CreateModel(billetName: "unique name");
TheBlacksmithVakulaDbContext.InsertBilletToDatabaseAndReturn(billetName: billetModel.BilletName!);
//Act
var response = await HttpClient.PostAsync($"/api/billets", MakeContent(billetModel));
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}
[Test]
public async Task Post_WhenDataIsIncorrect_ShouldBadRequest_Test()
{
//Arrange
var billetModelWithIdIncorrect = new BilletBindingModel { Id = "Id", BilletName = "name" };
var billetModelWithNameIncorrect = new BilletBindingModel { Id = Guid.NewGuid().ToString(), BilletName = string.Empty };
//Act
var responseWithIdIncorrect = await HttpClient.PostAsync($"/api/billets", MakeContent(billetModelWithIdIncorrect));
var responseWithNameIncorrect = await HttpClient.PostAsync($"/api/billets", MakeContent(billetModelWithNameIncorrect));
//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/billets", 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/billets", MakeContent(new { Data = "test", Position = 10 }));
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}
[Test]
public async Task Put_ShouldSuccess_Test()
{
//Arrange
var billetModel = CreateModel();
TheBlacksmithVakulaDbContext.InsertBilletToDatabaseAndReturn(billetModel.Id);
//Act
var response = await HttpClient.PutAsync($"/api/billets", MakeContent(billetModel));
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
TheBlacksmithVakulaDbContext.ChangeTracker.Clear();
AssertElement(TheBlacksmithVakulaDbContext.GetBilletFromDatabase(billetModel.Id!), billetModel);
}
[Test]
public async Task Put_CheckPrevNames_ShouldSuccess_Test()
{
//Arrange
var billetModel1 = CreateModel(billetName: "name 1");
var billetModel2 = CreateModel(id: billetModel1.Id, billetName: "name 2");
var billetModel3 = CreateModel(id: billetModel1.Id, billetName: "name 3");
TheBlacksmithVakulaDbContext.InsertBilletToDatabaseAndReturn(billetModel1.Id);
//Act
await HttpClient.PutAsync($"/api/billets", MakeContent(billetModel1));
await HttpClient.PutAsync($"/api/billets", MakeContent(billetModel2));
await HttpClient.PutAsync($"/api/billets", MakeContent(billetModel3));
//Assert
TheBlacksmithVakulaDbContext.ChangeTracker.Clear();
var entityModel = TheBlacksmithVakulaDbContext.GetBilletFromDatabase(billetModel1.Id!);
Assert.That(entityModel, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(entityModel.BilletName, Is.EqualTo(billetModel3.BilletName));
Assert.That(entityModel.PrevBilletName, Is.EqualTo(billetModel2.BilletName));
Assert.That(entityModel.PrevPrevBilletName, Is.EqualTo(billetModel1.BilletName));
});
}
[Test]
public async Task Put_WhenNoFoundRecord_ShouldBadRequest_Test()
{
//Arrange
var billetModel = CreateModel();
TheBlacksmithVakulaDbContext.InsertBilletToDatabaseAndReturn();
//Act
var response = await HttpClient.PutAsync($"/api/billets", MakeContent(billetModel));
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}
[Test]
public async Task Put_WhenHaveRecordWithSameName_ShouldBadRequest_Test()
{
//Arrange
var billetModel = CreateModel(billetName: "unique name");
TheBlacksmithVakulaDbContext.InsertBilletToDatabaseAndReturn(billetModel.Id);
TheBlacksmithVakulaDbContext.InsertBilletToDatabaseAndReturn(billetName: billetModel.BilletName!);
//Act
var response = await HttpClient.PostAsync($"/api/billets", MakeContent(billetModel));
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}
[Test]
public async Task Put_WhenDataIsIncorrect_ShouldBadRequest_Test()
{
//Arrange
var billetModelWithIdIncorrect = new BilletBindingModel { Id = "Id", BilletName = "name" };
var billetModelWithNameIncorrect = new BilletBindingModel { Id = Guid.NewGuid().ToString(), BilletName = string.Empty };
//Act
var responseWithIdIncorrect = await HttpClient.PutAsync($"/api/billets", MakeContent(billetModelWithIdIncorrect));
var responseWithNameIncorrect = await HttpClient.PutAsync($"/api/billets", MakeContent(billetModelWithNameIncorrect));
//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/billets", 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/billets", MakeContent(new { Data = "test", Position = 10 }));
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}
[Test]
public async Task Delete_ShouldSuccess_Test()
{
//Arrange
var billetId = Guid.NewGuid().ToString();
TheBlacksmithVakulaDbContext.InsertBilletToDatabaseAndReturn(billetId);
//Act
var response = await HttpClient.DeleteAsync($"/api/billets/{billetId}");
//Assert
Assert.Multiple(() =>
{
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
Assert.That(TheBlacksmithVakulaDbContext.GetBilletFromDatabase(billetId), Is.Null);
});
}
[Test]
public async Task Delete_WhenHaveProducts_ShouldSuccess_Test()
{
//Arrange
var billetId = TheBlacksmithVakulaDbContext.InsertBilletToDatabaseAndReturn().Id;
TheBlacksmithVakulaDbContext.InsertProductToDatabaseAndReturn(billetId);
//Act
var response = await HttpClient.DeleteAsync($"/api/billets/{billetId}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}
[Test]
public async Task Delete_WhenNoFoundRecord_ShouldBadRequest_Test()
{
//Arrange
TheBlacksmithVakulaDbContext.InsertBilletToDatabaseAndReturn();
//Act
var response = await HttpClient.DeleteAsync($"/api/billets/{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/billets/id");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}
private static void AssertElement(BilletViewModel? actual, Billet expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.Id, Is.EqualTo(expected.Id));
Assert.That(actual.BilletName, Is.EqualTo(expected.BilletName));
Assert.That(actual.PrevBilletName, Is.EqualTo(expected.PrevBilletName));
Assert.That(actual.PrevPrevBilletName, Is.EqualTo(expected.PrevPrevBilletName));
});
}
private static BilletBindingModel CreateModel(string? id = null, string billetName = "name")
=> new()
{
Id = id ?? Guid.NewGuid().ToString(),
BilletName = billetName
};
private static void AssertElement(Billet? actual, BilletBindingModel expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.Id, Is.EqualTo(expected.Id));
Assert.That(actual.BilletName, Is.EqualTo(expected.BilletName));
});
}
}
}

View File

@@ -0,0 +1,508 @@
using System.Net;
using TheBlacksmithVakulaContract.BindingModels;
using TheBlacksmithVakulaContract.ViewModels;
using TheBlacksmithVakulaDatabase.Models;
using TheBlacksmithVakulaTests.Infrastructure;
namespace TheBlacksmithVakulaTests.WebApiControllersTests
{
[TestFixture]
internal class BlacksmithControllerTets : BaseWebApiControllerTest
{
private Rank _rank;
[SetUp]
public void SetUp()
{
_rank = TheBlacksmithVakulaDbContext.InsertRankToDatabaseAndReturn();
}
[TearDown]
public void TearDown()
{
TheBlacksmithVakulaDbContext.RemoveRanksFromDatabase();
TheBlacksmithVakulaDbContext.RemoveBlacksmithsFromDatabase();
}
[Test]
public async Task GetList_WhenHaveRecords_ShouldSuccess_Test()
{
//Arrange
var blacksmith = TheBlacksmithVakulaDbContext.InsertBlacksmithToDatabaseAndReturn(fio: "fio 1", rankId: _rank.RankId).AddRank(_rank);
TheBlacksmithVakulaDbContext.InsertBlacksmithToDatabaseAndReturn(fio: "fio 2", rankId: _rank.RankId);
TheBlacksmithVakulaDbContext.InsertBlacksmithToDatabaseAndReturn(fio: "fio 3", rankId: _rank.RankId);
//Act
var response = await HttpClient.GetAsync("/api/blacksmiths/getrecords");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
var data = await GetModelFromResponseAsync<List<BlacksmithViewModel>>(response);
Assert.Multiple(() =>
{
Assert.That(data, Is.Not.Null);
Assert.That(data, Has.Count.EqualTo(3));
});
AssertElement(data.First(x => x.Id == blacksmith.Id), blacksmith);
}
[Test]
public async Task GetList_WhenNoRecords_ShouldSuccess_Test()
{
//Act
var response = await HttpClient.GetAsync("/api/blacksmiths/getrecords");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
var data = await GetModelFromResponseAsync<List<BlacksmithViewModel>>(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
TheBlacksmithVakulaDbContext.InsertBlacksmithToDatabaseAndReturn(fio: "fio 1", rankId: _rank.RankId, isDeleted: true);
TheBlacksmithVakulaDbContext.InsertBlacksmithToDatabaseAndReturn(fio: "fio 2", rankId: _rank.RankId, isDeleted: false);
TheBlacksmithVakulaDbContext.InsertBlacksmithToDatabaseAndReturn(fio: "fio 3", rankId: _rank.RankId, isDeleted: false);
//Act
var response = await HttpClient.GetAsync("/api/blacksmiths/getrecords?includeDeleted=false");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
var data = await GetModelFromResponseAsync<List<BlacksmithViewModel>>(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
TheBlacksmithVakulaDbContext.InsertBlacksmithToDatabaseAndReturn(fio: "fio 1", rankId: _rank.RankId, isDeleted: true);
TheBlacksmithVakulaDbContext.InsertBlacksmithToDatabaseAndReturn(fio: "fio 2", rankId: _rank.RankId, isDeleted: true);
TheBlacksmithVakulaDbContext.InsertBlacksmithToDatabaseAndReturn(fio: "fio 3", rankId: _rank.RankId, isDeleted: false);
//Act
var response = await HttpClient.GetAsync("/api/blacksmiths/getrecords?includeDeleted=true");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
var data = await GetModelFromResponseAsync<List<BlacksmithViewModel>>(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_ByRankId_ShouldSuccess_Test()
{
//Arrange
TheBlacksmithVakulaDbContext.InsertBlacksmithToDatabaseAndReturn(fio: "fio 1", rankId: _rank.RankId);
TheBlacksmithVakulaDbContext.InsertBlacksmithToDatabaseAndReturn(fio: "fio 2", rankId: _rank.RankId);
TheBlacksmithVakulaDbContext.InsertBlacksmithToDatabaseAndReturn(fio: "fio 3", rankId: _rank.RankId, isDeleted: true);
TheBlacksmithVakulaDbContext.InsertBlacksmithToDatabaseAndReturn(fio: "fio 4");
//Act
var response = await HttpClient.GetAsync($"/api/blacksmiths/getrankrecords?id={_rank.RankId}&includeDeleted=true");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
var data = await GetModelFromResponseAsync<List<BlacksmithViewModel>>(response);
Assert.That(data, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(data, Has.Count.EqualTo(3));
Assert.That(data.All(x => x.RankId == _rank.RankId));
});
}
[Test]
public async Task GetList_ByRankId_WhenNoRecords_ShouldSuccess_Test()
{
//Arrange
TheBlacksmithVakulaDbContext.InsertBlacksmithToDatabaseAndReturn(fio: "fio 1", rankId: _rank.RankId);
TheBlacksmithVakulaDbContext.InsertBlacksmithToDatabaseAndReturn(fio: "fio 4");
//Act
var response = await HttpClient.GetAsync($"/api/blacksmiths/getrankrecords?id={Guid.NewGuid()}&includeDeleted=true");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
var data = await GetModelFromResponseAsync<List<BlacksmithViewModel>>(response);
Assert.That(data, Is.Not.Null);
Assert.That(data, Has.Count.EqualTo(0));
}
[Test]
public async Task GetList_ByRankId_WhenIdIsIncorrect_ShouldBadRequest_Test()
{
//Act
var response = await HttpClient.GetAsync($"/api/blacksmiths/getrankrecords?id=id&includeDeleted=true");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}
[Test]
public async Task GetList_ByBirthDate_ShouldSuccess_Test()
{
//Arrange
TheBlacksmithVakulaDbContext.InsertBlacksmithToDatabaseAndReturn(fio: "fio 1", birthDate: DateTime.UtcNow.AddYears(-25));
TheBlacksmithVakulaDbContext.InsertBlacksmithToDatabaseAndReturn(fio: "fio 2", birthDate: DateTime.UtcNow.AddYears(-21));
TheBlacksmithVakulaDbContext.InsertBlacksmithToDatabaseAndReturn(fio: "fio 3", birthDate: DateTime.UtcNow.AddYears(-20), isDeleted: true);
TheBlacksmithVakulaDbContext.InsertBlacksmithToDatabaseAndReturn(fio: "fio 4", birthDate: DateTime.UtcNow.AddYears(-19));
//Act
var response = await HttpClient.GetAsync($"/api/blacksmiths/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"); //:MM/dd/yyyy HH:mm:ss
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
var data = await GetModelFromResponseAsync<List<BlacksmithViewModel>>(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/blacksmiths/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
TheBlacksmithVakulaDbContext.InsertBlacksmithToDatabaseAndReturn(fio: "fio 1", employmentDate: DateTime.UtcNow.AddDays(-2));
TheBlacksmithVakulaDbContext.InsertBlacksmithToDatabaseAndReturn(fio: "fio 2", employmentDate: DateTime.UtcNow.AddDays(-1));
TheBlacksmithVakulaDbContext.InsertBlacksmithToDatabaseAndReturn(fio: "fio 3", employmentDate: DateTime.UtcNow.AddDays(1), isDeleted: true);
TheBlacksmithVakulaDbContext.InsertBlacksmithToDatabaseAndReturn(fio: "fio 4", employmentDate: DateTime.UtcNow.AddDays(2));
//Act
var response = await HttpClient.GetAsync($"/api/blacksmiths/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<BlacksmithViewModel>>(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/blacksmiths/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 blacksmith = TheBlacksmithVakulaDbContext.InsertBlacksmithToDatabaseAndReturn(rankId: _rank.RankId).AddRank(_rank);
//Act
var response = await HttpClient.GetAsync($"/api/blacksmiths/getrecord/{blacksmith.Id}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
AssertElement(await GetModelFromResponseAsync<BlacksmithViewModel>(response), blacksmith);
}
[Test]
public async Task GetElement_ById_WhenNoRecord_ShouldNotFound_Test()
{
//Arrange
TheBlacksmithVakulaDbContext.InsertBlacksmithToDatabaseAndReturn();
//Act
var response = await HttpClient.GetAsync($"/api/blacksmiths/getrecord/{Guid.NewGuid()}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
}
[Test]
public async Task GetElement_ById_WhenRecordWasDeleted_ShouldNotFound_Test()
{
//Arrange
var blacksmith = TheBlacksmithVakulaDbContext.InsertBlacksmithToDatabaseAndReturn(rankId: _rank.RankId, isDeleted: true);
//Act
var response = await HttpClient.GetAsync($"/api/blacksmiths/getrecord/{blacksmith.Id}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
}
[Test]
public async Task GetElement_ByFIO_WhenHaveRecord_ShouldSuccess_Test()
{
//Arrange
var blacksmith = TheBlacksmithVakulaDbContext.InsertBlacksmithToDatabaseAndReturn(rankId: _rank.RankId).AddRank(_rank);
//Act
var response = await HttpClient.GetAsync($"/api/blacksmiths/getrecord/{blacksmith.FIO}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
AssertElement(await GetModelFromResponseAsync<BlacksmithViewModel>(response), blacksmith);
}
[Test]
public async Task GetElement_ByFIO_WhenNoRecord_ShouldNotFound_Test()
{
//Arrange
TheBlacksmithVakulaDbContext.InsertBlacksmithToDatabaseAndReturn();
//Act
var response = await HttpClient.GetAsync($"/api/blacksmiths/getrecord/New%20Fio");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
}
[Test]
public async Task GetElement_ByFIO_WhenRecordWasDeleted_ShouldNotFound_Test()
{
//Arrange
var blacksmith = TheBlacksmithVakulaDbContext.InsertBlacksmithToDatabaseAndReturn(rankId: _rank.RankId, isDeleted: true).AddRank(_rank);
//Act
var response = await HttpClient.GetAsync($"/api/blacksmiths/getrecord/{blacksmith.FIO}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
}
[Test]
public async Task Post_ShouldSuccess_Test()
{
//Arrange
TheBlacksmithVakulaDbContext.InsertBlacksmithToDatabaseAndReturn();
var blacksmithModel = CreateModel(_rank.Id);
//Act
var response = await HttpClient.PostAsync($"/api/blacksmiths/register", MakeContent(blacksmithModel));
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
AssertElement(TheBlacksmithVakulaDbContext.GetBlacksmithFromDatabaseById(blacksmithModel.Id!), blacksmithModel);
}
[Test]
public async Task Post_WhenHaveRecordWithSameId_ShouldBadRequest_Test()
{
//Arrange
var blacksmithModel = CreateModel(_rank.Id);
TheBlacksmithVakulaDbContext.InsertBlacksmithToDatabaseAndReturn(blacksmithModel.Id);
//Act
var response = await HttpClient.PostAsync($"/api/blacksmiths/register", MakeContent(blacksmithModel));
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}
[Test]
public async Task Post_WhenDataIsIncorrect_ShouldBadRequest_Test()
{
//Arrange
var blacksmithModelWithIdIncorrect = new BlacksmithBindingModel { Id = "Id", FIO = "fio", BirthDate = DateTime.UtcNow.AddYears(-22), EmploymentDate = DateTime.UtcNow.AddDays(-5), RankId = _rank.Id };
var blacksmithModelWithFioIncorrect = new BlacksmithBindingModel { Id = Guid.NewGuid().ToString(), FIO = string.Empty, BirthDate = DateTime.UtcNow.AddYears(-22), EmploymentDate = DateTime.UtcNow.AddDays(-5), RankId = _rank.Id };
var blacksmithModelWithRankIdIncorrect = new BlacksmithBindingModel { Id = Guid.NewGuid().ToString(), FIO = "fio", BirthDate = DateTime.UtcNow.AddYears(-22), EmploymentDate = DateTime.UtcNow.AddDays(-5), RankId = "Id" };
var blacksmithModelWithBirthDateIncorrect = new BlacksmithBindingModel { Id = Guid.NewGuid().ToString(), FIO = "fio", BirthDate = DateTime.UtcNow.AddYears(-15), EmploymentDate = DateTime.UtcNow.AddDays(-5), RankId = _rank.Id };
//Act
var responseWithIdIncorrect = await HttpClient.PostAsync($"/api/blacksmiths/register", MakeContent(blacksmithModelWithIdIncorrect));
var responseWithFioIncorrect = await HttpClient.PostAsync($"/api/blacksmiths/register", MakeContent(blacksmithModelWithFioIncorrect));
var responseWithRankIdIncorrect = await HttpClient.PostAsync($"/api/blacksmiths/register", MakeContent(blacksmithModelWithRankIdIncorrect));
var responseWithBirthDateIncorrect = await HttpClient.PostAsync($"/api/blacksmiths/register", MakeContent(blacksmithModelWithBirthDateIncorrect));
//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(responseWithRankIdIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "RankId 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/blacksmiths/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/blacksmiths/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 blacksmithModel = CreateModel(_rank.Id);
TheBlacksmithVakulaDbContext.InsertBlacksmithToDatabaseAndReturn(blacksmithModel.Id);
//Act
var response = await HttpClient.PutAsync($"/api/blacksmiths/changeinfo", MakeContent(blacksmithModel));
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
TheBlacksmithVakulaDbContext.ChangeTracker.Clear();
AssertElement(TheBlacksmithVakulaDbContext.GetBlacksmithFromDatabaseById(blacksmithModel.Id!), blacksmithModel);
}
[Test]
public async Task Put_WhenNoFoundRecord_ShouldBadRequest_Test()
{
//Arrange
var blacksmithModel = CreateModel(_rank.Id, fio: "new fio");
TheBlacksmithVakulaDbContext.InsertBlacksmithToDatabaseAndReturn();
//Act
var response = await HttpClient.PutAsync($"/api/blacksmiths/changeinfo", MakeContent(blacksmithModel));
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}
[Test]
public async Task Put_WhenRecordWasDeleted_ShouldBadRequest_Test()
{
//Arrange
var blacksmithModel = CreateModel(_rank.Id, fio: "new fio");
TheBlacksmithVakulaDbContext.InsertBlacksmithToDatabaseAndReturn(blacksmithModel.Id, isDeleted: true);
//Act
var response = await HttpClient.PutAsync($"/api/blacksmiths/changeinfo", MakeContent(blacksmithModel));
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}
[Test]
public async Task Put_WhenDataIsIncorrect_ShouldBadRequest_Test()
{
//Arrange
var blacksmithModelWithIdIncorrect = new BlacksmithBindingModel { Id = "Id", FIO = "fio", BirthDate = DateTime.UtcNow.AddYears(-22), EmploymentDate = DateTime.UtcNow.AddDays(-5), RankId = _rank.Id };
var blacksmithModelWithFioIncorrect = new BlacksmithBindingModel { Id = Guid.NewGuid().ToString(), FIO = string.Empty, BirthDate = DateTime.UtcNow.AddYears(-22), EmploymentDate = DateTime.UtcNow.AddDays(-5), RankId = _rank.Id };
var blacksmithModelWithRankIdIncorrect = new BlacksmithBindingModel { Id = Guid.NewGuid().ToString(), FIO = "fio", BirthDate = DateTime.UtcNow.AddYears(-22), EmploymentDate = DateTime.UtcNow.AddDays(-5), RankId = "Id" };
var blacksmithModelWithBirthDateIncorrect = new BlacksmithBindingModel { Id = Guid.NewGuid().ToString(), FIO = "fio", BirthDate = DateTime.UtcNow.AddYears(-15), EmploymentDate = DateTime.UtcNow.AddDays(-5), RankId = _rank.Id };
//Act
var responseWithIdIncorrect = await HttpClient.PutAsync($"/api/blacksmiths/changeinfo", MakeContent(blacksmithModelWithIdIncorrect));
var responseWithFioIncorrect = await HttpClient.PutAsync($"/api/blacksmiths/changeinfo", MakeContent(blacksmithModelWithFioIncorrect));
var responseWithRankIdIncorrect = await HttpClient.PutAsync($"/api/blacksmiths/changeinfo", MakeContent(blacksmithModelWithRankIdIncorrect));
var responseWithBirthDateIncorrect = await HttpClient.PutAsync($"/api/blacksmiths/changeinfo", MakeContent(blacksmithModelWithBirthDateIncorrect));
//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(responseWithRankIdIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "RankId 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/blacksmiths/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/blacksmiths/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 blacksmithId = Guid.NewGuid().ToString();
TheBlacksmithVakulaDbContext.InsertBlacksmithToDatabaseAndReturn(blacksmithId);
//Act
var response = await HttpClient.DeleteAsync($"/api/blacksmiths/delete/{blacksmithId}");
TheBlacksmithVakulaDbContext.ChangeTracker.Clear();
//Assert
Assert.Multiple(() =>
{
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
Assert.That(TheBlacksmithVakulaDbContext.GetBlacksmithFromDatabaseById(blacksmithId)!.IsDeleted);
});
}
[Test]
public async Task Delete_WhenNoFoundRecord_ShouldBadRequest_Test()
{
//Arrange
TheBlacksmithVakulaDbContext.InsertBlacksmithToDatabaseAndReturn();
//Act
var response = await HttpClient.DeleteAsync($"/api/blacksmiths/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/blacksmiths/delete/id");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}
[Test]
public async Task Delete_WhenRecordWasDeleted_ShouldBadRequest_Test()
{
//Arrange
var blacksmithId = TheBlacksmithVakulaDbContext.InsertBlacksmithToDatabaseAndReturn(isDeleted: true).Id;
//Act
var response = await HttpClient.DeleteAsync($"/api/blacksmiths/delete/{blacksmithId}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}
private static void AssertElement(BlacksmithViewModel? actual, Blacksmith expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.Id, Is.EqualTo(expected.Id));
Assert.That(actual.RankId, Is.EqualTo(expected.RankId));
Assert.That(actual.RankName, Is.EqualTo(expected.Rank!.RankName));
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 BlacksmithBindingModel CreateModel(string rankId, 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),
RankId = rankId
};
}
private static void AssertElement(Blacksmith? actual, BlacksmithBindingModel expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.Id, Is.EqualTo(expected.Id));
Assert.That(actual.RankId, Is.EqualTo(expected.RankId));
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);
});
}
}
}

View File

@@ -0,0 +1,371 @@
using System.Net;
using TheBlacksmithVakulaContract.BindingModels;
using TheBlacksmithVakulaContract.ViewModels;
using TheBlacksmithVakulaDatabase.Models;
using TheBlacksmithVakulaTests.Infrastructure;
namespace TheBlacksmithVakulaTests.WebApiControllersTests
{
[TestFixture]
internal class BuyerControllerTests : BaseWebApiControllerTest
{
[TearDown]
public void TearDown()
{
TheBlacksmithVakulaDbContext.RemoveOrdersFromDatabase();
TheBlacksmithVakulaDbContext.RemoveBlacksmithsFromDatabase();
TheBlacksmithVakulaDbContext.RemoveBuyersFromDatabase();
}
[Test]
public async Task GetList_WhenHaveRecords_ShouldSuccess_Test()
{
//Arrange
var buyer = TheBlacksmithVakulaDbContext.InsertBuyerToDatabaseAndReturn(phoneNumber: "+5-555-555-55-55");
TheBlacksmithVakulaDbContext.InsertBuyerToDatabaseAndReturn(phoneNumber: "+6-666-666-66-66");
TheBlacksmithVakulaDbContext.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 = TheBlacksmithVakulaDbContext.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
TheBlacksmithVakulaDbContext.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 = TheBlacksmithVakulaDbContext.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
TheBlacksmithVakulaDbContext.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 = TheBlacksmithVakulaDbContext.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
TheBlacksmithVakulaDbContext.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
TheBlacksmithVakulaDbContext.InsertBuyerToDatabaseAndReturn();
var buyerModel = CreateBindingModel();
//Act
var response = await HttpClient.PostAsync($"/api/buyers", MakeContent(buyerModel));
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
AssertElement(TheBlacksmithVakulaDbContext.GetBuyerFromDatabase(buyerModel.Id!), buyerModel);
}
[Test]
public async Task Post_WhenHaveRecordWithSameId_ShouldBadRequest_Test()
{
//Arrange
var buyerModel = CreateBindingModel();
TheBlacksmithVakulaDbContext.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();
TheBlacksmithVakulaDbContext.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");
TheBlacksmithVakulaDbContext.InsertBuyerToDatabaseAndReturn(buyerModel.Id);
//Act
var response = await HttpClient.PutAsync($"/api/buyers", MakeContent(buyerModel));
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
TheBlacksmithVakulaDbContext.ChangeTracker.Clear();
AssertElement(TheBlacksmithVakulaDbContext.GetBuyerFromDatabase(buyerModel.Id!), buyerModel);
}
[Test]
public async Task Put_WhenNoFoundRecord_ShouldBadRequest_Test()
{
//Arrange
var buyerModel = CreateBindingModel(fio: "new fio");
TheBlacksmithVakulaDbContext.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");
TheBlacksmithVakulaDbContext.InsertBuyerToDatabaseAndReturn(buyerModel.Id);
TheBlacksmithVakulaDbContext.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();
TheBlacksmithVakulaDbContext.InsertBuyerToDatabaseAndReturn(buyerId);
//Act
var response = await HttpClient.DeleteAsync($"/api/buyers/{buyerId}");
//Assert
Assert.Multiple(() =>
{
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
Assert.That(TheBlacksmithVakulaDbContext.GetBuyerFromDatabase(buyerId), Is.Null);
});
}
[Test]
public async Task Delete_WhenHaveOrdersByThisBuyer_ShouldSuccess_Test()
{
//Arrange
var buyer = TheBlacksmithVakulaDbContext.InsertBuyerToDatabaseAndReturn();
var blacksmith = TheBlacksmithVakulaDbContext.InsertBlacksmithToDatabaseAndReturn();
TheBlacksmithVakulaDbContext.InsertOrderToDatabaseAndReturn(blacksmith.Id, buyer.Id);
TheBlacksmithVakulaDbContext.InsertOrderToDatabaseAndReturn(blacksmith.Id, buyer.Id);
var ordersBeforeDelete = TheBlacksmithVakulaDbContext.GetOrdersByBuyerId(buyer.Id);
//Act
var response = await HttpClient.DeleteAsync($"/api/buyers/{buyer.Id}");
//Assert
TheBlacksmithVakulaDbContext.ChangeTracker.Clear();
var element = TheBlacksmithVakulaDbContext.GetBuyerFromDatabase(buyer.Id);
var ordersAfterDelete = TheBlacksmithVakulaDbContext.GetOrdersByBuyerId(buyer.Id);
var ordersNoBuyers = TheBlacksmithVakulaDbContext.GetOrdersByBuyerId(null);
Assert.Multiple(() =>
{
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
Assert.That(element, Is.Null);
Assert.That(ordersBeforeDelete, Has.Length.EqualTo(2));
Assert.That(ordersAfterDelete, Is.Empty);
Assert.That(ordersNoBuyers, Has.Length.EqualTo(2));
});
}
[Test]
public async Task Delete_WhenNoFoundRecord_ShouldBadRequest_Test()
{
//Arrange
TheBlacksmithVakulaDbContext.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));
});
}
}
}

View File

@@ -0,0 +1,504 @@
using System.Net;
using TheBlacksmithVakulaContract.BindingModels;
using TheBlacksmithVakulaContract.Enums;
using TheBlacksmithVakulaContract.ViewModels;
using TheBlacksmithVakulaDatabase.Models;
using TheBlacksmithVakulaTests.Infrastructure;
namespace TheBlacksmithVakulaTests.WebApiControllersTests
{
[TestFixture]
internal class OrderControllerTests : BaseWebApiControllerTest
{
private string _buyerId;
private string _blacksmithId;
private string _billetId;
private string _productId;
[SetUp]
public void SetUp()
{
_buyerId = TheBlacksmithVakulaDbContext.InsertBuyerToDatabaseAndReturn().Id;
_blacksmithId = TheBlacksmithVakulaDbContext.InsertBlacksmithToDatabaseAndReturn().Id;
_billetId = TheBlacksmithVakulaDbContext.InsertBilletToDatabaseAndReturn().Id;
_productId = TheBlacksmithVakulaDbContext.InsertProductToDatabaseAndReturn(_billetId).Id;
}
[TearDown]
public void TearDown()
{
TheBlacksmithVakulaDbContext.RemoveOrdersFromDatabase();
TheBlacksmithVakulaDbContext.RemoveBlacksmithsFromDatabase();
TheBlacksmithVakulaDbContext.RemoveBuyersFromDatabase();
TheBlacksmithVakulaDbContext.RemoveProductsFromDatabase();
TheBlacksmithVakulaDbContext.RemoveBilletsFromDatabase();
}
[Test]
public async Task GetList_WhenHaveRecords_ShouldSuccess_Test()
{
//Arrange
var order = TheBlacksmithVakulaDbContext.InsertOrderToDatabaseAndReturn(_blacksmithId, buyerId: _buyerId, sum: 10, products: [(_productId, 10)]);
TheBlacksmithVakulaDbContext.InsertOrderToDatabaseAndReturn(_blacksmithId, products: [(_productId, 10)]);
TheBlacksmithVakulaDbContext.InsertOrderToDatabaseAndReturn(_blacksmithId, products: [(_productId, 10)]);
//Act
var response = await HttpClient.GetAsync($"/api/orders/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<OrderViewModel>>(response);
Assert.Multiple(() =>
{
Assert.That(data, Is.Not.Null);
Assert.That(data, Has.Count.EqualTo(3));
});
AssertElement(data.First(x => x.Sum == order.Sum), order);
}
[Test]
public async Task GetList_WhenNoRecords_ShouldSuccess_Test()
{
//Act
var response = await HttpClient.GetAsync($"/api/orders/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<OrderViewModel>>(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
TheBlacksmithVakulaDbContext.InsertOrderToDatabaseAndReturn(_blacksmithId, _buyerId, orderDate: DateTime.UtcNow.AddDays(-1).AddMinutes(-3), products: [(_productId, 10)]);
TheBlacksmithVakulaDbContext.InsertOrderToDatabaseAndReturn(_blacksmithId, _buyerId, orderDate: DateTime.UtcNow.AddDays(-1).AddMinutes(3), products: [(_productId, 10)]);
TheBlacksmithVakulaDbContext.InsertOrderToDatabaseAndReturn(_blacksmithId, null, orderDate: DateTime.UtcNow.AddDays(1).AddMinutes(-3), products: [(_productId, 10)]);
TheBlacksmithVakulaDbContext.InsertOrderToDatabaseAndReturn(_blacksmithId, null, orderDate: DateTime.UtcNow.AddDays(1).AddMinutes(3), products: [(_productId, 10)]);
//Act
var response = await HttpClient.GetAsync($"/api/orders/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<OrderViewModel>>(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/orders/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_ByBlacksmithId_ShouldSuccess_Test()
{
//Arrange
var blacksmith = TheBlacksmithVakulaDbContext.InsertBlacksmithToDatabaseAndReturn(fio: "Other blacksmith");
TheBlacksmithVakulaDbContext.InsertOrderToDatabaseAndReturn(_blacksmithId, _buyerId, products: [(_productId, 10)]);
TheBlacksmithVakulaDbContext.InsertOrderToDatabaseAndReturn(_blacksmithId, _buyerId, products: [(_productId, 10)]);
TheBlacksmithVakulaDbContext.InsertOrderToDatabaseAndReturn(blacksmith.Id, null, products: [(_productId, 10)]);
//Act
var response = await HttpClient.GetAsync($"/api/orders/getblacksmithrecords?id={_blacksmithId}&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<OrderViewModel>>(response);
Assert.That(data, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(data, Has.Count.EqualTo(2));
Assert.That(data.All(x => x.BlacksmithId == _blacksmithId));
});
}
[Test]
public async Task GetList_ByBlacksmithId_WhenNoRecords_ShouldSuccess_Test()
{
//Arrange
var blacksmith = TheBlacksmithVakulaDbContext.InsertBlacksmithToDatabaseAndReturn(fio: "Other blacksmith");
TheBlacksmithVakulaDbContext.InsertOrderToDatabaseAndReturn(_blacksmithId, _buyerId, products: [(_productId, 10)]);
//Act
var response = await HttpClient.GetAsync($"/api/orders/getblacksmithrecords?id={blacksmith.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<OrderViewModel>>(response);
Assert.That(data, Is.Not.Null);
Assert.That(data, Has.Count.EqualTo(0));
}
[Test]
public async Task GetList_ByBlacksmithId_WhenDateIsIncorrect_ShouldBadRequest_Test()
{
//Act
var response = await HttpClient.GetAsync($"/api/orders/getblacksmithrecords?id={_blacksmithId}&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_ByBlacksmithId_WhenIdIsIncorrect_ShouldBadRequest_Test()
{
//Act
var response = await HttpClient.GetAsync($"/api/orders/getblacksmithrecords?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 = TheBlacksmithVakulaDbContext.InsertBuyerToDatabaseAndReturn(fio: "Other fio", phoneNumber: "+8-888-888-88-88");
TheBlacksmithVakulaDbContext.InsertOrderToDatabaseAndReturn(_blacksmithId, _buyerId, products: [(_productId, 10)]);
TheBlacksmithVakulaDbContext.InsertOrderToDatabaseAndReturn(_blacksmithId, _buyerId, products: [(_productId, 10)]);
TheBlacksmithVakulaDbContext.InsertOrderToDatabaseAndReturn(_blacksmithId, buyer.Id, products: [(_productId, 10)]);
TheBlacksmithVakulaDbContext.InsertOrderToDatabaseAndReturn(_blacksmithId, null, products: [(_productId, 10)]);
//Act
var response = await HttpClient.GetAsync($"/api/orders/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<OrderViewModel>>(response);
Assert.That(data, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(data, Has.Count.EqualTo(0));
Assert.That(data.All(x => x.BuyerId == _buyerId));
});
}
[Test]
public async Task GetList_ByBuyerId_WhenNoRecords_ShouldSuccess_Test()
{
//Arrange
var buyer = TheBlacksmithVakulaDbContext.InsertBuyerToDatabaseAndReturn(fio: "Other buyer", phoneNumber: "+8-888-888-88-88");
TheBlacksmithVakulaDbContext.InsertOrderToDatabaseAndReturn(_blacksmithId, _buyerId, products: [(_productId, 10)]);
//Act
var response = await HttpClient.GetAsync($"/api/orders/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<OrderViewModel>>(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/orders/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/orders/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 = TheBlacksmithVakulaDbContext.InsertProductToDatabaseAndReturn(_billetId, productName: "Other name");
TheBlacksmithVakulaDbContext.InsertOrderToDatabaseAndReturn(_blacksmithId, _buyerId, products: [(_productId, 5)]);
TheBlacksmithVakulaDbContext.InsertOrderToDatabaseAndReturn(_blacksmithId, _buyerId, products: [(_productId, 10), (product.Id, 4)]);
TheBlacksmithVakulaDbContext.InsertOrderToDatabaseAndReturn(_blacksmithId, null, products: [(product.Id, 1)]);
TheBlacksmithVakulaDbContext.InsertOrderToDatabaseAndReturn(_blacksmithId, null, products: [(product.Id, 1), (_productId, 10)]);
//Act
var response = await HttpClient.GetAsync($"/api/orders/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<OrderViewModel>>(response);
Assert.That(data, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(data, Has.Count.EqualTo(0));
Assert.That(data.All(x => x.Products.Any(y => y.ProductId == _productId)));
});
}
[Test]
public async Task GetList_ByProductId_WhenNoRecords_ShouldSuccess_Test()
{
//Arrange
var product = TheBlacksmithVakulaDbContext.InsertProductToDatabaseAndReturn(_billetId, productName: "Other product");
TheBlacksmithVakulaDbContext.InsertOrderToDatabaseAndReturn(_blacksmithId, _buyerId, products: [(_productId, 10)]);
//Act
var response = await HttpClient.GetAsync($"/api/orders/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<OrderViewModel>>(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/orders/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/orders/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 order = TheBlacksmithVakulaDbContext.InsertOrderToDatabaseAndReturn(_blacksmithId, _buyerId, products: [(_productId, 5)]);
//Act
var response = await HttpClient.GetAsync($"/api/orders/getrecord/{order.Id}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
AssertElement(await GetModelFromResponseAsync<OrderViewModel>(response), order);
}
[Test]
public async Task GetElement_ById_WhenNoRecord_ShouldNotFound_Test()
{
//Arrange
TheBlacksmithVakulaDbContext.InsertOrderToDatabaseAndReturn(_blacksmithId, _buyerId, products: [(_productId, 5)]);
//Act
var response = await HttpClient.GetAsync($"/api/orders/getrecord/{Guid.NewGuid()}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
}
[Test]
public async Task GetElement_ById_WhenRecordHasCanceled_ShouldSuccess_Test()
{
//Arrange
var order = TheBlacksmithVakulaDbContext.InsertOrderToDatabaseAndReturn(_blacksmithId, _buyerId, products: [(_productId, 1)], isCancel: true);
//Act
var response = await HttpClient.GetAsync($"/api/orders/getrecord/{order.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/orders/getrecord/Id");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}
[Test]
public async Task Post_ShouldSuccess_Test()
{
//Arrange
TheBlacksmithVakulaDbContext.InsertOrderToDatabaseAndReturn(_blacksmithId, null, products: [(_productId, 5)]);
var orderModel = CreateModel(_blacksmithId, _buyerId, _productId);
//Act
var response = await HttpClient.PostAsync($"/api/orders/order", MakeContent(orderModel));
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
AssertElement(TheBlacksmithVakulaDbContext.GetOrdersByBuyerId(_buyerId)[0], orderModel);
}
[Test]
public async Task Post_WhenNoBuyer_ShouldSuccess_Test()
{
//Arrange
TheBlacksmithVakulaDbContext.InsertOrderToDatabaseAndReturn(_blacksmithId, _buyerId, products: [(_productId, 5)]);
var orderModel = CreateModel(_blacksmithId, null, _productId);
//Act
var response = await HttpClient.PostAsync($"/api/orders/order", MakeContent(orderModel));
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
AssertElement(TheBlacksmithVakulaDbContext.GetOrdersByBuyerId(null)[0], orderModel);
}
[Test]
public async Task Post_WhenDataIsIncorrect_ShouldBadRequest_Test()
{
//Arrange
var orderId = Guid.NewGuid().ToString();
var orderModelWithIdIncorrect = new OrderBindingModel { Id = "Id", BlacksmithId = _blacksmithId, BuyerId = _buyerId, DiscountType = 1, Products = [new OrderProductBindingModel { OrderId = orderId, ProductId = _productId, Count = 10 }] };
var orderModelWithBlacksmithIdIncorrect = new OrderBindingModel { Id = orderId, BlacksmithId = "Id", BuyerId = _buyerId, DiscountType = 1, Products = [new OrderProductBindingModel { OrderId = orderId, ProductId = _productId, Count = 10 }] };
var orderModelWithBuyerIdIncorrect = new OrderBindingModel { Id = orderId, BlacksmithId = _blacksmithId, BuyerId = "Id", DiscountType = 1, Products = [new OrderProductBindingModel { OrderId = orderId, ProductId = _productId, Count = 10 }] };
var orderModelWithProductsIncorrect = new OrderBindingModel { Id = orderId, BlacksmithId = _blacksmithId, BuyerId = _buyerId, DiscountType = 1, Products = null };
var orderModelWithProductIdIncorrect = new OrderBindingModel { Id = orderId, BlacksmithId = _blacksmithId, BuyerId = _buyerId, DiscountType = 1, Products = [new OrderProductBindingModel { OrderId = orderId, ProductId = "Id", Count = 10 }] };
var orderModelWithCountIncorrect = new OrderBindingModel { Id = orderId, BlacksmithId = _blacksmithId, BuyerId = _buyerId, DiscountType = 1, Products = [new OrderProductBindingModel { OrderId = orderId, ProductId = _productId, Count = -10 }] };
//Act
var responseWithIdIncorrect = await HttpClient.PostAsync($"/api/orders/order", MakeContent(orderModelWithIdIncorrect));
var responseWithBlacksmithIdIncorrect = await HttpClient.PostAsync($"/api/orders/order", MakeContent(orderModelWithBlacksmithIdIncorrect));
var responseWithBuyerIdIncorrect = await HttpClient.PostAsync($"/api/orders/order", MakeContent(orderModelWithBuyerIdIncorrect));
var responseWithProductsIncorrect = await HttpClient.PostAsync($"/api/orders/order", MakeContent(orderModelWithProductsIncorrect));
var responseWithProductIdIncorrect = await HttpClient.PostAsync($"/api/orders/order", MakeContent(orderModelWithProductIdIncorrect));
var responseWithCountIncorrect = await HttpClient.PostAsync($"/api/orders/order", MakeContent(orderModelWithCountIncorrect));
//Assert
Assert.Multiple(() =>
{
Assert.That(responseWithIdIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "BlacksmithId is incorrect");
Assert.That(responseWithBlacksmithIdIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "BlacksmithId 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");
});
}
[Test]
public async Task Post_WhenSendEmptyData_ShouldBadRequest_Test()
{
//Act
var response = await HttpClient.PostAsync($"/api/orders/order", 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/orders/order", MakeContent(new { Data = "test", Position = 10 }));
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}
[Test]
public async Task Delete_ShouldSuccess_Test()
{
//Arrange
var order = TheBlacksmithVakulaDbContext.InsertOrderToDatabaseAndReturn(_blacksmithId, _buyerId, products: [(_productId, 5)]);
//Act
var response = await HttpClient.DeleteAsync($"/api/orders/cancel/{order.Id}");
TheBlacksmithVakulaDbContext.ChangeTracker.Clear();
//Assert
Assert.Multiple(() =>
{
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
Assert.That(TheBlacksmithVakulaDbContext.GetOrderFromDatabaseById(order.Id)!.IsCancel);
});
}
[Test]
public async Task Delete_WhenNoFoundRecord_ShouldBadRequest_Test()
{
//Arrange
TheBlacksmithVakulaDbContext.InsertOrderToDatabaseAndReturn(_blacksmithId, _buyerId, products: [(_productId, 5)]);
//Act
var response = await HttpClient.DeleteAsync($"/api/orders/cancel/{Guid.NewGuid()}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}
[Test]
public async Task Delete_WhenIsCanceled_ShouldBadRequest_Test()
{
//Arrange
var order = TheBlacksmithVakulaDbContext.InsertOrderToDatabaseAndReturn(_blacksmithId, _buyerId, products: [(_productId, 5)], isCancel: true);
//Act
var response = await HttpClient.DeleteAsync($"/api/orders/cancel/{order.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/orders/cancel/id");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}
private static void AssertElement(OrderViewModel? actual, Order expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.Id, Is.EqualTo(expected.Id));
Assert.That(actual.BlacksmithFIO, Is.EqualTo(expected.Blacksmith!.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.OrderProducts is not null)
{
Assert.That(actual.Products, Is.Not.Null);
Assert.That(actual.Products, Has.Count.EqualTo(expected.OrderProducts.Count));
for (int i = 0; i < actual.Products.Count; ++i)
{
Assert.Multiple(() =>
{
Assert.That(actual.Products[i].ProductName, Is.EqualTo(expected.OrderProducts[i].Product!.ProductName));
Assert.That(actual.Products[i].Count, Is.EqualTo(expected.OrderProducts[i].Count));
});
}
}
else
{
Assert.That(actual.Products, Is.Null);
}
}
private static OrderBindingModel CreateModel(string blacksmithId, string? buyerId, string productId, string? id = null, DiscountType discountType = DiscountType.OnSale, int count = 1)
{
var orderId = id ?? Guid.NewGuid().ToString();
return new()
{
Id = orderId,
BlacksmithId = blacksmithId,
BuyerId = buyerId,
DiscountType = (int)discountType,
Products = [new OrderProductBindingModel { OrderId = orderId, ProductId = productId, Count = count }]
};
}
private static void AssertElement(Order? actual, OrderBindingModel expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.BlacksmithId, Is.EqualTo(expected.BlacksmithId));
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.OrderProducts, Is.Not.Null);
Assert.That(actual.OrderProducts, Has.Count.EqualTo(expected.Products.Count));
for (int i = 0; i < actual.OrderProducts.Count; ++i)
{
Assert.Multiple(() =>
{
Assert.That(actual.OrderProducts[i].ProductId, Is.EqualTo(expected.Products[i].ProductId));
Assert.That(actual.OrderProducts[i].Count, Is.EqualTo(expected.Products[i].Count));
});
}
}
else
{
Assert.That(actual.OrderProducts, Is.Null);
}
}
}
}

View File

@@ -0,0 +1,536 @@
using System.Net;
using TheBlacksmithVakulaContract.BindingModels;
using TheBlacksmithVakulaContract.Enums;
using TheBlacksmithVakulaContract.ViewModels;
using TheBlacksmithVakulaDatabase.Models;
using TheBlacksmithVakulaTests.Infrastructure;
namespace TheBlacksmithVakulaTests.WebApiControllersTests
{
[TestFixture]
internal class ProductControllerTests : BaseWebApiControllerTest
{
private string _billetId;
[SetUp]
public void SetUp()
{
_billetId = TheBlacksmithVakulaDbContext.InsertBilletToDatabaseAndReturn().Id;
}
[TearDown]
public void TearDown()
{
TheBlacksmithVakulaDbContext.RemoveProductsFromDatabase();
TheBlacksmithVakulaDbContext.RemoveBilletsFromDatabase();
}
[Test]
public async Task GetList_WhenHaveRecords_ShouldSuccess_Test()
{
//Arrange
var product = TheBlacksmithVakulaDbContext.InsertProductToDatabaseAndReturn(_billetId, productName: "name 1");
TheBlacksmithVakulaDbContext.InsertProductToDatabaseAndReturn(_billetId, productName: "name 2");
TheBlacksmithVakulaDbContext.InsertProductToDatabaseAndReturn(_billetId, 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
TheBlacksmithVakulaDbContext.InsertProductToDatabaseAndReturn(_billetId, productName: "name 1", isDeleted: true);
TheBlacksmithVakulaDbContext.InsertProductToDatabaseAndReturn(_billetId, productName: "name 2", isDeleted: false);
TheBlacksmithVakulaDbContext.InsertProductToDatabaseAndReturn(_billetId, 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
TheBlacksmithVakulaDbContext.InsertProductToDatabaseAndReturn(_billetId, productName: "name 1", isDeleted: true);
TheBlacksmithVakulaDbContext.InsertProductToDatabaseAndReturn(_billetId, productName: "name 2", isDeleted: true);
TheBlacksmithVakulaDbContext.InsertProductToDatabaseAndReturn(_billetId, 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_ByBillet_ShouldSuccess_Test()
{
//Arrange
var manufacruer = TheBlacksmithVakulaDbContext.InsertBilletToDatabaseAndReturn(billetName: "name 2");
var product = TheBlacksmithVakulaDbContext.InsertProductToDatabaseAndReturn(_billetId, productName: "name 1", isDeleted: true);
TheBlacksmithVakulaDbContext.InsertProductToDatabaseAndReturn(_billetId, productName: "name 2", isDeleted: false);
TheBlacksmithVakulaDbContext.InsertProductToDatabaseAndReturn(manufacruer.Id, productName: "name 3", isDeleted: false);
//Act
var response = await HttpClient.GetAsync($"/api/products/getbilletrecords?id={_billetId}&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.BilletId == _billetId));
});
AssertElement(data.First(x => x.Id == product.Id), product);
}
[Test]
public async Task GetList_ByBillet_WhenOnlyActual_ShouldSuccess_Test()
{
//Arrange
var manufacruer = TheBlacksmithVakulaDbContext.InsertBilletToDatabaseAndReturn(billetName: "name 2");
TheBlacksmithVakulaDbContext.InsertProductToDatabaseAndReturn(_billetId, productName: "name 1", isDeleted: true);
TheBlacksmithVakulaDbContext.InsertProductToDatabaseAndReturn(_billetId, productName: "name 2", isDeleted: false);
TheBlacksmithVakulaDbContext.InsertProductToDatabaseAndReturn(manufacruer.Id, productName: "name 3", isDeleted: false);
//Act
var response = await HttpClient.GetAsync($"/api/products/getbilletrecords?id={_billetId}&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.BilletId == _billetId && !x.IsDeleted));
});
}
[Test]
public async Task GetList_ByBillet_WhenIdIsNotGuid_ShouldBadRequest_Test()
{
//Act
var response = await HttpClient.GetAsync($"/api/products/getbilletrecords?id=id&includeDeleted=false");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}
[Test]
public async Task GetHistoryByProductId_WhenHaveRecords_ShouldSuccess_Test()
{
//Arrange
var product = TheBlacksmithVakulaDbContext.InsertProductToDatabaseAndReturn(_billetId);
TheBlacksmithVakulaDbContext.InsertProductHistoryToDatabaseAndReturn(product.Id, 20, DateTime.UtcNow.AddDays(-1));
TheBlacksmithVakulaDbContext.InsertProductHistoryToDatabaseAndReturn(product.Id, 30, DateTime.UtcNow.AddMinutes(-10));
var history = TheBlacksmithVakulaDbContext.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 = TheBlacksmithVakulaDbContext.InsertProductToDatabaseAndReturn(_billetId);
TheBlacksmithVakulaDbContext.InsertProductHistoryToDatabaseAndReturn(product.Id, 20, DateTime.UtcNow.AddDays(-1));
TheBlacksmithVakulaDbContext.InsertProductHistoryToDatabaseAndReturn(product.Id, 30, DateTime.UtcNow.AddMinutes(-10));
TheBlacksmithVakulaDbContext.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 = TheBlacksmithVakulaDbContext.InsertProductToDatabaseAndReturn(_billetId);
//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
TheBlacksmithVakulaDbContext.InsertProductToDatabaseAndReturn(_billetId);
//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 = TheBlacksmithVakulaDbContext.InsertProductToDatabaseAndReturn(_billetId, 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 = TheBlacksmithVakulaDbContext.InsertProductToDatabaseAndReturn(_billetId);
//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
TheBlacksmithVakulaDbContext.InsertProductToDatabaseAndReturn(_billetId);
//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 = TheBlacksmithVakulaDbContext.InsertProductToDatabaseAndReturn(_billetId, 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
TheBlacksmithVakulaDbContext.InsertProductToDatabaseAndReturn(_billetId);
var productModel = CreateModel(_billetId);
//Act
var response = await HttpClient.PostAsync($"/api/products/register", MakeContent(productModel));
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
AssertElement(TheBlacksmithVakulaDbContext.GetProductFromDatabaseById(productModel.Id!), productModel);
}
[Test]
public async Task Post_WhenHaveRecordWithSameId_ShouldBadRequest_Test()
{
//Arrange
var productModel = CreateModel(_billetId);
TheBlacksmithVakulaDbContext.InsertProductToDatabaseAndReturn(_billetId, 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(_billetId, productName: "unique name");
TheBlacksmithVakulaDbContext.InsertProductToDatabaseAndReturn(_billetId, 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", BilletId = _billetId, ProductName = "name", Price = 100, ProductType = ProductType.Tool.ToString() };
var productModelWithNameIncorrect = new ProductBindingModel { Id = Guid.NewGuid().ToString(), BilletId = _billetId, ProductName = string.Empty, Price = 100, ProductType = ProductType.Tool.ToString() };
var productModelWithProductTypeIncorrect = new ProductBindingModel { Id = Guid.NewGuid().ToString(), BilletId = _billetId, ProductName = "name", Price = 100, ProductType = string.Empty };
var productModelWithPriceIncorrect = new ProductBindingModel { Id = Guid.NewGuid().ToString(), BilletId = _billetId, ProductName = "name", Price = 0, ProductType = ProductType.Tool.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(_billetId);
TheBlacksmithVakulaDbContext.InsertProductToDatabaseAndReturn(_billetId, productModel.Id);
//Act
var response = await HttpClient.PutAsync($"/api/products/changeinfo", MakeContent(productModel));
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
TheBlacksmithVakulaDbContext.ChangeTracker.Clear();
AssertElement(TheBlacksmithVakulaDbContext.GetProductFromDatabaseById(productModel.Id!), productModel);
}
[Test]
public async Task Put_WhenNoFoundRecord_ShouldBadRequest_Test()
{
//Arrange
var productModel = CreateModel(_billetId);
TheBlacksmithVakulaDbContext.InsertProductToDatabaseAndReturn(_billetId);
//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(_billetId, productName: "unique name");
TheBlacksmithVakulaDbContext.InsertProductToDatabaseAndReturn(_billetId, productModel.Id);
TheBlacksmithVakulaDbContext.InsertProductToDatabaseAndReturn(_billetId, 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(_billetId);
TheBlacksmithVakulaDbContext.InsertProductToDatabaseAndReturn(_billetId, 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", BilletId = _billetId, ProductName = "name", Price = 100, ProductType = ProductType.Tool.ToString() };
var productModelWithNameIncorrect = new ProductBindingModel { Id = Guid.NewGuid().ToString(), BilletId = _billetId, ProductName = string.Empty, Price = 100, ProductType = ProductType.Tool.ToString() };
var productModelWithProductTypeIncorrect = new ProductBindingModel { Id = Guid.NewGuid().ToString(), BilletId = _billetId, ProductName = "name", Price = 100, ProductType = string.Empty };
var productModelWithPriceIncorrect = new ProductBindingModel { Id = Guid.NewGuid().ToString(), BilletId = _billetId, ProductName = "name", Price = 0, ProductType = ProductType.Tool.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();
TheBlacksmithVakulaDbContext.InsertProductToDatabaseAndReturn(_billetId, productId);
//Act
var response = await HttpClient.DeleteAsync($"/api/products/delete/{productId}");
TheBlacksmithVakulaDbContext.ChangeTracker.Clear();
//Assert
Assert.Multiple(() =>
{
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
Assert.That(TheBlacksmithVakulaDbContext.GetProductFromDatabaseById(productId)!.IsDeleted);
});
}
[Test]
public async Task Delete_WhenNoFoundRecord_ShouldBadRequest_Test()
{
//Arrange
TheBlacksmithVakulaDbContext.InsertProductToDatabaseAndReturn(_billetId);
//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 = TheBlacksmithVakulaDbContext.InsertProductToDatabaseAndReturn(_billetId, 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.BilletId, Is.EqualTo(expected.BilletId));
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.BilletName, Is.EqualTo(expected.Billet!.BilletName));
});
}
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 billetId, string? id = null, string productName = "name", ProductType productType = ProductType.Tool, double price = 1)
=> new()
{
Id = id ?? Guid.NewGuid().ToString(),
BilletId = billetId,
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.BilletId, Is.EqualTo(expected.BilletId));
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);
});
}
}
}

View File

@@ -0,0 +1,468 @@
using System.Net;
using TheBlacksmithVakulaContract.BindingModels;
using TheBlacksmithVakulaContract.Enums;
using TheBlacksmithVakulaContract.ViewModels;
using TheBlacksmithVakulaDatabase.Models;
using TheBlacksmithVakulaTests.Infrastructure;
namespace TheBlacksmithVakulaTests.WebApiControllersTests
{
[TestFixture]
internal class RankControllerTests : BaseWebApiControllerTest
{
[TearDown]
public void TearDown()
{
TheBlacksmithVakulaDbContext.RemoveRanksFromDatabase();
}
[Test]
public async Task GetRecords_WhenHaveRecords_ShouldSuccess_Test()
{
//Arrange
var rank = TheBlacksmithVakulaDbContext.InsertRankToDatabaseAndReturn(rankName: "name 1");
TheBlacksmithVakulaDbContext.InsertRankToDatabaseAndReturn(rankName: "name 2");
TheBlacksmithVakulaDbContext.InsertRankToDatabaseAndReturn(rankName: "name 3");
//Act
var response = await HttpClient.GetAsync("/api/ranks");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
var data = await GetModelFromResponseAsync<List<RankViewModel>>(response);
Assert.Multiple(() =>
{
Assert.That(data, Is.Not.Null);
Assert.That(data, Has.Count.EqualTo(3));
});
AssertElement(data.First(x => x.Id == rank.RankId), rank);
}
[Test]
public async Task GetRecords_WhenNoRecords_ShouldSuccess_Test()
{
//Act
var response = await HttpClient.GetAsync("/api/ranks");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
var data = await GetModelFromResponseAsync<List<BilletViewModel>>(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 rankId = Guid.NewGuid().ToString();
TheBlacksmithVakulaDbContext.InsertRankToDatabaseAndReturn(rankName: "name 1", isActual: true);
var rank = TheBlacksmithVakulaDbContext.InsertRankToDatabaseAndReturn(rankId, "name 2", isActual: true);
TheBlacksmithVakulaDbContext.InsertRankToDatabaseAndReturn(rankId, "name 2", isActual: false);
//Act
var response = await HttpClient.GetAsync($"/api/rankhistory/{rankId}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
var data = await GetModelFromResponseAsync<List<RankViewModel>>(response);
Assert.Multiple(() =>
{
Assert.That(data, Is.Not.Null);
Assert.That(data, Has.Count.EqualTo(2));
});
AssertElement(data.First(x => x.Id == rank.RankId), rank);
}
[Test]
public async Task GetHistory_WhenNoRecords_ShouldSuccess_Test()
{
//Arrange
var rankId = Guid.NewGuid().ToString();
TheBlacksmithVakulaDbContext.InsertRankToDatabaseAndReturn(rankName: "name 1", isActual: true);
TheBlacksmithVakulaDbContext.InsertRankToDatabaseAndReturn(rankId, "name 2", isActual: true);
TheBlacksmithVakulaDbContext.InsertRankToDatabaseAndReturn(rankId, "name 2", isActual: false);
//Act
var response = await HttpClient.GetAsync($"/api/rankhistory/{Guid.NewGuid()}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
var data = await GetModelFromResponseAsync<List<RankViewModel>>(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/rankhistory/id");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}
[Test]
public async Task GetElement_ById_WhenHaveRecord_ShouldSuccess_Test()
{
//Arrange
var rank = TheBlacksmithVakulaDbContext.InsertRankToDatabaseAndReturn();
//Act
var response = await HttpClient.GetAsync($"/api/ranks/{rank.RankId}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
AssertElement(await GetModelFromResponseAsync<RankViewModel>(response), rank);
}
[Test]
public async Task GetElement_ById_WhenNoRecord_ShouldNotFound_Test()
{
//Arrange
TheBlacksmithVakulaDbContext.InsertRankToDatabaseAndReturn();
//Act
var response = await HttpClient.GetAsync($"/api/ranks/{Guid.NewGuid()}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
}
[Test]
public async Task GetElement_ById_WhenRecordWasDeleted_ShouldNotFound_Test()
{
//Arrange
var rank = TheBlacksmithVakulaDbContext.InsertRankToDatabaseAndReturn(isActual: false);
//Act
var response = await HttpClient.GetAsync($"/api/ranks/{rank.RankId}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
}
[Test]
public async Task GetElement_ByName_WhenHaveRecord_ShouldSuccess_Test()
{
//Arrange
var rank = TheBlacksmithVakulaDbContext.InsertRankToDatabaseAndReturn();
//Act
var response = await HttpClient.GetAsync($"/api/ranks/{rank.RankName}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
AssertElement(await GetModelFromResponseAsync<RankViewModel>(response), rank);
}
[Test]
public async Task GetElement_ByName_WhenNoRecord_ShouldNotFound_Test()
{
//Arrange
TheBlacksmithVakulaDbContext.InsertRankToDatabaseAndReturn();
//Act
var response = await HttpClient.GetAsync($"/api/ranks/New%20Name");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
}
[Test]
public async Task GetElement_ByName_WhenRecordWasDeleted_ShouldNotFound_Test()
{
//Arrange
var rank = TheBlacksmithVakulaDbContext.InsertRankToDatabaseAndReturn(isActual: false);
//Act
var response = await HttpClient.GetAsync($"/api/ranks/{rank.RankName}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
}
[Test]
public async Task Post_ShouldSuccess_Test()
{
//Arrange
TheBlacksmithVakulaDbContext.InsertRankToDatabaseAndReturn();
var rankModel = CreateModel();
//Act
var response = await HttpClient.PostAsync($"/api/ranks", MakeContent(rankModel));
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
AssertElement(TheBlacksmithVakulaDbContext.GetRankFromDatabaseByRankId(rankModel.Id!), rankModel);
}
[Test]
public async Task Post_WhenHaveRecordWithSameId_ShouldBadRequest_Test()
{
//Arrange
var rankModel = CreateModel();
TheBlacksmithVakulaDbContext.InsertRankToDatabaseAndReturn(rankModel.Id);
//Act
var response = await HttpClient.PostAsync($"/api/ranks", MakeContent(rankModel));
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}
[Test]
public async Task Post_WhenHaveRecordWithSameName_ShouldBadRequest_Test()
{
//Arrange
var rankModel = CreateModel(rankName: "unique name");
TheBlacksmithVakulaDbContext.InsertRankToDatabaseAndReturn(rankName: rankModel.RankName!);
//Act
var response = await HttpClient.PostAsync($"/api/ranks", MakeContent(rankModel));
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}
[Test]
public async Task Post_WhenDataIsIncorrect_ShouldBadRequest_Test()
{
//Arrange
var rankModelWithIdIncorrect = new RankBindingModel { Id = "Id", RankName = "name", RankType = RankType.Master.ToString() };
var rankModelWithNameIncorrect = new RankBindingModel { Id = Guid.NewGuid().ToString(), RankName = string.Empty, RankType = RankType.Master.ToString() };
var rankModelWithRankTypeIncorrect = new RankBindingModel { Id = Guid.NewGuid().ToString(), RankName = string.Empty, RankType = string.Empty };
var rankModelWithSalaryIncorrect = new RankBindingModel { Id = Guid.NewGuid().ToString(), RankName = string.Empty, RankType = RankType.Master.ToString() };
//Act
var responseWithIdIncorrect = await HttpClient.PostAsync($"/api/ranks", MakeContent(rankModelWithIdIncorrect));
var responseWithNameIncorrect = await HttpClient.PostAsync($"/api/ranks", MakeContent(rankModelWithNameIncorrect));
var responseWithRankTypeIncorrect = await HttpClient.PostAsync($"/api/ranks", MakeContent(rankModelWithRankTypeIncorrect));
var responseWithSalaryIncorrect = await HttpClient.PostAsync($"/api/ranks", MakeContent(rankModelWithSalaryIncorrect));
//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(responseWithRankTypeIncorrect.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/ranks", 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/ranks", MakeContent(new { Data = "test", Position = 10 }));
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}
[Test]
public async Task Put_ShouldSuccess_Test()
{
//Arrange
var rankModel = CreateModel();
TheBlacksmithVakulaDbContext.InsertRankToDatabaseAndReturn(rankModel.Id);
//Act
var response = await HttpClient.PutAsync($"/api/ranks", MakeContent(rankModel));
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
TheBlacksmithVakulaDbContext.ChangeTracker.Clear();
AssertElement(TheBlacksmithVakulaDbContext.GetRankFromDatabaseByRankId(rankModel.Id!), rankModel);
}
[Test]
public async Task Put_WhenNoFoundRecord_ShouldBadRequest_Test()
{
//Arrange
var rankModel = CreateModel();
TheBlacksmithVakulaDbContext.InsertRankToDatabaseAndReturn();
//Act
var response = await HttpClient.PutAsync($"/api/ranks", MakeContent(rankModel));
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}
[Test]
public async Task Put_WhenRecordWasDeleted_ShouldBadRequest_Test()
{
//Arrange
var rankModel = CreateModel();
TheBlacksmithVakulaDbContext.InsertRankToDatabaseAndReturn(rankModel.Id, isActual: false);
//Act
var response = await HttpClient.PutAsync($"/api/ranks", MakeContent(rankModel));
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}
[Test]
public async Task Put_WhenHaveRecordWithSameName_ShouldBadRequest_Test()
{
//Arrange
var rankModel = CreateModel(rankName: "unique name");
TheBlacksmithVakulaDbContext.InsertRankToDatabaseAndReturn(rankModel.Id);
TheBlacksmithVakulaDbContext.InsertRankToDatabaseAndReturn(rankName: rankModel.RankName!);
//Act
var response = await HttpClient.PutAsync($"/api/ranks", MakeContent(rankModel));
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}
[Test]
public async Task Put_WhenDataIsIncorrect_ShouldBadRequest_Test()
{
//Arrange
var rankModelWithIdIncorrect = new RankBindingModel { Id = "Id", RankName = "name", RankType = RankType.Master.ToString() };
var rankModelWithNameIncorrect = new RankBindingModel { Id = Guid.NewGuid().ToString(), RankName = string.Empty, RankType = RankType.Master.ToString() };
var rankModelWithRankTypeIncorrect = new RankBindingModel { Id = Guid.NewGuid().ToString(), RankName = string.Empty, RankType = string.Empty };
var rankModelWithSalaryIncorrect = new RankBindingModel { Id = Guid.NewGuid().ToString(), RankName = string.Empty, RankType = RankType.Master.ToString() };
//Act
var responseWithIdIncorrect = await HttpClient.PutAsync($"/api/ranks", MakeContent(rankModelWithIdIncorrect));
var responseWithNameIncorrect = await HttpClient.PutAsync($"/api/ranks", MakeContent(rankModelWithNameIncorrect));
var responseWithRankTypeIncorrect = await HttpClient.PutAsync($"/api/ranks", MakeContent(rankModelWithRankTypeIncorrect));
var responseWithSalaryIncorrect = await HttpClient.PutAsync($"/api/ranks", MakeContent(rankModelWithSalaryIncorrect));
//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(responseWithRankTypeIncorrect.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/ranks", 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/ranks", MakeContent(new { Data = "test", Position = 10 }));
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}
[Test]
public async Task Delete_ShouldSuccess_Test()
{
//Arrange
var rankId = TheBlacksmithVakulaDbContext.InsertRankToDatabaseAndReturn().RankId;
//Act
var response = await HttpClient.DeleteAsync($"/api/ranks/{rankId}");
//Assert
Assert.Multiple(() =>
{
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
Assert.That(TheBlacksmithVakulaDbContext.GetRankFromDatabaseByRankId(rankId), Is.Null);
});
}
[Test]
public async Task Delete_WhenNoFoundRecord_ShouldBadRequest_Test()
{
//Arrange
TheBlacksmithVakulaDbContext.InsertRankToDatabaseAndReturn();
//Act
var response = await HttpClient.DeleteAsync($"/api/ranks/{Guid.NewGuid()}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}
[Test]
public async Task Delete_WhenRecordWasDeleted_Test()
{
//Arrange
var rankId = TheBlacksmithVakulaDbContext.InsertRankToDatabaseAndReturn(isActual: false).RankId;
//Act
var response = await HttpClient.DeleteAsync($"/api/ranks/{rankId}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}
[Test]
public async Task Delete_WhenSendWrongFormatData_ShouldBadRequest_Test()
{
//Act
var response = await HttpClient.DeleteAsync($"/api/ranks/id");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}
[Test]
public async Task Patch_ShouldSuccess_Test()
{
//Arrange
var rankId = TheBlacksmithVakulaDbContext.InsertRankToDatabaseAndReturn(isActual: false).RankId;
//Act
var response = await HttpClient.PatchAsync($"/api/ranks/{rankId}", null);
//Assert
Assert.Multiple(() =>
{
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
Assert.That(TheBlacksmithVakulaDbContext.GetRankFromDatabaseByRankId(rankId), Is.Not.Null);
});
}
[Test]
public async Task Patch_WhenNoFoundRecord_ShouldBadRequest_Test()
{
//Arrange
TheBlacksmithVakulaDbContext.InsertRankToDatabaseAndReturn();
//Act
var response = await HttpClient.PatchAsync($"/api/ranks/{Guid.NewGuid()}", null);
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}
[Test]
public async Task Patch_WhenRecordNotWasDeleted_ShouldSuccess_Test()
{
//Arrange
var rankId = TheBlacksmithVakulaDbContext.InsertRankToDatabaseAndReturn().RankId;
//Act
var response = await HttpClient.PatchAsync($"/api/ranks/{rankId}", null);
//Assert
Assert.Multiple(() =>
{
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
Assert.That(TheBlacksmithVakulaDbContext.GetRankFromDatabaseByRankId(rankId), Is.Not.Null);
});
}
[Test]
public async Task Patch_WhenSendWrongFormatData_ShouldBadRequest_Test()
{
//Act
var response = await HttpClient.PatchAsync($"/api/ranks/id", null);
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}
private static void AssertElement(RankViewModel? actual, Rank expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.Id, Is.EqualTo(expected.RankId));
Assert.That(actual.RankName, Is.EqualTo(expected.RankName));
Assert.That(actual.RankType, Is.EqualTo(expected.RankType.ToString()));
});
}
private static RankBindingModel CreateModel(string? rankId = null, string rankName = "name", RankType rankType = RankType.Master)
=> new()
{
Id = rankId ?? Guid.NewGuid().ToString(),
RankName = rankName,
RankType = rankType.ToString()
};
private static void AssertElement(Rank? actual, RankBindingModel expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.RankId, Is.EqualTo(expected.Id));
Assert.That(actual.RankName, Is.EqualTo(expected.RankName));
Assert.That(actual.RankType.ToString(), Is.EqualTo(expected.RankType));
});
}
}
}

View File

@@ -0,0 +1,240 @@
using System.Net;
using TheBlacksmithVakulaContract.ViewModels;
using TheBlacksmithVakulaDatabase.Models;
using TheBlacksmithVakulaTests.Infrastructure;
namespace TheBlacksmithVakulaTests.WebApiControllersTests
{
[TestFixture]
internal class SalaryControllerTests : BaseWebApiControllerTest
{
[TearDown]
public void TearDown()
{
TheBlacksmithVakulaDbContext.RemoveRanksFromDatabase();
TheBlacksmithVakulaDbContext.RemoveOrdersFromDatabase();
TheBlacksmithVakulaDbContext.RemoveProductsFromDatabase();
TheBlacksmithVakulaDbContext.RemoveBilletsFromDatabase();
TheBlacksmithVakulaDbContext.RemoveSalariesFromDatabase();
TheBlacksmithVakulaDbContext.RemoveBlacksmithsFromDatabase();
}
[Test]
public async Task GetList_WhenHaveRecords_ShouldSuccess_Test()
{
//Arrange
var blacksmith = TheBlacksmithVakulaDbContext.InsertBlacksmithToDatabaseAndReturn(fio: "name");
var salary = TheBlacksmithVakulaDbContext.InsertSalaryToDatabaseAndReturn(blacksmith.Id, blacksmithSalary: 100);
TheBlacksmithVakulaDbContext.InsertSalaryToDatabaseAndReturn(blacksmith.Id);
TheBlacksmithVakulaDbContext.InsertSalaryToDatabaseAndReturn(blacksmith.Id);
//Act
var response = await HttpClient.GetAsync($"/api/salaries/getrecords?fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
var data = await GetModelFromResponseAsync<List<SalaryViewModel>>(response);
Assert.Multiple(() =>
{
Assert.That(data, Is.Not.Null);
Assert.That(data, Has.Count.EqualTo(3));
});
AssertElement(data.First(x => x.Salary == salary.BlacksmithSalary), salary);
}
[Test]
public async Task GetList_WhenNoRecords_ShouldSuccess_Test()
{
//Act
var response = await HttpClient.GetAsync($"/api/salaries/getrecords?fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
var data = await GetModelFromResponseAsync<List<SalaryViewModel>>(response);
Assert.Multiple(() =>
{
Assert.That(data, Is.Not.Null);
Assert.That(data, Has.Count.EqualTo(0));
});
}
[Test]
public async Task GetList_OnlyInDatePeriod_ShouldSuccess_Test()
{
//Arrange
var blacksmith = TheBlacksmithVakulaDbContext.InsertBlacksmithToDatabaseAndReturn(fio: "name");
TheBlacksmithVakulaDbContext.InsertSalaryToDatabaseAndReturn(blacksmith.Id, salaryDate: DateTime.UtcNow.AddDays(-2));
TheBlacksmithVakulaDbContext.InsertSalaryToDatabaseAndReturn(blacksmith.Id, salaryDate: DateTime.UtcNow.AddDays(-1).AddMinutes(-5));
TheBlacksmithVakulaDbContext.InsertSalaryToDatabaseAndReturn(blacksmith.Id, salaryDate: DateTime.UtcNow.AddDays(-1).AddMinutes(5));
TheBlacksmithVakulaDbContext.InsertSalaryToDatabaseAndReturn(blacksmith.Id, salaryDate: DateTime.UtcNow.AddDays(1).AddMinutes(-5));
TheBlacksmithVakulaDbContext.InsertSalaryToDatabaseAndReturn(blacksmith.Id, salaryDate: DateTime.UtcNow.AddDays(1).AddMinutes(5));
TheBlacksmithVakulaDbContext.InsertSalaryToDatabaseAndReturn(blacksmith.Id, salaryDate: DateTime.UtcNow.AddDays(-2));
//Act
var response = await HttpClient.GetAsync($"/api/salaries/getrecords?fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
var data = await GetModelFromResponseAsync<List<SalaryViewModel>>(response);
Assert.That(data, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(data, Has.Count.EqualTo(2));
});
}
[Test]
public async Task GetList_WhenDateIsIncorrect_ShouldBadRequest_Test()
{
//Act
var response = await HttpClient.GetAsync($"/api/salaries/getblacksmithrecords?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_ByBlacksmith_ShouldSuccess_Test()
{
//Arrange
var blacksmith1 = TheBlacksmithVakulaDbContext.InsertBlacksmithToDatabaseAndReturn(fio: "name 1");
var blacksmith2 = TheBlacksmithVakulaDbContext.InsertBlacksmithToDatabaseAndReturn(fio: "name 2");
TheBlacksmithVakulaDbContext.InsertSalaryToDatabaseAndReturn(blacksmith1.Id);
TheBlacksmithVakulaDbContext.InsertSalaryToDatabaseAndReturn(blacksmith1.Id);
TheBlacksmithVakulaDbContext.InsertSalaryToDatabaseAndReturn(blacksmith2.Id);
//Act
var response = await HttpClient.GetAsync($"/api/salaries/getblacksmithrecords?fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}&id={blacksmith1.Id}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
var data = await GetModelFromResponseAsync<List<SalaryViewModel>>(response);
Assert.That(data, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(data, Has.Count.EqualTo(2));
Assert.That(data.All(x => x.BlacksmithId == blacksmith1.Id));
});
}
[Test]
public async Task GetList_ByBlacksmith_OnlyInDatePeriod_ShouldSuccess_Test()
{
//Arrange
var blacksmith1 = TheBlacksmithVakulaDbContext.InsertBlacksmithToDatabaseAndReturn(fio: "name 1");
var blacksmith2 = TheBlacksmithVakulaDbContext.InsertBlacksmithToDatabaseAndReturn(fio: "name 2");
TheBlacksmithVakulaDbContext.InsertSalaryToDatabaseAndReturn(blacksmith1.Id, salaryDate: DateTime.UtcNow.AddDays(-2));
TheBlacksmithVakulaDbContext.InsertSalaryToDatabaseAndReturn(blacksmith1.Id, salaryDate: DateTime.UtcNow.AddDays(-1).AddMinutes(5));
TheBlacksmithVakulaDbContext.InsertSalaryToDatabaseAndReturn(blacksmith2.Id, salaryDate: DateTime.UtcNow.AddDays(-1).AddMinutes(5));
TheBlacksmithVakulaDbContext.InsertSalaryToDatabaseAndReturn(blacksmith1.Id, salaryDate: DateTime.UtcNow.AddDays(1).AddMinutes(-5));
TheBlacksmithVakulaDbContext.InsertSalaryToDatabaseAndReturn(blacksmith2.Id, salaryDate: DateTime.UtcNow.AddDays(1).AddMinutes(-5));
TheBlacksmithVakulaDbContext.InsertSalaryToDatabaseAndReturn(blacksmith1.Id, salaryDate: DateTime.UtcNow.AddDays(-2));
//Act
var response = await HttpClient.GetAsync($"/api/salaries/getblacksmithrecords?fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}&id={blacksmith1.Id}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
var data = await GetModelFromResponseAsync<List<SalaryViewModel>>(response);
Assert.That(data, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(data, Has.Count.EqualTo(2));
Assert.That(data.All(x => x.BlacksmithId == blacksmith1.Id));
});
}
[Test]
public async Task GetList_ByBlacksmith_WhenDateIsIncorrect_ShouldBadRequest_Test()
{
//Arrange
var blacksmith = TheBlacksmithVakulaDbContext.InsertBlacksmithToDatabaseAndReturn(fio: "name 1");
//Act
var response = await HttpClient.GetAsync($"/api/salaries/getblacksmithrecords?fromDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&id={blacksmith.Id}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}
[Test]
public async Task GetList_ByBlacksmith_WhenIdIsNotGuid_ShouldBadRequest_Test()
{
//Act
var response = await HttpClient.GetAsync($"/api/salaries/getblacksmithrecords?fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}&id=id");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}
[Test]
public async Task Calculate_ShouldSuccess_Test()
{
//Arrange
var blacksmith = TheBlacksmithVakulaDbContext.InsertBlacksmithToDatabaseAndReturn(fio: "name");
var billet = TheBlacksmithVakulaDbContext.InsertBilletToDatabaseAndReturn();
var product = TheBlacksmithVakulaDbContext.InsertProductToDatabaseAndReturn(billet.Id, price: 100);
TheBlacksmithVakulaDbContext.InsertOrderToDatabaseAndReturn(blacksmith.Id, null, sum: 2000, products: [(product.Id, 10)]);
TheBlacksmithVakulaDbContext.InsertOrderToDatabaseAndReturn(blacksmith.Id, null, sum: 2000, products: [(product.Id, 10)]);
//Act
var response = await HttpClient.PostAsync($"/api/salaries/calculate?date={DateTime.UtcNow:MM/dd/yyyy}", null);
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
var salary = TheBlacksmithVakulaDbContext.GetSalariesFromDatabaseByBlacksmithId(blacksmith.Id);
Assert.Multiple(() =>
{
Assert.That(salary, Has.Length.EqualTo(1));
Assert.That(salary.First().BlacksmithSalary, Is.EqualTo(2000));
Assert.That(salary.First().SalaryDate.Month, Is.EqualTo(DateTime.UtcNow.Month));
});
}
[Test]
public async Task Calculate_WithSeveralBlacksmiths_ShouldSuccess_Test()
{
//Arrange
var blacksmith1 = TheBlacksmithVakulaDbContext.InsertBlacksmithToDatabaseAndReturn(fio: "name 1");
var blacksmith2 = TheBlacksmithVakulaDbContext.InsertBlacksmithToDatabaseAndReturn(fio: "name 2");
var blacksmith3 = TheBlacksmithVakulaDbContext.InsertBlacksmithToDatabaseAndReturn(fio: "name 3");
var billet = TheBlacksmithVakulaDbContext.InsertBilletToDatabaseAndReturn();
var product = TheBlacksmithVakulaDbContext.InsertProductToDatabaseAndReturn(billet.Id, price: 100);
TheBlacksmithVakulaDbContext.InsertOrderToDatabaseAndReturn(blacksmith1.Id, null, sum: 2000, products: [(product.Id, 10)]);
TheBlacksmithVakulaDbContext.InsertOrderToDatabaseAndReturn(blacksmith1.Id, null, sum: 2000, products: [(product.Id, 10)]);
TheBlacksmithVakulaDbContext.InsertOrderToDatabaseAndReturn(blacksmith2.Id, null, sum: 2000, products: [(product.Id, 10)]);
TheBlacksmithVakulaDbContext.InsertOrderToDatabaseAndReturn(blacksmith3.Id, null, sum: 2000, products: [(product.Id, 10)]);
//Act
var response = await HttpClient.PostAsync($"/api/salaries/calculate?date={DateTime.UtcNow:MM/dd/yyyy}", null);
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
var salary = TheBlacksmithVakulaDbContext.Salaries.ToArray();
Assert.That(salary, Has.Length.EqualTo(3));
}
[Test]
public async Task Calculate_WithoutBlacksmiths_ShouldSuccess_Test()
{
//Act
var response = await HttpClient.PostAsync($"/api/salaries/calculate?date={DateTime.UtcNow:MM/dd/yyyy}", null);
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
var salary = TheBlacksmithVakulaDbContext.Salaries.ToArray();
Assert.That(salary, Has.Length.EqualTo(0));
}
[Test]
public async Task Calculate_WithoutOrdersByBlacksmith_ShouldSuccess_Test()
{
//Arrange
var blacksmith1 = TheBlacksmithVakulaDbContext.InsertBlacksmithToDatabaseAndReturn(fio: "name 1");
var blacksmith2 = TheBlacksmithVakulaDbContext.InsertBlacksmithToDatabaseAndReturn(fio: "name 2");
var billet = TheBlacksmithVakulaDbContext.InsertBilletToDatabaseAndReturn();
var product = TheBlacksmithVakulaDbContext.InsertProductToDatabaseAndReturn(billet.Id, price: 100);
TheBlacksmithVakulaDbContext.InsertOrderToDatabaseAndReturn(blacksmith1.Id, null, orderDate: DateTime.UtcNow.AddMonths(-1), sum: 2000, products: [(product.Id, 10)]);
TheBlacksmithVakulaDbContext.InsertOrderToDatabaseAndReturn(blacksmith2.Id, null, sum: 2000, products: [(product.Id, 10)]);
//Act
var response = await HttpClient.PostAsync($"/api/salaries/calculate?date={DateTime.UtcNow:MM/dd/yyyy}", null);
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
var salary1 = TheBlacksmithVakulaDbContext.GetSalariesFromDatabaseByBlacksmithId(blacksmith1.Id).First().BlacksmithSalary;
var salary2 = TheBlacksmithVakulaDbContext.GetSalariesFromDatabaseByBlacksmithId(blacksmith2.Id).First().BlacksmithSalary;
Assert.That(salary1, Is.Not.EqualTo(salary2));
}
private static void AssertElement(SalaryViewModel? actual, Salary expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.BlacksmithFIO, Is.EqualTo(expected.Blacksmith!.FIO));
Assert.That(actual.Salary, Is.EqualTo(expected.BlacksmithSalary));
});
}
}
}

View File

@@ -0,0 +1,18 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": {
"Default": "Information"
},
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "../logs/theblacksmithvakula-.log",
"rollingInterval": "Day",
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}, { CorrelationId }, { Level: u3 }, { Username }, { Message: lj }, { Exception }, { NewLine }"
}
}
]
}
}

View File

@@ -0,0 +1,190 @@
using AutoMapper;
using TheBlacksmithVakulaContract.AdapterContracts;
using TheBlacksmithVakulaContract.AdapterContracts.OperationResponses;
using TheBlacksmithVakulaContract.BindingModels;
using TheBlacksmithVakulaContract.BusinessLogicsContracts;
using TheBlacksmithVakulaContract.DataModels;
using TheBlacksmithVakulaContract.Exceptions;
using TheBlacksmithVakulaContract.ViewModels;
namespace TheBlacksmithVakulaWebApi.Adapters
{
public class BilletAdapter : IBilletAdapter
{
private readonly IBilletBusinessLogicContract _billetBusinessLogicContract;
private readonly ILogger _logger;
private readonly Mapper _mapper;
public BilletAdapter(IBilletBusinessLogicContract billetBusinessLogicContract, ILogger<BilletAdapter> logger)
{
_billetBusinessLogicContract = billetBusinessLogicContract;
_logger = logger;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<BilletBindingModel, BilletDataModel>();
cfg.CreateMap<BilletDataModel, BilletViewModel>();
});
_mapper = new Mapper(config);
}
public BilletOperationResponse GetList()
{
try
{
return BilletOperationResponse.OK([.. _billetBusinessLogicContract.GetAllBillets().Select(x => _mapper.Map<BilletViewModel>(x))]);
}
catch (NullListException)
{
_logger.LogError("NullListException");
return BilletOperationResponse.NotFound("The list is not initialized");
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return BilletOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
}
catch (Exception ex)
{
_logger.LogError(ex, "Exception");
return BilletOperationResponse.InternalServerError(ex.Message);
}
}
public BilletOperationResponse GetElement(string data)
{
try
{
return BilletOperationResponse.OK(_mapper.Map<BilletViewModel>(_billetBusinessLogicContract.GetBilletByData(data)));
}
catch (ArgumentNullException ex)
{
_logger.LogError(ex, "ArgumentNullException");
return BilletOperationResponse.BadRequest("Data is empty");
}
catch (ElementNotFoundException ex)
{
_logger.LogError(ex, "ElementNotFoundException");
return BilletOperationResponse.NotFound($"Not found element by data {data}");
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return BilletOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
}
catch (Exception ex)
{
_logger.LogError(ex, "Exception");
return BilletOperationResponse.InternalServerError(ex.Message);
}
}
public BilletOperationResponse RegisterBillet(BilletBindingModel billetModel)
{
try
{
_billetBusinessLogicContract.InsertBillet(_mapper.Map<BilletDataModel>(billetModel));
return BilletOperationResponse.NoContent();
}
catch (ArgumentNullException ex)
{
_logger.LogError(ex, "ArgumentNullException");
return BilletOperationResponse.BadRequest("Data is empty");
}
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return BilletOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
}
catch (ElementExistsException ex)
{
_logger.LogError(ex, "ElementExistsException");
return BilletOperationResponse.BadRequest(ex.Message);
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return BilletOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
}
catch (Exception ex)
{
_logger.LogError(ex, "Exception");
return BilletOperationResponse.InternalServerError(ex.Message);
}
}
public BilletOperationResponse ChangeBilletInfo(BilletBindingModel billetModel)
{
try
{
_billetBusinessLogicContract.UpdateBillet(_mapper.Map<BilletDataModel>(billetModel));
return BilletOperationResponse.NoContent();
}
catch (ArgumentNullException ex)
{
_logger.LogError(ex, "ArgumentNullException");
return BilletOperationResponse.BadRequest("Data is empty");
}
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return BilletOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
}
catch (ElementNotFoundException ex)
{
_logger.LogError(ex, "ElementNotFoundException");
return BilletOperationResponse.BadRequest($"Not found element by Id {billetModel.Id}");
}
catch (ElementExistsException ex)
{
_logger.LogError(ex, "ElementExistsException");
return BilletOperationResponse.BadRequest(ex.Message);
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return BilletOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
}
catch (Exception ex)
{
_logger.LogError(ex, "Exception");
return BilletOperationResponse.InternalServerError(ex.Message);
}
}
public BilletOperationResponse RemoveBillet(string id)
{
try
{
_billetBusinessLogicContract.DeleteBillet(id);
return BilletOperationResponse.NoContent();
}
catch (ArgumentNullException ex)
{
_logger.LogError(ex, "ArgumentNullException");
return BilletOperationResponse.BadRequest("Id is empty");
}
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return BilletOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
}
catch (ElementNotFoundException ex)
{
_logger.LogError(ex, "ElementNotFoundException");
return BilletOperationResponse.BadRequest($"Not found element by id: {id}");
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return BilletOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
}
catch (Exception ex)
{
_logger.LogError(ex, "Exception");
return BilletOperationResponse.InternalServerError(ex.Message);
}
}
}
}

View File

@@ -0,0 +1,279 @@
using AutoMapper;
using TheBlacksmithVakulaContract.AdapterContracts;
using TheBlacksmithVakulaContract.AdapterContracts.OperationResponses;
using TheBlacksmithVakulaContract.BindingModels;
using TheBlacksmithVakulaContract.BusinessLogicsContracts;
using TheBlacksmithVakulaContract.DataModels;
using TheBlacksmithVakulaContract.Exceptions;
using TheBlacksmithVakulaContract.ViewModels;
namespace TheBlacksmithVakulaWebApi.Adapters
{
public class BlacksmithAdapter : IBlacksmithAdapter
{
private readonly IBlacksmithBusinessLogicContract _blacksmithBusinessLogicContract;
private readonly ILogger _logger;
private readonly Mapper _mapper;
public BlacksmithAdapter(IBlacksmithBusinessLogicContract blacksmithBusinessLogicContract, ILogger<BlacksmithAdapter> logger)
{
_blacksmithBusinessLogicContract = blacksmithBusinessLogicContract;
_logger = logger;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<BlacksmithBindingModel, BlacksmithDataModel>();
cfg.CreateMap<BlacksmithDataModel, BlacksmithViewModel>();
});
_mapper = new Mapper(config);
}
public BlacksmithOperationResponse GetList(bool includeDeleted)
{
try
{
return BlacksmithOperationResponse.OK([.. _blacksmithBusinessLogicContract.GetAllBlacksmith(!includeDeleted).Select(x => _mapper.Map<BlacksmithViewModel>(x))]);
}
catch (NullListException)
{
_logger.LogError("NullListException");
return BlacksmithOperationResponse.NotFound("The list is not initialized");
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return BlacksmithOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
}
catch (Exception ex)
{
_logger.LogError(ex, "Exception");
return BlacksmithOperationResponse.InternalServerError(ex.Message);
}
}
public BlacksmithOperationResponse GetRankList(string id, bool includeDeleted)
{
try
{
return BlacksmithOperationResponse.OK([.. _blacksmithBusinessLogicContract.GetAllBlacksmithByRank(id, !includeDeleted).Select(x => _mapper.Map<BlacksmithViewModel>(x))]);
}
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return BlacksmithOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
}
catch (NullListException)
{
_logger.LogError("NullListException");
return BlacksmithOperationResponse.NotFound("The list is not initialized");
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return BlacksmithOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
}
catch (Exception ex)
{
_logger.LogError(ex, "Exception");
return BlacksmithOperationResponse.InternalServerError(ex.Message);
}
}
public BlacksmithOperationResponse GetListByBirthDate(DateTime fromDate, DateTime toDate, bool includeDeleted)
{
try
{
return BlacksmithOperationResponse.OK([.. _blacksmithBusinessLogicContract.GetAllBlacksmithByBirthDate(fromDate, toDate, !includeDeleted).Select(x => _mapper.Map<BlacksmithViewModel>(x))]);
}
catch (IncorrectDatesException ex)
{
_logger.LogError(ex, "IncorrectDatesException");
return BlacksmithOperationResponse.BadRequest($"Incorrect dates: {ex.Message}");
}
catch (NullListException)
{
_logger.LogError("NullListException");
return BlacksmithOperationResponse.NotFound("The list is not initialized");
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return BlacksmithOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
}
catch (Exception ex)
{
_logger.LogError(ex, "Exception");
return BlacksmithOperationResponse.InternalServerError(ex.Message);
}
}
public BlacksmithOperationResponse GetListByEmploymentDate(DateTime fromDate, DateTime toDate, bool includeDeleted)
{
try
{
return BlacksmithOperationResponse.OK([.. _blacksmithBusinessLogicContract.GetAllBlacksmithByEmploymentDate(fromDate, toDate, !includeDeleted).Select(x => _mapper.Map<BlacksmithViewModel>(x))]);
}
catch (IncorrectDatesException ex)
{
_logger.LogError(ex, "IncorrectDatesException");
return BlacksmithOperationResponse.BadRequest($"Incorrect dates: {ex.Message}");
}
catch (NullListException)
{
_logger.LogError("NullListException");
return BlacksmithOperationResponse.NotFound("The list is not initialized");
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return BlacksmithOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
}
catch (Exception ex)
{
_logger.LogError(ex, "Exception");
return BlacksmithOperationResponse.InternalServerError(ex.Message);
}
}
public BlacksmithOperationResponse GetElement(string data)
{
try
{
return BlacksmithOperationResponse.OK(_mapper.Map<BlacksmithViewModel>(_blacksmithBusinessLogicContract.GetBlacksmithByData(data)));
}
catch (ArgumentNullException ex)
{
_logger.LogError(ex, "ArgumentNullException");
return BlacksmithOperationResponse.BadRequest("Data is empty");
}
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return BlacksmithOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
}
catch (ElementNotFoundException ex)
{
_logger.LogError(ex, "ElementNotFoundException");
return BlacksmithOperationResponse.NotFound($"Not found element by data {data}");
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return BlacksmithOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
}
catch (Exception ex)
{
_logger.LogError(ex, "Exception");
return BlacksmithOperationResponse.InternalServerError(ex.Message);
}
}
public BlacksmithOperationResponse RegisterBlacksmith(BlacksmithBindingModel blacksmithModel)
{
try
{
_blacksmithBusinessLogicContract.InsertBlacksmith(_mapper.Map<BlacksmithDataModel>(blacksmithModel));
return BlacksmithOperationResponse.NoContent();
}
catch (ArgumentNullException ex)
{
_logger.LogError(ex, "ArgumentNullException");
return BlacksmithOperationResponse.BadRequest("Data is empty");
}
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return BlacksmithOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
}
catch (ElementExistsException ex)
{
_logger.LogError(ex, "ElementExistsException");
return BlacksmithOperationResponse.BadRequest(ex.Message);
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return BlacksmithOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
}
catch (Exception ex)
{
_logger.LogError(ex, "Exception");
return BlacksmithOperationResponse.InternalServerError(ex.Message);
}
}
public BlacksmithOperationResponse ChangeBlacksmithInfo(BlacksmithBindingModel blacksmithModel)
{
try
{
_blacksmithBusinessLogicContract.UpdateBlacksmith(_mapper.Map<BlacksmithDataModel>(blacksmithModel));
return BlacksmithOperationResponse.NoContent();
}
catch (ArgumentNullException ex)
{
_logger.LogError(ex, "ArgumentNullException");
return BlacksmithOperationResponse.BadRequest("Data is empty");
}
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return BlacksmithOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
}
catch (ElementNotFoundException ex)
{
_logger.LogError(ex, "ElementNotFoundException");
return BlacksmithOperationResponse.BadRequest($"Not found element by Id {blacksmithModel.Id}");
}
catch (ElementExistsException ex)
{
_logger.LogError(ex, "ElementExistsException");
return BlacksmithOperationResponse.BadRequest(ex.Message);
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return BlacksmithOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
}
catch (Exception ex)
{
_logger.LogError(ex, "Exception");
return BlacksmithOperationResponse.InternalServerError(ex.Message);
}
}
public BlacksmithOperationResponse RemoveBlacksmith(string id)
{
try
{
_blacksmithBusinessLogicContract.DeleteBlacksmith(id);
return BlacksmithOperationResponse.NoContent();
}
catch (ArgumentNullException ex)
{
_logger.LogError(ex, "ArgumentNullException");
return BlacksmithOperationResponse.BadRequest("Id is empty");
}
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return BlacksmithOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
}
catch (ElementNotFoundException ex)
{
_logger.LogError(ex, "ElementNotFoundException");
return BlacksmithOperationResponse.BadRequest($"Not found element by id: {id}");
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return BlacksmithOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
}
catch (Exception ex)
{
_logger.LogError(ex, "Exception");
return BlacksmithOperationResponse.InternalServerError(ex.Message);
}
}
}
}

View File

@@ -0,0 +1,191 @@
using AutoMapper;
using TheBlacksmithVakulaContract.AdapterContracts;
using TheBlacksmithVakulaContract.AdapterContracts.OperationResponses;
using TheBlacksmithVakulaContract.BindingModels;
using TheBlacksmithVakulaContract.BusinessLogicsContracts;
using TheBlacksmithVakulaContract.DataModels;
using TheBlacksmithVakulaContract.Exceptions;
using TheBlacksmithVakulaContract.ViewModels;
namespace TheBlacksmithVakulaWebApi.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);
}
}
}
}

View File

@@ -0,0 +1,263 @@
using AutoMapper;
using TheBlacksmithVakulaContract.AdapterContracts;
using TheBlacksmithVakulaContract.AdapterContracts.OperationResponses;
using TheBlacksmithVakulaContract.BindingModels;
using TheBlacksmithVakulaContract.BusinessLogicsContracts;
using TheBlacksmithVakulaContract.DataModels;
using TheBlacksmithVakulaContract.Exceptions;
using TheBlacksmithVakulaContract.ViewModels;
namespace TheBlacksmithVakulaWebApi.Adapters
{
public class OrderAdapter : IOrderAdapter
{
private readonly IOrderBusinessLogicContract _orderBusinessLogicContract;
private readonly ILogger _logger;
private readonly Mapper _mapper;
public OrderAdapter(IOrderBusinessLogicContract orderBusinessLogicContract, ILogger<OrderAdapter> logger)
{
_orderBusinessLogicContract = orderBusinessLogicContract;
_logger = logger;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<OrderBindingModel, OrderDataModel>();
cfg.CreateMap<OrderDataModel, OrderViewModel>();
cfg.CreateMap<OrderProductBindingModel, OrderProductDataModel>();
cfg.CreateMap<OrderProductDataModel, OrderProductViewModel>();
});
_mapper = new Mapper(config);
}
public OrderOperationResponse GetList(DateTime fromDate, DateTime toDate)
{
try
{
return OrderOperationResponse.OK([.. _orderBusinessLogicContract.GetAllOrderByPeriod(fromDate, toDate).Select(x => _mapper.Map<OrderViewModel>(x))]);
}
catch (IncorrectDatesException ex)
{
_logger.LogError(ex, "IncorrectDatesException");
return OrderOperationResponse.BadRequest($"Incorrect dates: {ex.Message}");
}
catch (NullListException)
{
_logger.LogError("NullListException");
return OrderOperationResponse.NotFound("The list is not initialized");
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return OrderOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
}
catch (Exception ex)
{
_logger.LogError(ex, "Exception");
return OrderOperationResponse.InternalServerError(ex.Message);
}
}
public OrderOperationResponse GetBlacksmithList(string id, DateTime fromDate, DateTime toDate)
{
try
{
return OrderOperationResponse.OK([.. _orderBusinessLogicContract.GetAllOrderByBlacksmithByPeriod(id, fromDate, toDate).Select(x => _mapper.Map<OrderViewModel>(x))]);
}
catch (IncorrectDatesException ex)
{
_logger.LogError(ex, "IncorrectDatesException");
return OrderOperationResponse.BadRequest($"Incorrect dates: {ex.Message}");
}
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return OrderOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
}
catch (NullListException)
{
_logger.LogError("NullListException");
return OrderOperationResponse.NotFound("The list is not initialized");
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return OrderOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
}
catch (Exception ex)
{
_logger.LogError(ex, "Exception");
return OrderOperationResponse.InternalServerError(ex.Message);
}
}
public OrderOperationResponse GetBuyerList(string id, DateTime fromDate, DateTime toDate)
{
try
{
return OrderOperationResponse.OK([.. _orderBusinessLogicContract.GetAllOrderByBuyerByPeriod(id, fromDate, toDate).Select(x => _mapper.Map<OrderViewModel>(x))]);
}
catch (IncorrectDatesException ex)
{
_logger.LogError(ex, "IncorrectDatesException");
return OrderOperationResponse.BadRequest($"Incorrect dates: {ex.Message}");
}
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return OrderOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
}
catch (NullListException)
{
_logger.LogError("NullListException");
return OrderOperationResponse.NotFound("The list is not initialized");
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return OrderOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
}
catch (Exception ex)
{
_logger.LogError(ex, "Exception");
return OrderOperationResponse.InternalServerError(ex.Message);
}
}
public OrderOperationResponse GetProductList(string id, DateTime fromDate, DateTime toDate)
{
try
{
return OrderOperationResponse.OK([.. _orderBusinessLogicContract.GetAllOrderByProductByPeriod(id, fromDate, toDate).Select(x => _mapper.Map<OrderViewModel>(x))]);
}
catch (IncorrectDatesException ex)
{
_logger.LogError(ex, "IncorrectDatesException");
return OrderOperationResponse.BadRequest($"Incorrect dates: {ex.Message}");
}
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return OrderOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
}
catch (NullListException)
{
_logger.LogError("NullListException");
return OrderOperationResponse.NotFound("The list is not initialized");
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return OrderOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
}
catch (Exception ex)
{
_logger.LogError(ex, "Exception");
return OrderOperationResponse.InternalServerError(ex.Message);
}
}
public OrderOperationResponse GetElement(string id)
{
try
{
return OrderOperationResponse.OK(_mapper.Map<OrderViewModel>(_orderBusinessLogicContract.GetOrderByData(id)));
}
catch (ArgumentNullException ex)
{
_logger.LogError(ex, "ArgumentNullException");
return OrderOperationResponse.BadRequest("Data is empty");
}
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return OrderOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
}
catch (ElementNotFoundException ex)
{
_logger.LogError(ex, "ElementNotFoundException");
return OrderOperationResponse.NotFound($"Not found element by data {id}");
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return OrderOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
}
catch (Exception ex)
{
_logger.LogError(ex, "Exception");
return OrderOperationResponse.InternalServerError(ex.Message);
}
}
public OrderOperationResponse MakeOrder(OrderBindingModel orderModel)
{
try
{
var data = _mapper.Map<OrderDataModel>(orderModel);
_orderBusinessLogicContract.InsertOrder(_mapper.Map<OrderDataModel>(orderModel));
return OrderOperationResponse.NoContent();
}
catch (ArgumentNullException ex)
{
_logger.LogError(ex, "ArgumentNullException");
return OrderOperationResponse.BadRequest("Data is empty");
}
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return OrderOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return OrderOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
}
catch (Exception ex)
{
_logger.LogError(ex, "Exception");
return OrderOperationResponse.InternalServerError(ex.Message);
}
}
public OrderOperationResponse CancelOrder(string id)
{
try
{
_orderBusinessLogicContract.CancelOrder(id);
return OrderOperationResponse.NoContent();
}
catch (ArgumentNullException ex)
{
_logger.LogError(ex, "ArgumentNullException");
return OrderOperationResponse.BadRequest("Id is empty");
}
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return OrderOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
}
catch (ElementNotFoundException ex)
{
_logger.LogError(ex, "ElementNotFoundException");
return OrderOperationResponse.BadRequest($"Not found element by id: {id}");
}
catch (ElementDeletedException ex)
{
_logger.LogError(ex, "ElementDeletedException");
return OrderOperationResponse.BadRequest($"Element by id: {id} was deleted");
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return OrderOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
}
catch (Exception ex)
{
_logger.LogError(ex, "Exception");
return OrderOperationResponse.InternalServerError(ex.Message);
}
}
}
}

View File

@@ -0,0 +1,267 @@
using AutoMapper;
using TheBlacksmithVakulaContract.AdapterContracts;
using TheBlacksmithVakulaContract.AdapterContracts.OperationResponses;
using TheBlacksmithVakulaContract.BindingModels;
using TheBlacksmithVakulaContract.BusinessLogicsContracts;
using TheBlacksmithVakulaContract.DataModels;
using TheBlacksmithVakulaContract.Exceptions;
using TheBlacksmithVakulaContract.ViewModels;
namespace TheBlacksmithVakulaWebApi.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 GetBilletList(string id, bool includeDeleted)
{
try
{
return ProductOperationResponse.OK([.. _productBusinessLogicContract.GetAllProductsByBillet(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);
}
}
}
}

View File

@@ -0,0 +1,267 @@
using AutoMapper;
using TheBlacksmithVakulaContract.AdapterContracts;
using TheBlacksmithVakulaContract.AdapterContracts.OperationResponses;
using TheBlacksmithVakulaContract.BindingModels;
using TheBlacksmithVakulaContract.BusinessLogicsContracts;
using TheBlacksmithVakulaContract.DataModels;
using TheBlacksmithVakulaContract.Exceptions;
using TheBlacksmithVakulaContract.ViewModels;
namespace TheBlacksmithVakulaWebApi.Adapters
{
public class RankAdapter : IRankAdapter
{
private readonly IRankBusinessLogicContract _rankBusinessLogicContract;
private readonly ILogger _logger;
private readonly Mapper _mapper;
public RankAdapter(IRankBusinessLogicContract rankBusinessLogicContract, ILogger<RankAdapter> logger)
{
_rankBusinessLogicContract = rankBusinessLogicContract;
_logger = logger;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<RankBindingModel, RankDataModel>();
cfg.CreateMap<RankDataModel, RankViewModel>();
});
_mapper = new Mapper(config);
}
public RankOperationResponse GetList()
{
try
{
return RankOperationResponse.OK([.. _rankBusinessLogicContract.GetAllRanks().Select(x => _mapper.Map<RankViewModel>(x))]);
}
catch (NullListException)
{
_logger.LogError("NullListException");
return RankOperationResponse.NotFound("The list is not initialized");
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return RankOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
}
catch (Exception ex)
{
_logger.LogError(ex, "Exception");
return RankOperationResponse.InternalServerError(ex.Message);
}
}
public RankOperationResponse GetHistory(string id)
{
try
{
return RankOperationResponse.OK([.. _rankBusinessLogicContract.GetAllDataOfRank(id).Select(x => _mapper.Map<RankViewModel>(x))]);
}
catch (ArgumentNullException ex)
{
_logger.LogError(ex, "ArgumentNullException");
return RankOperationResponse.BadRequest("Data is empty");
}
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return RankOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return RankOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
}
catch (Exception ex)
{
_logger.LogError(ex, "Exception");
return RankOperationResponse.InternalServerError(ex.Message);
}
}
public RankOperationResponse GetElement(string data)
{
try
{
return RankOperationResponse.OK(_mapper.Map<RankViewModel>(_rankBusinessLogicContract.GetRankByData(data)));
}
catch (ArgumentNullException ex)
{
_logger.LogError(ex, "ArgumentNullException");
return RankOperationResponse.BadRequest("Data is empty");
}
catch (ElementNotFoundException ex)
{
_logger.LogError(ex, "ElementNotFoundException");
return RankOperationResponse.NotFound($"Not found element by data {data}");
}
catch (ElementDeletedException ex)
{
_logger.LogError(ex, "ElementDeletedException");
return RankOperationResponse.BadRequest($"Element by data: {data} was deleted");
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return RankOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
}
catch (Exception ex)
{
_logger.LogError(ex, "Exception");
return RankOperationResponse.InternalServerError(ex.Message);
}
}
public RankOperationResponse RegisterRank(RankBindingModel rankModel)
{
try
{
_rankBusinessLogicContract.InsertRank(_mapper.Map<RankDataModel>(rankModel));
return RankOperationResponse.NoContent();
}
catch (ArgumentNullException ex)
{
_logger.LogError(ex, "ArgumentNullException");
return RankOperationResponse.BadRequest("Data is empty");
}
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return RankOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
}
catch (ElementExistsException ex)
{
_logger.LogError(ex, "ElementExistsException");
return RankOperationResponse.BadRequest(ex.Message);
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return RankOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
}
catch (Exception ex)
{
_logger.LogError(ex, "Exception");
return RankOperationResponse.InternalServerError(ex.Message);
}
}
public RankOperationResponse ChangeRankInfo(RankBindingModel rankModel)
{
try
{
_rankBusinessLogicContract.UpdateRank(_mapper.Map<RankDataModel>(rankModel));
return RankOperationResponse.NoContent();
}
catch (ArgumentNullException ex)
{
_logger.LogError(ex, "ArgumentNullException");
return RankOperationResponse.BadRequest("Data is empty");
}
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return RankOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
}
catch (ElementNotFoundException ex)
{
_logger.LogError(ex, "ElementNotFoundException");
return RankOperationResponse.BadRequest($"Not found element by Id {rankModel.Id}");
}
catch (ElementExistsException ex)
{
_logger.LogError(ex, "ElementExistsException");
return RankOperationResponse.BadRequest(ex.Message);
}
catch (ElementDeletedException ex)
{
_logger.LogError(ex, "ElementDeletedException");
return RankOperationResponse.BadRequest($"Element by id: {rankModel.Id} was deleted");
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return RankOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
}
catch (Exception ex)
{
_logger.LogError(ex, "Exception");
return RankOperationResponse.InternalServerError(ex.Message);
}
}
public RankOperationResponse RemoveRank(string id)
{
try
{
_rankBusinessLogicContract.DeleteRank(id);
return RankOperationResponse.NoContent();
}
catch (ArgumentNullException ex)
{
_logger.LogError(ex, "ArgumentNullException");
return RankOperationResponse.BadRequest("Id is empty");
}
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return RankOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
}
catch (ElementNotFoundException ex)
{
_logger.LogError(ex, "ElementNotFoundException");
return RankOperationResponse.BadRequest($"Not found element by id: {id}");
}
catch (ElementDeletedException ex)
{
_logger.LogError(ex, "ElementDeletedException");
return RankOperationResponse.BadRequest($"Element by id: {id} was deleted");
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return RankOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
}
catch (Exception ex)
{
_logger.LogError(ex, "Exception");
return RankOperationResponse.InternalServerError(ex.Message);
}
}
public RankOperationResponse RestoreRank(string id)
{
try
{
_rankBusinessLogicContract.RestoreRank(id);
return RankOperationResponse.NoContent();
}
catch (ArgumentNullException ex)
{
_logger.LogError(ex, "ArgumentNullException");
return RankOperationResponse.BadRequest("Id is empty");
}
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return RankOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
}
catch (ElementNotFoundException ex)
{
_logger.LogError(ex, "ElementNotFoundException");
return RankOperationResponse.BadRequest($"Not found element by id: {id}");
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return RankOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
}
catch (Exception ex)
{
_logger.LogError(ex, "Exception");
return RankOperationResponse.InternalServerError(ex.Message);
}
}
}
}

View File

@@ -0,0 +1,120 @@
using AutoMapper;
using TheBlacksmithVakulaContract.AdapterContracts;
using TheBlacksmithVakulaContract.AdapterContracts.OperationResponses;
using TheBlacksmithVakulaContract.BusinessLogicsContracts;
using TheBlacksmithVakulaContract.DataModels;
using TheBlacksmithVakulaContract.Exceptions;
using TheBlacksmithVakulaContract.ViewModels;
namespace TheBlacksmithVakulaWebApi.Adapters
{
public class SalaryAdapter : ISalaryAdapter
{
private readonly ISalaryBusinessLogicContract _salaryBusinessLogicContract;
private readonly ILogger _logger;
private readonly Mapper _mapper;
public SalaryAdapter(ISalaryBusinessLogicContract salaryBusinessLogicContract, ILogger<SalaryAdapter> logger)
{
_salaryBusinessLogicContract = salaryBusinessLogicContract;
_logger = logger;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<SalaryDataModel, SalaryViewModel>();
});
_mapper = new Mapper(config);
}
public SalaryOperationResponse GetListByPeriod(DateTime fromDate, DateTime toDate)
{
try
{
return SalaryOperationResponse.OK([.. _salaryBusinessLogicContract.GetAllSalariesByPeriod(fromDate, toDate).Select(x => _mapper.Map<SalaryViewModel>(x))]);
}
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return SalaryOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
}
catch (IncorrectDatesException ex)
{
_logger.LogError(ex, "IncorrectDatesException");
return SalaryOperationResponse.BadRequest($"Incorrect dates: {ex.Message}");
}
catch (NullListException)
{
_logger.LogError("NullListException");
return SalaryOperationResponse.NotFound("The list is not initialized");
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return SalaryOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
}
catch (Exception ex)
{
_logger.LogError(ex, "Exception");
return SalaryOperationResponse.InternalServerError(ex.Message);
}
}
public SalaryOperationResponse GetListByPeriodByBlacksmith(DateTime fromDate, DateTime toDate, string blacksmithId)
{
try
{
return SalaryOperationResponse.OK([.. _salaryBusinessLogicContract.GetAllSalariesByPeriodByBlacksmith(fromDate, toDate, blacksmithId).Select(x => _mapper.Map<SalaryViewModel>(x))]);
}
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return SalaryOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
}
catch (IncorrectDatesException ex)
{
_logger.LogError(ex, "IncorrectDatesException");
return SalaryOperationResponse.BadRequest($"Incorrect dates: {ex.Message}");
}
catch (NullListException)
{
_logger.LogError("NullListException");
return SalaryOperationResponse.NotFound("The list is not initialized");
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return SalaryOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
}
catch (Exception ex)
{
_logger.LogError(ex, "Exception");
return SalaryOperationResponse.InternalServerError(ex.Message);
}
}
public SalaryOperationResponse CalculateSalary(DateTime date)
{
try
{
_salaryBusinessLogicContract.CalculateSalaryByMounth(date);
return SalaryOperationResponse.NoContent();
}
catch (NullListException)
{
_logger.LogError("NullListException");
return SalaryOperationResponse.NotFound("The list is not initialized");
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return SalaryOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
}
catch (Exception ex)
{
_logger.LogError(ex, "Exception");
return SalaryOperationResponse.InternalServerError(ex.Message);
}
}
}
}

View File

@@ -0,0 +1,14 @@
using Microsoft.IdentityModel.Tokens;
using System.Text;
namespace TheBlacksmithVakulaWebApi
{
public class AuthOptions
{
public const string ISSUER = "TheBlacksmithVakula_AuthServer";
public const string AUDIENCE = "TheBlacksmithVakula_AuthClient";
const string KEY = "vakulasecret_secretsecretsecretkey!123";
public static SymmetricSecurityKey GetSymmetricSecurityKey() => new(Encoding.UTF8.GetBytes(KEY));
}
}

View File

@@ -0,0 +1,46 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using TheBlacksmithVakulaContract.AdapterContracts;
using TheBlacksmithVakulaContract.BindingModels;
namespace TheBlacksmithVakulaWebApi.Controllers
{
[Authorize]
[Route("api/[controller]")]
[ApiController]
[Produces("application/json")]
public class BilletsController(IBilletAdapter adapter) : ControllerBase
{
private readonly IBilletAdapter _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] BilletBindingModel model)
{
return _adapter.RegisterBillet(model).GetResponse(Request, Response);
}
[HttpPut]
public IActionResult ChangeInfo([FromBody] BilletBindingModel model)
{
return _adapter.ChangeBilletInfo(model).GetResponse(Request, Response);
}
[HttpDelete("{id}")]
public IActionResult Delete(string id)
{
return _adapter.RemoveBillet(id).GetResponse(Request, Response);
}
}
}

View File

@@ -0,0 +1,64 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using TheBlacksmithVakulaContract.AdapterContracts;
using TheBlacksmithVakulaContract.BindingModels;
namespace TheBlacksmithVakulaWebApi.Controllers
{
[Authorize]
[Route("api/[controller]/[action]")]
[ApiController]
[Produces("application/json")]
public class BlacksmithsController(IBlacksmithAdapter adapter) : ControllerBase
{
private readonly IBlacksmithAdapter _adapter = adapter;
[HttpGet]
public IActionResult GetRecords(bool includeDeleted = false)
{
return _adapter.GetList(includeDeleted).GetResponse(Request, Response);
}
[HttpGet]
public IActionResult GetRankRecords(string id, bool includeDeleted = false)
{
return _adapter.GetRankList(id, includeDeleted).GetResponse(Request, Response);
}
[HttpGet]
public IActionResult GetBirthDateRecords(DateTime fromDate, DateTime toDate, bool includeDeleted = false)
{
return _adapter.GetListByBirthDate(fromDate, toDate, includeDeleted).GetResponse(Request, Response);
}
[HttpGet]
public IActionResult GetEmploymentRecords(DateTime fromDate, DateTime toDate, bool includeDeleted = false)
{
return _adapter.GetListByEmploymentDate(fromDate, toDate, includeDeleted).GetResponse(Request, Response);
}
[HttpGet("{data}")]
public IActionResult GetRecord(string data)
{
return _adapter.GetElement(data).GetResponse(Request, Response);
}
[HttpPost]
public IActionResult Register([FromBody] BlacksmithBindingModel model)
{
return _adapter.RegisterBlacksmith(model).GetResponse(Request, Response);
}
[HttpPut]
public IActionResult ChangeInfo([FromBody] BlacksmithBindingModel model)
{
return _adapter.ChangeBlacksmithInfo(model).GetResponse(Request, Response);
}
[HttpDelete("{id}")]
public IActionResult Delete(string id)
{
return _adapter.RemoveBlacksmith(id).GetResponse(Request, Response);
}
}
}

View File

@@ -0,0 +1,46 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using TheBlacksmithVakulaContract.AdapterContracts;
using TheBlacksmithVakulaContract.BindingModels;
namespace TheBlacksmithVakulaWebApi.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);
}
}
}

View File

@@ -0,0 +1,58 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using TheBlacksmithVakulaContract.AdapterContracts;
using TheBlacksmithVakulaContract.BindingModels;
namespace TheBlacksmithVakulaWebApi.Controllers
{
[Authorize]
[Route("api/[controller]/[action]")]
[ApiController]
[Produces("application/json")]
public class OrdersController(IOrderAdapter adapter) : ControllerBase
{
private readonly IOrderAdapter _adapter = adapter;
[HttpGet]
public IActionResult GetRecords(DateTime fromDate, DateTime toDate)
{
return _adapter.GetList(fromDate, toDate).GetResponse(Request, Response);
}
[HttpGet]
public IActionResult GetBlacksmithRecords(string id, DateTime fromDate, DateTime toDate)
{
return _adapter.GetBlacksmithList(id, fromDate, toDate).GetResponse(Request, Response);
}
[HttpGet]
public IActionResult GetBuyerRecords(string id, DateTime fromDate, DateTime toDate)
{
return _adapter.GetBuyerList(id, fromDate, toDate).GetResponse(Request, Response);
}
[HttpGet]
public IActionResult GetProductRecords(string id, DateTime fromDate, DateTime toDate)
{
return _adapter.GetProductList(id, fromDate, toDate).GetResponse(Request, Response);
}
[HttpGet("{data}")]
public IActionResult GetRecord(string data)
{
return _adapter.GetElement(data).GetResponse(Request, Response);
}
[HttpPost]
public IActionResult Order([FromBody] OrderBindingModel model)
{
return _adapter.MakeOrder(model).GetResponse(Request, Response);
}
[HttpDelete("{id}")]
public IActionResult Cancel(string id)
{
return _adapter.CancelOrder(id).GetResponse(Request, Response);
}
}
}

View File

@@ -0,0 +1,58 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using TheBlacksmithVakulaContract.AdapterContracts;
using TheBlacksmithVakulaContract.BindingModels;
namespace TheBlacksmithVakulaWebApi.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 GetBilletRecords(string id, bool includeDeleted)
{
return _adapter.GetBilletList(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);
}
}
}

View File

@@ -0,0 +1,21 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using TheBlacksmithVakulaContract.AdapterContracts;
namespace TheBlacksmithVakulaWebApi.Controllers
{
[Authorize]
[Route("api/[controller]")]
[ApiController]
[Produces("application/json")]
public class RankHistoryController(IRankAdapter adapter) : ControllerBase
{
private readonly IRankAdapter _adapter = adapter;
[HttpGet("{id}")]
public IActionResult GetHistory(string id)
{
return _adapter.GetHistory(id).GetResponse(Request, Response);
}
}
}

View File

@@ -0,0 +1,52 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using TheBlacksmithVakulaContract.AdapterContracts;
using TheBlacksmithVakulaContract.BindingModels;
namespace TheBlacksmithVakulaWebApi.Controllers
{
[Authorize]
[Route("api/[controller]")]
[ApiController]
[Produces("application/json")]
public class RanksController(IRankAdapter adapter) : ControllerBase
{
private readonly IRankAdapter _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] RankBindingModel model)
{
return _adapter.RegisterRank(model).GetResponse(Request, Response);
}
[HttpPut]
public IActionResult ChangeInfo([FromBody] RankBindingModel model)
{
return _adapter.ChangeRankInfo(model).GetResponse(Request, Response);
}
[HttpDelete("{id}")]
public IActionResult Delete(string id)
{
return _adapter.RemoveRank(id).GetResponse(Request, Response);
}
[HttpPatch("{id}")]
public IActionResult Restore(string id)
{
return _adapter.RestoreRank(id).GetResponse(Request, Response);
}
}
}

View File

@@ -0,0 +1,32 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using TheBlacksmithVakulaContract.AdapterContracts;
namespace TheBlacksmithVakulaWebApi.Controllers;
[Authorize]
[Route("api/[controller]/[action]")]
[ApiController]
[Produces("application/json")]
public class SalariesController(ISalaryAdapter adapter) : ControllerBase
{
private readonly ISalaryAdapter _adapter = adapter;
[HttpGet]
public IActionResult GetRecords(DateTime fromDate, DateTime toDate)
{
return _adapter.GetListByPeriod(fromDate, toDate).GetResponse(Request, Response);
}
[HttpGet]
public IActionResult GetBlacksmithRecords(string id, DateTime fromDate, DateTime toDate)
{
return _adapter.GetListByPeriodByBlacksmith(fromDate, toDate, id).GetResponse(Request, Response);
}
[HttpPost]
public IActionResult Calculate(DateTime date)
{
return _adapter.CalculateSalary(date).GetResponse(Request, Response);
}
}

View File

@@ -0,0 +1,35 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace TheBlacksmithVakulaWebApi.Controllers
{
[Authorize]
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
[HttpGet(Name = "GetWeatherForecast")]
public IEnumerable<WeatherForecast> Get()
{
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
})
.ToArray();
}
}
}

View File

@@ -0,0 +1,15 @@
using TheBlacksmithVakulaContract.Infrastructure;
namespace TheBlacksmithVakulaWebApi.Infrastructure
{
public class ConfigurationDataBase(IConfiguration configuration) : IConfigurationDatabase
{
private readonly Lazy<DataBaseSettings> _dataBaseSettings = new(() =>
{
return configuration.GetValue<DataBaseSettings>("DataBaseSettings") ??
throw new InvalidDataException(nameof(DataBaseSettings));
});
public string ConnectionString => _dataBaseSettings.Value.ConnectionString;
}
}

View File

@@ -0,0 +1,7 @@
namespace TheBlacksmithVakulaWebApi.Infrastructure
{
public class DataBaseSettings
{
public required string ConnectionString { get; set; }
}
}

View File

@@ -0,0 +1,111 @@
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using TheBlacksmithVakulaWebApi;
using Serilog;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using TheBlacksmithVakulaDatabase;
using Microsoft.EntityFrameworkCore;
using TheBlacksmithVakulaContract.BusinessLogicsContracts;
using TheBlacksmithVakulaContract.Infrastructure;
using TheBlacksmithVakulaContract.StoragesContracts;
using TheBlacksmithVakulaDatabase.Implementations;
using TheBlacksmithVakulaWebApi.Infrastructure;
using TheBlacksmithVakulaBusinessLogic.Implementations;
using TheBlacksmithVakulaContract.AdapterContracts;
using TheBlacksmithVakulaWebApi.Adapters;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi
builder.Services.AddOpenApi();
using var loggerFactory = new LoggerFactory();
loggerFactory.AddSerilog(new LoggerConfiguration().ReadFrom.Configuration(builder.Configuration).CreateLogger());
builder.Services.AddSingleton(loggerFactory.CreateLogger("Any"));
builder.Services.AddAuthorization();
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidIssuer = AuthOptions.ISSUER,
ValidateAudience = true,
ValidAudience = AuthOptions.AUDIENCE,
ValidateLifetime = true,
IssuerSigningKey = AuthOptions.GetSymmetricSecurityKey(),
ValidateIssuerSigningKey = true,
};
});
builder.Services.AddSingleton<IConfigurationDatabase, ConfigurationDataBase>();
builder.Services.AddTransient<IBuyerBusinessLogicContract,BuyerBusinessLogicContract>();
builder.Services.AddTransient<IBilletBusinessLogicContract,BilletBusinessLogicContract>();
builder.Services.AddTransient<IRankBusinessLogicContract,RankBusinessLogicContract>();
builder.Services.AddTransient<IProductBusinessLogicContract,ProductBusinessLogicContract>();
builder.Services.AddTransient<ISalaryBusinessLogicContract,SalaryBusinessLogicContract>();
builder.Services.AddTransient<IOrderBusinessLogicContract,OrderBusinessLogicContract>();
builder.Services.AddTransient<IBlacksmithBusinessLogicContract,BlacksmithBusinessLogicContract>();
builder.Services.AddTransient<TheBlacksmithVakulaDbContext>();
builder.Services.AddTransient<IBuyerStorageContract, BuyerStorageContract>();
builder.Services.AddTransient<IBilletStorageContract,BilletStorageContract>();
builder.Services.AddTransient<IRankStorageContract, RankStorageContract>();
builder.Services.AddTransient<IProductStorageContract, ProductStorageContract>();
builder.Services.AddTransient<ISalaryStorageContract, SalaryStorageContract>();
builder.Services.AddTransient<IOrderStorageContract, OrderStorageContract>();
builder.Services.AddTransient<IBlacksmithStorageContract, BlacksmithStorageContract>();
builder.Services.AddTransient<IBuyerAdapter, BuyerAdapter>();
builder.Services.AddTransient<IBilletAdapter, BilletAdapter>();
builder.Services.AddTransient<IRankAdapter, RankAdapter>();
builder.Services.AddTransient<IProductAdapter, ProductAdapter>();
builder.Services.AddTransient<IOrderAdapter, OrderAdapter>();
builder.Services.AddTransient<IBlacksmithAdapter, BlacksmithAdapter>();
builder.Services.AddTransient<ISalaryAdapter, SalaryAdapter>();
builder.Services.AddOpenApi();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.MapOpenApi();
}
if (app.Environment.IsProduction())
{
var dbContext = app.Services.GetRequiredService<TheBlacksmithVakulaDbContext>();
if (dbContext.Database.CanConnect())
{
dbContext.Database.EnsureCreated();
dbContext.Database.Migrate();
}
}
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.Map("/login/{username}", (string username) =>
{
return new JwtSecurityTokenHandler().WriteToken(new JwtSecurityToken(
issuer: AuthOptions.ISSUER,
audience: AuthOptions.AUDIENCE,
claims: [new(ClaimTypes.Name, username)],
expires: DateTime.UtcNow.Add(TimeSpan.FromMinutes(2)),
signingCredentials: new SigningCredentials(AuthOptions.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256)));
});
app.MapControllers();
app.Run();

View File

@@ -0,0 +1,23 @@
{
"$schema": "https://json.schemastore.org/launchsettings.json",
"profiles": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": false,
"applicationUrl": "http://localhost:5272",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": false,
"applicationUrl": "https://localhost:7010;http://localhost:5272",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}

View File

@@ -0,0 +1,25 @@
<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.4" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="9.0.4" />
<PackageReference Include="Serilog.AspNetCore" Version="9.0.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\TheBlacksmithVakulaBuisnessLogic\TheBlacksmithVakulaBusinessLogic.csproj" />
<ProjectReference Include="..\TheBlacksmithVakulaContract\TheBlacksmithVakulaContract.csproj" />
<ProjectReference Include="..\TheBlacksmithVakulaDatabase\TheBlacksmithVakulaDatabase.csproj" />
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="TheBlacksmithVakulaTests" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,6 @@
@TheBlacksmithVakulaWebApi_HostAddress = http://localhost:5272
GET {{TheBlacksmithVakulaWebApi_HostAddress}}/weatherforecast/
Accept: application/json
###

View File

@@ -0,0 +1,13 @@
namespace TheBlacksmithVakulaWebApi
{
public class WeatherForecast
{
public DateOnly Date { get; set; }
public int TemperatureC { get; set; }
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
public string? Summary { get; set; }
}
}

View File

@@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}

View File

@@ -0,0 +1,28 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": {
"Default": "Information"
},
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "../logs/theblacksmithvakula-.log",
"rollingInterval": "Day",
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}, { CorrelationId }, { Level: u3 }, { Username }, { Message: lj }, { Exception }, { NewLine }"
}
}
]
},
"DataBaseSettings": {
"ConnectionString": "Host=127.0.0.1;Port=5432;Database=TheBlacksmithVakula;Username=postgres;Password=postgres;"
},
"AllowedHosts": "*"
}