Compare commits
6 Commits
Task_3_Sto
...
Task_4_Api
| Author | SHA1 | Date | |
|---|---|---|---|
| 53f638495d | |||
| cb58370355 | |||
| 2cdb96a5d5 | |||
| d46875fe33 | |||
| 6e307bfb0f | |||
| 98af2eb8a1 |
@@ -1,19 +1,19 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net7.0</TargetFramework>
|
||||
<TargetFramework>net9.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<LangVersion>preview</LangVersion>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="AutoMapper" Version="12.0.0" />
|
||||
<PackageReference Include="AutoMapper" Version="14.0.0" />
|
||||
<PackageReference Include="EntityFramework" Version="6.5.1" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.15" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="9.0.3" />
|
||||
<PackageReference Include="Npgsql" Version="7.0.10" />
|
||||
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="7.0.11" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="9.0.4" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="9.0.4" />
|
||||
<PackageReference Include="Npgsql" Version="9.0.3" />
|
||||
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="9.0.4" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
@@ -22,6 +22,7 @@
|
||||
|
||||
<ItemGroup>
|
||||
<InternalsVisibleTo Include="AndDietCokeTests" />
|
||||
<InternalsVisibleTo Include="AndDietCokeWebApi" />
|
||||
<InternalsVisibleTo Include="DynamicProxyGenAssembly2" />
|
||||
</ItemGroup>
|
||||
|
||||
|
||||
@@ -25,7 +25,7 @@ internal class DishBusinessLogicContract(IDishStorageContract dishStorageContrac
|
||||
}
|
||||
public List<DishHistoryDataModel> GetDishHistoryByDish(string dishId)
|
||||
{
|
||||
_logger.LogInformation("GetProductHistoryByProduct for {dishId}", dishId);
|
||||
_logger.LogInformation("GetDishHistoryByDish for {dishId}", dishId);
|
||||
if (dishId.IsEmpty())
|
||||
{
|
||||
throw new ArgumentNullException(nameof(dishId));
|
||||
|
||||
@@ -77,9 +77,9 @@ internal class SaleBusinessLogicContract(ISaleStorageContract saleStorageContrac
|
||||
}
|
||||
if (!dishId.IsGuid())
|
||||
{
|
||||
throw new ValidationException("The value in the field productId is not a unique identifier.");
|
||||
throw new ValidationException("The value in the field dishId is not a unique identifier.");
|
||||
}
|
||||
return _saleStorageContract.GetList(fromDate, toDate, productId: dishId) ?? throw new NullListException();
|
||||
return _saleStorageContract.GetList(fromDate, toDate, dishId: dishId) ?? throw new NullListException();
|
||||
}
|
||||
|
||||
public SaleDataModel GetSaleByData(string data)
|
||||
|
||||
@@ -1,18 +1,18 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net7.0</TargetFramework>
|
||||
<TargetFramework>net9.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<LangVersion>preview</LangVersion>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="AutoMapper" Version="12.0.0" />
|
||||
<PackageReference Include="AutoMapper" Version="14.0.0" />
|
||||
<PackageReference Include="EntityFramework" Version="6.5.1" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.15" />
|
||||
<PackageReference Include="Npgsql" Version="7.0.10" />
|
||||
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="7.0.11" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="9.0.4" />
|
||||
<PackageReference Include="Npgsql" Version="9.0.3" />
|
||||
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="9.0.4" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
@@ -21,6 +21,7 @@
|
||||
|
||||
<ItemGroup>
|
||||
<InternalsVisibleTo Include="AndDietCokeTests" />
|
||||
<InternalsVisibleTo Include="AndDietCokeWebApi" />
|
||||
<InternalsVisibleTo Include="DynamicProxyGenAssembly2" />
|
||||
</ItemGroup>
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace AndDietCokeDatabase;
|
||||
|
||||
internal class AndDietCokeDbContext(IConfigurationDatabase configurationDatabase) : DbContext
|
||||
public class AndDietCokeDbContext(IConfigurationDatabase configurationDatabase) : DbContext
|
||||
{
|
||||
private readonly IConfigurationDatabase? _configurationDatabase = configurationDatabase;
|
||||
|
||||
|
||||
@@ -27,7 +27,8 @@ internal class SaleStorageContract : ISaleStorageContract
|
||||
.ConstructUsing(od => new OrderDishDataModel(
|
||||
od.OrderId,
|
||||
od.DishId,
|
||||
od.Count
|
||||
od.Count,
|
||||
od.Price
|
||||
));
|
||||
|
||||
cfg.CreateMap<Sale, SaleDataModel>()
|
||||
@@ -35,14 +36,14 @@ internal class SaleStorageContract : ISaleStorageContract
|
||||
src.Id,
|
||||
src.WorkerId,
|
||||
src.BuyerId,
|
||||
src.Sum,
|
||||
src.IsConstantClient,
|
||||
src.IsCancel,
|
||||
src.OrderDishes != null
|
||||
? src.OrderDishes.Select(od => new OrderDishDataModel(
|
||||
od.OrderId,
|
||||
od.DishId,
|
||||
od.Count
|
||||
od.Count,
|
||||
od.Price
|
||||
)).ToList()
|
||||
: new List<OrderDishDataModel>()
|
||||
));
|
||||
|
||||
@@ -13,6 +13,7 @@ public class OrderDish
|
||||
public required string DishId { get; set; }
|
||||
|
||||
public int Count { get; set; }
|
||||
public double Price { get; set; }
|
||||
|
||||
public Sale? Sale { get; set; }
|
||||
|
||||
|
||||
@@ -21,6 +21,9 @@ public class Worker
|
||||
public DateTime BirthDate { get; set; }
|
||||
|
||||
public DateTime EmploymentDate { get; set; }
|
||||
|
||||
[NotMapped]
|
||||
public Post? Post { get; set; }
|
||||
|
||||
public bool IsDeleted { get; set; }
|
||||
|
||||
@@ -29,4 +32,10 @@ public class Worker
|
||||
|
||||
[ForeignKey("WorkerId")]
|
||||
public List<Sale>? Sales { get; set; }
|
||||
|
||||
public Worker AddPost(Post? post)
|
||||
{
|
||||
Post = post;
|
||||
return this;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,11 +9,13 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AndDietCokeTests", "AndDiet
|
||||
EndProject
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AndDietCokeBuisnessLogic", "AndDietCokeBuisnessLogic\AndDietCokeBuisnessLogic.csproj", "{3C1C0E8F-5CB4-4E93-B20C-86FF4B248ECF}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AndDietCokeDatabase", "AndDietCokeDatabase\AndDietCokeDatabase.csproj", "{4AFC4FDC-F8CA-4CC5-84E2-162ADA98EDD4}"
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AndDietCokeDatabase", "AndDietCokeDatabase\AndDietCokeDatabase.csproj", "{4AFC4FDC-F8CA-4CC5-84E2-162ADA98EDD4}"
|
||||
ProjectSection(ProjectDependencies) = postProject
|
||||
{624595D1-D7AA-4448-AA30-4D5AA21AE6D6} = {624595D1-D7AA-4448-AA30-4D5AA21AE6D6}
|
||||
EndProjectSection
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AndDietCokeWebApi", "AndDietCokeWebApi\AndDietCokeWebApi.csproj", "{59659F17-4A33-47B1-951B-A329A547B3BF}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
@@ -36,6 +38,10 @@ Global
|
||||
{4AFC4FDC-F8CA-4CC5-84E2-162ADA98EDD4}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{4AFC4FDC-F8CA-4CC5-84E2-162ADA98EDD4}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{4AFC4FDC-F8CA-4CC5-84E2-162ADA98EDD4}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{59659F17-4A33-47B1-951B-A329A547B3BF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{59659F17-4A33-47B1-951B-A329A547B3BF}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{59659F17-4A33-47B1-951B-A329A547B3BF}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{59659F17-4A33-47B1-951B-A329A547B3BF}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
using AndDietCokeContracts.AdapterContracts.OperationResponses;
|
||||
using AndDietCokeContracts.BindingModels;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace AndDietCokeContracts.AdapterContracts;
|
||||
|
||||
public interface IBuyerAdapter
|
||||
{
|
||||
BuyerOperationResponse GetList();
|
||||
|
||||
BuyerOperationResponse GetElement(string data);
|
||||
|
||||
BuyerOperationResponse RegisterBuyer(BuyerBindingModel buyerModel);
|
||||
|
||||
BuyerOperationResponse ChangeBuyerInfo(BuyerBindingModel buyerModel);
|
||||
|
||||
BuyerOperationResponse RemoveBuyer(string id);
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
using AndDietCokeContracts.AdapterContracts.OperationResponses;
|
||||
using AndDietCokeContracts.BindingModels;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace AndDietCokeContracts.AdapterContracts;
|
||||
|
||||
public interface IDishAdapter
|
||||
{
|
||||
DishOperationResponse GetList(bool includeDeleted);
|
||||
|
||||
DishOperationResponse GetHistory(string id);
|
||||
|
||||
DishOperationResponse GetElement(string data);
|
||||
|
||||
DishOperationResponse RegisterDish(DishBindingModel dishModel);
|
||||
|
||||
DishOperationResponse ChangeDishInfo(DishBindingModel dishModel);
|
||||
|
||||
DishOperationResponse RemoveDish(string id);
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
using AndDietCokeContracts.AdapterContracts.OperationResponses;
|
||||
using AndDietCokeContracts.BindingModels;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace AndDietCokeContracts.AdapterContracts;
|
||||
|
||||
public interface IPostAdapter
|
||||
{
|
||||
PostOperationResponse GetList();
|
||||
|
||||
PostOperationResponse GetHistory(string id);
|
||||
|
||||
PostOperationResponse GetElement(string data);
|
||||
|
||||
PostOperationResponse RegisterPost(PostBindingModel postModel);
|
||||
|
||||
PostOperationResponse ChangePostInfo(PostBindingModel postModel);
|
||||
|
||||
PostOperationResponse RemovePost(string id);
|
||||
|
||||
PostOperationResponse RestorePost(string id);
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
using AndDietCokeContracts.AdapterContracts.OperationResponses;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace AndDietCokeContracts.AdapterContracts;
|
||||
|
||||
public interface ISalaryAdapter
|
||||
{
|
||||
SalaryOperationResponse GetListByPeriod(DateTime fromDate, DateTime toDate);
|
||||
SalaryOperationResponse GetListByPeriodByEmployee(DateTime fromDate, DateTime toDate, string employeeId);
|
||||
SalaryOperationResponse CalculateSalary(DateTime date);
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
using AndDietCokeContracts.AdapterContracts.OperationResponses;
|
||||
using AndDietCokeContracts.BindingModels;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace AndDietCokeContracts.AdapterContracts;
|
||||
|
||||
public interface ISaleAdapter
|
||||
{
|
||||
SaleOperationResponse GetList(DateTime fromDate, DateTime toDate);
|
||||
|
||||
SaleOperationResponse GetWorkerList(string id, DateTime fromDate, DateTime toDate);
|
||||
|
||||
SaleOperationResponse GetBuyerList(string id, DateTime fromDate, DateTime toDate);
|
||||
|
||||
SaleOperationResponse GetDishList(string id, DateTime fromDate, DateTime toDate);
|
||||
|
||||
SaleOperationResponse GetElement(string id);
|
||||
|
||||
SaleOperationResponse MakeSale(SaleBindingModel saleModel);
|
||||
|
||||
SaleOperationResponse CancelSale(string id);
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
using AndDietCokeContracts.AdapterContracts.OperationResponses;
|
||||
using AndDietCokeContracts.BindingModels;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace AndDietCokeContracts.AdapterContracts;
|
||||
|
||||
public interface IWorkerAdapter
|
||||
{
|
||||
WorkerOperationResponse GetList(bool includeDeleted);
|
||||
|
||||
WorkerOperationResponse GetPostList(string id, bool includeDeleted);
|
||||
|
||||
WorkerOperationResponse GetListByBirthDate(DateTime fromDate, DateTime toDate, bool includeDeleted);
|
||||
|
||||
WorkerOperationResponse GetListByEmploymentDate(DateTime fromDate, DateTime toDate, bool includeDeleted);
|
||||
|
||||
WorkerOperationResponse GetElement(string data);
|
||||
|
||||
WorkerOperationResponse RegisterWorker(WorkerBindingModel workerModel);
|
||||
|
||||
WorkerOperationResponse ChangeWorkerInfo(WorkerBindingModel workerModel);
|
||||
|
||||
WorkerOperationResponse RemoveWorker(string id);
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
using AndDietCokeContracts.Infrastrusture;
|
||||
using AndDietCokeContracts.ViewModels;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace AndDietCokeContracts.AdapterContracts.OperationResponses;
|
||||
|
||||
public class BuyerOperationResponse : OperationResponse
|
||||
{
|
||||
public static BuyerOperationResponse OK(List<BuyerViewModel> data) => OK<BuyerOperationResponse, List<BuyerViewModel>>(data);
|
||||
|
||||
public static BuyerOperationResponse OK(BuyerViewModel data) => OK<BuyerOperationResponse, BuyerViewModel>(data);
|
||||
|
||||
public static BuyerOperationResponse NoContent() => NoContent<BuyerOperationResponse>();
|
||||
|
||||
public static BuyerOperationResponse BadRequest(string message) => BadRequest<BuyerOperationResponse>(message);
|
||||
|
||||
public static BuyerOperationResponse NotFound(string message) => NotFound<BuyerOperationResponse>(message);
|
||||
|
||||
public static BuyerOperationResponse InternalServerError(string message) => InternalServerError<BuyerOperationResponse>(message);
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
using AndDietCokeContracts.Infrastrusture;
|
||||
using AndDietCokeContracts.ViewModels;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace AndDietCokeContracts.AdapterContracts.OperationResponses;
|
||||
|
||||
public class DishOperationResponse : OperationResponse
|
||||
{
|
||||
public static DishOperationResponse OK(List<DishViewModel> data) => OK<DishOperationResponse, List<DishViewModel>>(data);
|
||||
|
||||
public static DishOperationResponse OK(List<DishHistoryViewModel> data) => OK<DishOperationResponse, List<DishHistoryViewModel>>(data);
|
||||
|
||||
public static DishOperationResponse OK(DishViewModel data) => OK<DishOperationResponse, DishViewModel>(data);
|
||||
|
||||
public static DishOperationResponse NoContent() => NoContent<DishOperationResponse>();
|
||||
|
||||
public static DishOperationResponse NotFound(string message) => NotFound<DishOperationResponse>(message);
|
||||
|
||||
public static DishOperationResponse BadRequest(string message) => BadRequest<DishOperationResponse>(message);
|
||||
|
||||
public static DishOperationResponse InternalServerError(string message) => InternalServerError<DishOperationResponse>(message);
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
using AndDietCokeContracts.Infrastrusture;
|
||||
using AndDietCokeContracts.ViewModels;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace AndDietCokeContracts.AdapterContracts.OperationResponses;
|
||||
|
||||
public class PostOperationResponse : OperationResponse
|
||||
{
|
||||
public static PostOperationResponse OK(List<PostViewModel> data) => OK<PostOperationResponse, List<PostViewModel>>(data);
|
||||
|
||||
public static PostOperationResponse OK(PostViewModel data) => OK<PostOperationResponse, PostViewModel>(data);
|
||||
|
||||
public static PostOperationResponse NoContent() => NoContent<PostOperationResponse>();
|
||||
|
||||
public static PostOperationResponse NotFound(string message) => NotFound<PostOperationResponse>(message);
|
||||
|
||||
public static PostOperationResponse BadRequest(string message) => BadRequest<PostOperationResponse>(message);
|
||||
|
||||
public static PostOperationResponse InternalServerError(string message) => InternalServerError<PostOperationResponse>(message);
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
using AndDietCokeContracts.Infrastrusture;
|
||||
using AndDietCokeContracts.ViewModels;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace AndDietCokeContracts.AdapterContracts.OperationResponses;
|
||||
|
||||
public class SalaryOperationResponse : OperationResponse
|
||||
{
|
||||
public static SalaryOperationResponse OK(List<SalaryViewModel> data) => OK<SalaryOperationResponse, List<SalaryViewModel>>(data);
|
||||
|
||||
public static SalaryOperationResponse NoContent() => NoContent<SalaryOperationResponse>();
|
||||
|
||||
public static SalaryOperationResponse NotFound(string message) => NotFound<SalaryOperationResponse>(message);
|
||||
|
||||
public static SalaryOperationResponse BadRequest(string message) => BadRequest<SalaryOperationResponse>(message);
|
||||
|
||||
public static SalaryOperationResponse InternalServerError(string message) => InternalServerError<SalaryOperationResponse>(message);
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
using AndDietCokeContracts.Infrastrusture;
|
||||
using AndDietCokeContracts.ViewModels;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace AndDietCokeContracts.AdapterContracts.OperationResponses;
|
||||
|
||||
public class SaleOperationResponse : OperationResponse
|
||||
{
|
||||
public static SaleOperationResponse OK(List<SaleViewModel> data) => OK<SaleOperationResponse, List<SaleViewModel>>(data);
|
||||
|
||||
public static SaleOperationResponse OK(SaleViewModel data) => OK<SaleOperationResponse, SaleViewModel>(data);
|
||||
|
||||
public static SaleOperationResponse NoContent() => NoContent<SaleOperationResponse>();
|
||||
|
||||
public static SaleOperationResponse NotFound(string message) => NotFound<SaleOperationResponse>(message);
|
||||
|
||||
public static SaleOperationResponse BadRequest(string message) => BadRequest<SaleOperationResponse>(message);
|
||||
|
||||
public static SaleOperationResponse InternalServerError(string message) => InternalServerError<SaleOperationResponse>(message);
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
using AndDietCokeContracts.Infrastrusture;
|
||||
using AndDietCokeContracts.ViewModels;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace AndDietCokeContracts.AdapterContracts.OperationResponses;
|
||||
|
||||
public class WorkerOperationResponse : OperationResponse
|
||||
{
|
||||
public static WorkerOperationResponse OK(List<WorkerViewModel> data) => OK<WorkerOperationResponse, List<WorkerViewModel>>(data);
|
||||
|
||||
public static WorkerOperationResponse OK(WorkerViewModel data) => OK<WorkerOperationResponse, WorkerViewModel>(data);
|
||||
|
||||
public static WorkerOperationResponse NoContent() => NoContent<WorkerOperationResponse>();
|
||||
|
||||
public static WorkerOperationResponse NotFound(string message) => NotFound<WorkerOperationResponse>(message);
|
||||
|
||||
public static WorkerOperationResponse BadRequest(string message) => BadRequest<WorkerOperationResponse>(message);
|
||||
|
||||
public static WorkerOperationResponse InternalServerError(string message) => InternalServerError<WorkerOperationResponse>(message);
|
||||
}
|
||||
@@ -1,18 +1,20 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net7.0</TargetFramework>
|
||||
<TargetFramework>net9.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<LangVersion>preview</LangVersion>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="AutoMapper" Version="12.0.0" />
|
||||
<PackageReference Include="AutoMapper" Version="14.0.0" />
|
||||
<PackageReference Include="EntityFramework" Version="6.5.1" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.15" />
|
||||
<PackageReference Include="Npgsql" Version="7.0.10" />
|
||||
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="7.0.11" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Mvc.Abstractions" Version="2.3.0" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Mvc.Core" Version="2.3.0" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="9.0.4" />
|
||||
<PackageReference Include="Npgsql" Version="9.0.3" />
|
||||
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="9.0.4" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
namespace AndDietCokeContracts.BindingModels;
|
||||
|
||||
public class BuyerBindingModel
|
||||
{
|
||||
public string? Id { get; set; }
|
||||
|
||||
public string? FIO { get; set; }
|
||||
|
||||
public string? PhoneNumber { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace AndDietCokeContracts.BindingModels;
|
||||
|
||||
public class DishBindingModel
|
||||
{
|
||||
public string? Id { get; set; }
|
||||
|
||||
public string? DishName { get; set; }
|
||||
|
||||
public string? DishType { get; set; }
|
||||
|
||||
public double Price { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace AndDietCokeContracts.BindingModels;
|
||||
|
||||
public class OrderDishBindingModel
|
||||
{
|
||||
public string? SaleId { get; set; }
|
||||
|
||||
public string? DishId { get; set; }
|
||||
|
||||
public int Count { get; set; }
|
||||
|
||||
public double Price { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace AndDietCokeContracts.BindingModels;
|
||||
|
||||
public class PostBindingModel
|
||||
{
|
||||
public string? Id { get; set; }
|
||||
|
||||
public string? PostId => Id;
|
||||
|
||||
public string? PostName { get; set; }
|
||||
|
||||
public string? PostType { get; set; }
|
||||
|
||||
public double Salary { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace AndDietCokeContracts.BindingModels;
|
||||
|
||||
public class SaleBindingModel
|
||||
{
|
||||
public string? Id { get; set; }
|
||||
|
||||
public string? WorkerId { get; set; }
|
||||
|
||||
public string? BuyerId { get; set; }
|
||||
|
||||
public int DiscountType { get; set; }
|
||||
|
||||
public List<OrderDishBindingModel>? Dishes { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace AndDietCokeContracts.BindingModels;
|
||||
|
||||
public class WorkerBindingModel
|
||||
{
|
||||
public string? Id { get; set; }
|
||||
|
||||
public string? FIO { get; set; }
|
||||
|
||||
public string? PostId { get; set; }
|
||||
|
||||
public DateTime BirthDate { get; set; }
|
||||
|
||||
public DateTime EmploymentDate { get; set; }
|
||||
}
|
||||
@@ -3,17 +3,27 @@ using AndDietCokeContracts.Extensions;
|
||||
using AndDietCokeContracts.Infrastrusture;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace AndDietCokeContracts.DataModels;
|
||||
|
||||
public class OrderDishDataModel(string orderId, string dishId, int count) : IValidation
|
||||
public class OrderDishDataModel(string orderId, string dishId, int count, double price) : IValidation
|
||||
{
|
||||
private readonly DishDataModel? _dish;
|
||||
public string OrderId { get; private set; } = orderId;
|
||||
public string DishId { get; private set; } = dishId;
|
||||
public int Count { get; private set; } = count;
|
||||
public double Price { get; private set; } = price;
|
||||
public string DishName => _dish?.DishName ?? string.Empty;
|
||||
|
||||
public OrderDishDataModel(string saleId, string dishId, int count, double price, DishDataModel dish) : this(saleId, dishId, count, price)
|
||||
{
|
||||
_dish = dish;
|
||||
}
|
||||
|
||||
public void Validate()
|
||||
{
|
||||
if (OrderId.IsEmpty())
|
||||
|
||||
@@ -11,16 +11,43 @@ using System.Xml;
|
||||
|
||||
namespace AndDietCokeContracts.DataModels;
|
||||
|
||||
public class SaleDataModel(string id, string workerId, string? buyerId, double sum, bool isConstantClient, bool isCancel, List<OrderDishDataModel> dishes) : IValidation
|
||||
public class SaleDataModel : IValidation
|
||||
{
|
||||
public string Id { get; private set; } = id;
|
||||
public string WorkerId { get; private set; } = workerId;
|
||||
public string? BuyerId { get; private set; } = buyerId;
|
||||
public DateTime SaleDate { get; private set; } = DateTime.UtcNow;
|
||||
public double Sum { get; private set; } = sum;
|
||||
public bool IsConstantClient { get; private set; } = isConstantClient;
|
||||
public bool IsCancel { get; private set; } = isCancel;
|
||||
public List<OrderDishDataModel> Dishes { get; private set; } = dishes;
|
||||
private readonly BuyerDataModel? _buyer;
|
||||
|
||||
private readonly WorkerDataModel? _worker;
|
||||
|
||||
public string Id { get; private set; }
|
||||
public string WorkerId { get; private set; }
|
||||
public string? BuyerId { get; private set; }
|
||||
public DateTime SaleDate { get; private set; }
|
||||
public double Sum { get; private set; }
|
||||
public bool IsConstantClient { get; private set; }
|
||||
public bool IsCancel { get; private set; }
|
||||
public List<OrderDishDataModel> Dishes { get; private set; }
|
||||
public string BuyerFIO => _buyer?.FIO ?? string.Empty;
|
||||
public string WorkerFIO => _worker?.FIO ?? string.Empty;
|
||||
|
||||
public SaleDataModel(string id, string workerId, string? buyerId, bool isConstantClient, bool isCancel, List<OrderDishDataModel> orderDishes)
|
||||
{
|
||||
Id = id;
|
||||
WorkerId = workerId;
|
||||
BuyerId = buyerId;
|
||||
IsCancel = isCancel;
|
||||
IsConstantClient = isConstantClient;
|
||||
Dishes = orderDishes;
|
||||
var percent = 0.0;
|
||||
Sum = Dishes?.Sum(x => x.Price * x.Count) ?? 0;
|
||||
}
|
||||
|
||||
public SaleDataModel(string id, string workerId, string? buyerId, double sum, bool isConstantClient, bool isCancel, List<OrderDishDataModel> orderDishes, WorkerDataModel worker, BuyerDataModel? buyer) : this(id, workerId, buyerId, isConstantClient, isCancel, orderDishes)
|
||||
{
|
||||
Sum = sum;
|
||||
_worker = worker;
|
||||
_buyer = buyer;
|
||||
}
|
||||
|
||||
public SaleDataModel(string id, string workerId, string? buyerId, double sum, int discountType, List<OrderDishDataModel> dishes) : this(id, workerId, buyerId, true, false, dishes) { }
|
||||
|
||||
public void Validate()
|
||||
{
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace AndDietCokeContracts.Infrastrusture;
|
||||
|
||||
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 };
|
||||
}
|
||||
@@ -9,7 +9,7 @@ namespace AndDietCokeContracts.StoragesContracts;
|
||||
|
||||
public interface ISaleStorageContract
|
||||
{
|
||||
List<SaleDataModel> GetList(DateTime? startDate = null, DateTime? endDate = null, string? workerId = null, string? buyerId = null, string? productId = null);
|
||||
List<SaleDataModel> GetList(DateTime? startDate = null, DateTime? endDate = null, string? workerId = null, string? buyerId = null, string? dishId = null);
|
||||
SaleDataModel? GetElementById(string id);
|
||||
void AddElement(SaleDataModel saleDataModel);
|
||||
void DelElement(string id);
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace AndDietCokeContracts.ViewModels;
|
||||
|
||||
public class BuyerViewModel
|
||||
{
|
||||
public required string Id { get; set; }
|
||||
|
||||
public required string FIO { get; set; }
|
||||
|
||||
public required string PhoneNumber { get; set; }
|
||||
|
||||
public double DiscountSize { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace AndDietCokeContracts.ViewModels;
|
||||
|
||||
public class DishHistoryViewModel
|
||||
{
|
||||
public required string DishName { get; set; }
|
||||
|
||||
public double OldPrice { get; set; }
|
||||
|
||||
public DateTime ChangeDate { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace AndDietCokeContracts.ViewModels;
|
||||
|
||||
public class DishViewModel
|
||||
{
|
||||
public required string Id { get; set; }
|
||||
|
||||
public required string DishName { get; set; }
|
||||
|
||||
public required string DishType { get; set; }
|
||||
|
||||
public double Price { get; set; }
|
||||
|
||||
public bool IsDeleted { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace AndDietCokeContracts.ViewModels;
|
||||
|
||||
public class OrderDishViewModel
|
||||
{
|
||||
public required string DishId { get; set; }
|
||||
|
||||
public required string DishName { get; set; }
|
||||
|
||||
public int Count { get; set; }
|
||||
|
||||
public double Price { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace AndDietCokeContracts.ViewModels;
|
||||
|
||||
public class PostViewModel
|
||||
{
|
||||
public required string Id { get; set; }
|
||||
|
||||
public required string PostName { get; set; }
|
||||
|
||||
public required string PostType { get; set; }
|
||||
|
||||
public double Salary { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace AndDietCokeContracts.ViewModels;
|
||||
|
||||
public class SalaryViewModel
|
||||
{
|
||||
public required string WorkerId { get; set; }
|
||||
public required string WorkerFIO { get; set; }
|
||||
public DateTime SalaryDate { get; set; }
|
||||
public double Salary { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace AndDietCokeContracts.ViewModels;
|
||||
|
||||
public class SaleViewModel
|
||||
{
|
||||
public required string Id { get; set; }
|
||||
|
||||
public required string WorkerId { get; set; }
|
||||
|
||||
public required string WorkerFIO { get; set; }
|
||||
|
||||
public string? BuyerId { get; set; }
|
||||
|
||||
public string? BuyerFIO { get; set; }
|
||||
|
||||
public DateTime SaleDate { get; set; }
|
||||
|
||||
public double Sum { get; set; }
|
||||
|
||||
public required string DiscountType { get; set; }
|
||||
|
||||
public double Discount { get; set; }
|
||||
|
||||
public bool IsCancel { get; set; }
|
||||
|
||||
public required List<OrderDishViewModel> Dishes { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace AndDietCokeContracts.ViewModels;
|
||||
|
||||
public class WorkerViewModel
|
||||
{
|
||||
public required string Id { get; set; }
|
||||
|
||||
public required string FIO { get; set; }
|
||||
|
||||
public required string PostId { get; set; }
|
||||
|
||||
public required string PostName { get; set; }
|
||||
|
||||
public bool IsDeleted { get; set; }
|
||||
|
||||
public DateTime BirthDate { get; set; }
|
||||
|
||||
public DateTime EmploymentDate { get; set; }
|
||||
}
|
||||
@@ -1,34 +1,48 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net7.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net9.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
|
||||
<IsPackable>false</IsPackable>
|
||||
<IsTestProject>true</IsTestProject>
|
||||
<LangVersion>preview</LangVersion>
|
||||
</PropertyGroup>
|
||||
<IsPackable>false</IsPackable>
|
||||
<IsTestProject>true</IsTestProject>
|
||||
<LangVersion>preview</LangVersion>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="AutoMapper" Version="14.0.0" />
|
||||
<PackageReference Include="EntityFramework" Version="6.5.1" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="9.0.4" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="9.0.4" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="9.0.4" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="9.0.4" />
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.13.0" />
|
||||
<PackageReference Include="Moq" Version="4.20.72" />
|
||||
<PackageReference Include="Npgsql" Version="9.0.3" />
|
||||
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="9.0.4" />
|
||||
<PackageReference Include="NUnit" Version="4.3.2" />
|
||||
<PackageReference Include="NUnit3TestAdapter" Version="5.0.0" />
|
||||
<PackageReference Include="NUnit.Analyzers" Version="4.7.0">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="coverlet.collector" Version="6.0.4">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="Serilog" Version="4.2.0" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="AutoMapper" Version="12.0.0" />
|
||||
<PackageReference Include="EntityFramework" Version="6.5.1" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.15" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="9.0.3" />
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.6.0" />
|
||||
<PackageReference Include="Moq" Version="4.20.72" />
|
||||
<PackageReference Include="Npgsql" Version="7.0.10" />
|
||||
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="7.0.11" />
|
||||
<PackageReference Include="NUnit" Version="3.13.3" />
|
||||
<PackageReference Include="NUnit3TestAdapter" Version="4.4.2" />
|
||||
<PackageReference Include="NUnit.Analyzers" Version="3.6.1" />
|
||||
<PackageReference Include="coverlet.collector" Version="3.2.0" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\AndDietCokeBuisnessLogic\AndDietCokeBuisnessLogic.csproj" />
|
||||
<ProjectReference Include="..\AndDietCokeDatabase\AndDietCokeDatabase.csproj" />
|
||||
<ProjectReference Include="..\AndDietCokeProject\AndDietCokeContracts.csproj" />
|
||||
<ProjectReference Include="..\AndDietCokeWebApi\AndDietCokeWebApi.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\AndDietCokeBuisnessLogic\AndDietCokeBuisnessLogic.csproj" />
|
||||
<ProjectReference Include="..\AndDietCokeDatabase\AndDietCokeDatabase.csproj" />
|
||||
<ProjectReference Include="..\AndDietCokeProject\AndDietCokeContracts.csproj" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Using Include="NUnit.Framework" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
||||
@@ -192,10 +192,12 @@ internal class SalaryBuisnessLogicContractTests
|
||||
{
|
||||
//Arrange
|
||||
var workerId = Guid.NewGuid().ToString();
|
||||
var saleSum = 200.0;
|
||||
int saleSum = 200;
|
||||
var postSalary = 2000.0;
|
||||
|
||||
var dish = new OrderDishDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), saleSum, 1) ;
|
||||
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
|
||||
.Returns([new SaleDataModel(Guid.NewGuid().ToString(), workerId, null, saleSum, true, false, [])]);
|
||||
.Returns([new SaleDataModel(Guid.NewGuid().ToString(), workerId, null, true, false, [dish])]);
|
||||
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
|
||||
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Waiter, postSalary, true, DateTime.UtcNow));
|
||||
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
|
||||
@@ -226,11 +228,11 @@ internal class SalaryBuisnessLogicContractTests
|
||||
new(worker3Id, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)
|
||||
};
|
||||
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
|
||||
.Returns([new SaleDataModel(Guid.NewGuid().ToString(), worker1Id, null, 1, true, false, []),
|
||||
new SaleDataModel(Guid.NewGuid().ToString(), worker1Id, null, 1, true, false, []),
|
||||
new SaleDataModel(Guid.NewGuid().ToString(), worker2Id, null, 1, true, false, []),
|
||||
new SaleDataModel(Guid.NewGuid().ToString(), worker3Id, null, 1, true, false, []),
|
||||
new SaleDataModel(Guid.NewGuid().ToString(), worker3Id, null, 1, true, false, [])]);
|
||||
.Returns([new SaleDataModel(Guid.NewGuid().ToString(), worker1Id, null, true, false, []),
|
||||
new SaleDataModel(Guid.NewGuid().ToString(), worker1Id, null, true, false, []),
|
||||
new SaleDataModel(Guid.NewGuid().ToString(), worker2Id, null, true, false, []),
|
||||
new SaleDataModel(Guid.NewGuid().ToString(), worker3Id, null, true, false, []),
|
||||
new SaleDataModel(Guid.NewGuid().ToString(), worker3Id, null, true, false, [])]);
|
||||
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
|
||||
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Chef, 2000, true, DateTime.UtcNow));
|
||||
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
|
||||
@@ -285,7 +287,7 @@ internal class SalaryBuisnessLogicContractTests
|
||||
//Arrange
|
||||
var workerId = Guid.NewGuid().ToString();
|
||||
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
|
||||
.Returns([new SaleDataModel(Guid.NewGuid().ToString(), workerId, null, 200, true, false, [])]);
|
||||
.Returns([new SaleDataModel(Guid.NewGuid().ToString(), workerId, null, true, false, [])]);
|
||||
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
|
||||
.Returns([new WorkerDataModel(workerId, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)]);
|
||||
//Act&Assert
|
||||
@@ -298,7 +300,7 @@ internal class SalaryBuisnessLogicContractTests
|
||||
//Arrange
|
||||
var workerId = Guid.NewGuid().ToString();
|
||||
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
|
||||
.Returns([new SaleDataModel(Guid.NewGuid().ToString(), workerId, null, 200, true, false, [])]);
|
||||
.Returns([new SaleDataModel(Guid.NewGuid().ToString(), workerId, null, true, false, [])]);
|
||||
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
|
||||
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Chef, 2000, true, DateTime.UtcNow));
|
||||
//Act&Assert
|
||||
@@ -326,7 +328,7 @@ internal class SalaryBuisnessLogicContractTests
|
||||
//Arrange
|
||||
var workerId = Guid.NewGuid().ToString();
|
||||
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
|
||||
.Returns([new SaleDataModel(Guid.NewGuid().ToString(), workerId, null, 200, true, false, [])]);
|
||||
.Returns([new SaleDataModel(Guid.NewGuid().ToString(), workerId, null, true, false, [])]);
|
||||
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
|
||||
.Throws(new StorageException(new InvalidOperationException()));
|
||||
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
|
||||
@@ -341,7 +343,7 @@ internal class SalaryBuisnessLogicContractTests
|
||||
//Arrange
|
||||
var workerId = Guid.NewGuid().ToString();
|
||||
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
|
||||
.Returns([new SaleDataModel(Guid.NewGuid().ToString(), workerId, null, 200, true, false, [])]);
|
||||
.Returns([new SaleDataModel(Guid.NewGuid().ToString(), workerId, null, true, false, [])]);
|
||||
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
|
||||
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Chef, 2000, true, DateTime.UtcNow));
|
||||
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
|
||||
|
||||
@@ -40,9 +40,9 @@ internal class SaleBuisnessLogicContractTests
|
||||
var date = DateTime.UtcNow;
|
||||
var listOriginal = new List<SaleDataModel>()
|
||||
{
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, true, false, []),
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, true, false, []),
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, true, false, []),
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, true, false, []),
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, true, false, []),
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, true, false, []),
|
||||
};
|
||||
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Returns(listOriginal);
|
||||
//Act
|
||||
@@ -103,10 +103,10 @@ internal class SaleBuisnessLogicContractTests
|
||||
var workerId = Guid.NewGuid().ToString();
|
||||
var listOriginal = new List<SaleDataModel>()
|
||||
{
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, true, false,
|
||||
[new OrderDishDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]),
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, true, false, []),
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, true, false, []),
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, true, false,
|
||||
[new OrderDishDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 20, 5)]),
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, true, false, []),
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, true, false, []),
|
||||
};
|
||||
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Returns(listOriginal);
|
||||
//Act
|
||||
@@ -184,10 +184,10 @@ internal class SaleBuisnessLogicContractTests
|
||||
var buyerId = Guid.NewGuid().ToString();
|
||||
var listOriginal = new List<SaleDataModel>()
|
||||
{
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, true, false,
|
||||
[new OrderDishDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]),
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, true, false, []),
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, true, false, []),
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, true, false,
|
||||
[new OrderDishDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 20, 5)]),
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, true, false, []),
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, true, false, []),
|
||||
};
|
||||
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Returns(listOriginal);
|
||||
//Act
|
||||
@@ -262,21 +262,21 @@ internal class SaleBuisnessLogicContractTests
|
||||
{
|
||||
//Arrange
|
||||
var date = DateTime.UtcNow;
|
||||
var productId = Guid.NewGuid().ToString();
|
||||
var dishId = Guid.NewGuid().ToString();
|
||||
var listOriginal = new List<SaleDataModel>()
|
||||
{
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, true, false,
|
||||
[new OrderDishDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]),
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, true, false, []),
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, true, false, []),
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, true, false,
|
||||
[new OrderDishDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 20, 5)]),
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, true, false, []),
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, true, false, []),
|
||||
};
|
||||
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Returns(listOriginal);
|
||||
//Act
|
||||
var list = _saleBusinessLogicContract.GetAllSalesByDishByPeriod(productId, date, date.AddDays(1));
|
||||
var list = _saleBusinessLogicContract.GetAllSalesByDishByPeriod(dishId, date, date.AddDays(1));
|
||||
//Assert
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Is.EquivalentTo(listOriginal));
|
||||
_saleStorageContract.Verify(x => x.GetList(date, date.AddDays(1), null, null, productId), Times.Once);
|
||||
_saleStorageContract.Verify(x => x.GetList(date, date.AddDays(1), null, null, dishId), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
@@ -316,7 +316,7 @@ internal class SaleBuisnessLogicContractTests
|
||||
public void GetAllSalesByDishByPeriod_DishIdIsNotGuid_ThrowException_Test()
|
||||
{
|
||||
//Act&Assert
|
||||
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByDishByPeriod("productId", DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<ValidationException>());
|
||||
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByDishByPeriod("dishId", DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<ValidationException>());
|
||||
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
|
||||
}
|
||||
|
||||
@@ -343,8 +343,8 @@ internal class SaleBuisnessLogicContractTests
|
||||
{
|
||||
//Arrange
|
||||
var id = Guid.NewGuid().ToString();
|
||||
var record = new SaleDataModel(id, Guid.NewGuid().ToString(), null, 10, true, false,
|
||||
[new OrderDishDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]);
|
||||
var record = new SaleDataModel(id, Guid.NewGuid().ToString(), null, true, false,
|
||||
[new OrderDishDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 20, 5)]);
|
||||
_saleStorageContract.Setup(x => x.GetElementById(id)).Returns(record);
|
||||
//Act
|
||||
var element = _saleBusinessLogicContract.GetSaleByData(id);
|
||||
@@ -394,8 +394,7 @@ internal class SaleBuisnessLogicContractTests
|
||||
{
|
||||
//Arrange
|
||||
var flag = false;
|
||||
var record = new SaleDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 10, true,
|
||||
false, [new OrderDishDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]);
|
||||
var record = new SaleDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), true, false, [new OrderDishDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 20, 5)]);
|
||||
_saleStorageContract.Setup(x => x.AddElement(It.IsAny<SaleDataModel>()))
|
||||
.Callback((SaleDataModel x) =>
|
||||
{
|
||||
@@ -418,7 +417,7 @@ internal class SaleBuisnessLogicContractTests
|
||||
_saleStorageContract.Setup(x => x.AddElement(It.IsAny<SaleDataModel>())).Throws(new ElementExistsException("Data", "Data"));
|
||||
//Act&Assert
|
||||
Assert.That(() => _saleBusinessLogicContract.InsertSale(new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(),
|
||||
Guid.NewGuid().ToString(), 10, true, false, [new OrderDishDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<ElementExistsException>());
|
||||
Guid.NewGuid().ToString(), true, false, [new OrderDishDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 20, 5)])), Throws.TypeOf<ElementExistsException>());
|
||||
_saleStorageContract.Verify(x => x.AddElement(It.IsAny<SaleDataModel>()), Times.Once);
|
||||
}
|
||||
|
||||
@@ -434,7 +433,7 @@ internal class SaleBuisnessLogicContractTests
|
||||
public void InsertSale_InvalidRecord_ThrowException_Test()
|
||||
{
|
||||
//Act&Assert
|
||||
Assert.That(() => _saleBusinessLogicContract.InsertSale(new SaleDataModel("id", Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 10, true, false, [])), Throws.TypeOf<ValidationException>());
|
||||
Assert.That(() => _saleBusinessLogicContract.InsertSale(new SaleDataModel("id", Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), true, false, [])), Throws.TypeOf<ValidationException>());
|
||||
_saleStorageContract.Verify(x => x.AddElement(It.IsAny<SaleDataModel>()), Times.Never);
|
||||
}
|
||||
|
||||
@@ -445,7 +444,7 @@ internal class SaleBuisnessLogicContractTests
|
||||
_saleStorageContract.Setup(x => x.AddElement(It.IsAny<SaleDataModel>())).Throws(new StorageException(new InvalidOperationException()));
|
||||
//Act&Assert
|
||||
Assert.That(() => _saleBusinessLogicContract.InsertSale(new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(),
|
||||
Guid.NewGuid().ToString(), 10, true, false, [new OrderDishDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<StorageException>());
|
||||
Guid.NewGuid().ToString(), true, false, [new OrderDishDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 20, 5)])), Throws.TypeOf<StorageException>());
|
||||
_saleStorageContract.Verify(x => x.AddElement(It.IsAny<SaleDataModel>()), Times.Once);
|
||||
}
|
||||
|
||||
|
||||
@@ -15,41 +15,41 @@ internal class OrderDataModelTests
|
||||
[Test]
|
||||
public void OrderIdIsNullOrEmptyTest()
|
||||
{
|
||||
var orderDish = CreateDataModel(null, Guid.NewGuid().ToString(), 10);
|
||||
var orderDish = CreateDataModel(null, Guid.NewGuid().ToString(), 10, 20);
|
||||
Assert.That(() => orderDish.Validate(), Throws.TypeOf<ValidationException>());
|
||||
orderDish = CreateDataModel(string.Empty, Guid.NewGuid().ToString(), 10);
|
||||
orderDish = CreateDataModel(string.Empty, Guid.NewGuid().ToString(), 10, 20);
|
||||
Assert.That(() => orderDish.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void OrderIdIsNotGuidTest()
|
||||
{
|
||||
var orderDish = CreateDataModel("saleId", Guid.NewGuid().ToString(), 10);
|
||||
var orderDish = CreateDataModel("saleId", Guid.NewGuid().ToString(), 10, 20);
|
||||
Assert.That(() => orderDish.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void DishIdIsNullOrEmptyTest()
|
||||
{
|
||||
var orderDish = CreateDataModel(Guid.NewGuid().ToString(), null, 10);
|
||||
var orderDish = CreateDataModel(Guid.NewGuid().ToString(), null, 10, 20);
|
||||
Assert.That(() => orderDish.Validate(), Throws.TypeOf<ValidationException>());
|
||||
orderDish = CreateDataModel(string.Empty, Guid.NewGuid().ToString(), 10);
|
||||
orderDish = CreateDataModel(string.Empty, Guid.NewGuid().ToString(), 10, 20);
|
||||
Assert.That(() => orderDish.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void DishIdIsNotGuidTest()
|
||||
{
|
||||
var orderDish = CreateDataModel(Guid.NewGuid().ToString(), "dishId", 10);
|
||||
var orderDish = CreateDataModel(Guid.NewGuid().ToString(), "dishId", 10, 20);
|
||||
Assert.That(() => orderDish.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void CountIsLessOrZeroTest()
|
||||
{
|
||||
var orderDish = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 0);
|
||||
var orderDish = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 0, 20);
|
||||
Assert.That(() => orderDish.Validate(), Throws.TypeOf<ValidationException>());
|
||||
orderDish = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), -10);
|
||||
orderDish = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), -10, 20);
|
||||
Assert.That(() => orderDish.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
@@ -59,7 +59,8 @@ internal class OrderDataModelTests
|
||||
var orderId = Guid.NewGuid().ToString();
|
||||
var dishId = Guid.NewGuid().ToString();
|
||||
var count = 10;
|
||||
var orderDish = CreateDataModel(orderId, dishId, count);
|
||||
var price = 20;
|
||||
var orderDish = CreateDataModel(orderId, dishId, count, price);
|
||||
Assert.That(() => orderDish.Validate(), Throws.Nothing);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
@@ -69,6 +70,6 @@ internal class OrderDataModelTests
|
||||
});
|
||||
}
|
||||
|
||||
private static OrderDishDataModel CreateDataModel(string? orderId, string? dishId, int count) => new(orderId, dishId, count);
|
||||
private static OrderDishDataModel CreateDataModel(string? orderId, string? dishId, int count, int price) => new(orderId, dishId, count, price);
|
||||
|
||||
}
|
||||
|
||||
@@ -61,7 +61,7 @@ internal class SaleDataModelTests
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ProductsIsNullOrEmptyTest()
|
||||
public void DishesIsNullOrEmptyTest()
|
||||
{
|
||||
var sale = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 10, true, false, null);
|
||||
Assert.That(() => sale.Validate(), Throws.TypeOf<ValidationException>());
|
||||
@@ -75,7 +75,7 @@ internal class SaleDataModelTests
|
||||
var saleId = Guid.NewGuid().ToString();
|
||||
var workerId = Guid.NewGuid().ToString();
|
||||
var buyerId = Guid.NewGuid().ToString();
|
||||
var sum = 10;
|
||||
var sum = 20;
|
||||
var isConstantClient = true;
|
||||
var isCancel = true;
|
||||
var dishes = CreateSubDataModel();
|
||||
@@ -93,7 +93,7 @@ internal class SaleDataModelTests
|
||||
});
|
||||
}
|
||||
|
||||
private static SaleDataModel CreateDataModel(string? id, string? workerId, string? buyerId, double sum, bool IsConstantClient, bool isCancel, List<OrderDishDataModel>? dishes) => new(id, workerId, buyerId, sum, IsConstantClient, isCancel, dishes);
|
||||
private static List<OrderDishDataModel> CreateSubDataModel() => [new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 1)];
|
||||
private static SaleDataModel CreateDataModel(string? id, string? workerId, string? buyerId, double sum, bool IsConstantClient, bool isCancel, List<OrderDishDataModel>? dishes) => new(id, workerId, buyerId, sum, IsConstantClient, isCancel, dishes, null, null);
|
||||
private static List<OrderDishDataModel> CreateSubDataModel() => [new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 1, 20)];
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
using AndDietCokeContracts.Enums;
|
||||
using AndDietCokeDatabase;
|
||||
using AndDietCokeDatabase.Models;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using static NUnit.Framework.Internal.OSPlatform;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace AndDietCokeTests.Infrastructure;
|
||||
|
||||
internal static class AndDietCokeDbContextExtensions
|
||||
{
|
||||
public static Buyer InsertBuyerToDatabaseAndReturn(this AndDietCokeDbContext 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 Post InsertPostToDatabaseAndReturn(this AndDietCokeDbContext dbContext, string? id = null, string postName = "test", PostType postType = PostType.Packer, double salary = 10, bool isActual = true, DateTime? changeDate = null)
|
||||
{
|
||||
var post = new Post() { Id = id ?? Guid.NewGuid().ToString(), PostId = Guid.NewGuid().ToString(), PostName = postName, PostType = postType, Salary = salary, IsActual = isActual, ChangeDate = changeDate ?? DateTime.UtcNow };
|
||||
dbContext.Posts.Add(post);
|
||||
dbContext.SaveChanges();
|
||||
return post;
|
||||
}
|
||||
|
||||
public static Dish InsertDishToDatabaseAndReturn(this AndDietCokeDbContext dbContext, string? id = null, string dishName = "test", DishType dishType = DishType.Drink, double price = 1, bool isDeleted = false)
|
||||
{
|
||||
var dish = new Dish() { Id = id ?? Guid.NewGuid().ToString(), DishName = dishName, DishType = dishType, Price = price, IsDeleted = isDeleted };
|
||||
dbContext.Dishes.Add(dish);
|
||||
dbContext.SaveChanges();
|
||||
return dish;
|
||||
}
|
||||
|
||||
public static DishHistory InsertDishHistoryToDatabaseAndReturn(this AndDietCokeDbContext dbContext, string dishId, double price = 10, DateTime? changeDate = null)
|
||||
{
|
||||
var dishHistory = new DishHistory() { Id = Guid.NewGuid().ToString(), DishId = dishId, OldPrice = price, ChangeDate = changeDate ?? DateTime.UtcNow };
|
||||
dbContext.DishHistories.Add(dishHistory);
|
||||
dbContext.SaveChanges();
|
||||
return dishHistory;
|
||||
}
|
||||
|
||||
public static Salary InsertSalaryToDatabaseAndReturn(this AndDietCokeDbContext dbContext, string workerId, double workerSalary = 1, DateTime? salaryDate = null)
|
||||
{
|
||||
dbContext.ChangeTracker.Clear();
|
||||
|
||||
var salary = new Salary() { WorkerId = workerId, WorkerSalary = workerSalary, SalaryDate = salaryDate ?? DateTime.UtcNow };
|
||||
dbContext.Salaries.Add(salary);
|
||||
dbContext.SaveChanges();
|
||||
return salary;
|
||||
}
|
||||
|
||||
public static Sale InsertSaleToDatabaseAndReturn(this AndDietCokeDbContext dbContext, string workerId, string? buyerId = null, DateTime? saleDate = null, double sum = 1, bool isConstantClient = false, bool isCancel = false, List<(string, int, double)>? dishes = null)
|
||||
{
|
||||
var sale = new Sale() { WorkerId = workerId, BuyerId = buyerId, SaleDate = saleDate ?? DateTime.UtcNow, Sum = sum, IsConstantClient = isConstantClient, IsCancel = isCancel, OrderDishes = [] };
|
||||
if (dishes is not null)
|
||||
{
|
||||
foreach (var elem in dishes)
|
||||
{
|
||||
sale.OrderDishes.Add(new OrderDish { DishId = elem.Item1, OrderId = sale.Id, Count = elem.Item2 });
|
||||
}
|
||||
}
|
||||
dbContext.Sales.Add(sale);
|
||||
dbContext.SaveChanges();
|
||||
return sale;
|
||||
}
|
||||
|
||||
public static Worker InsertWorkerToDatabaseAndReturn(this AndDietCokeDbContext dbContext, string? id = null, string fio = "test", string? postId = null, DateTime? birthDate = null, DateTime? employmentDate = null, bool isDeleted = false)
|
||||
{
|
||||
var worker = new Worker() { Id = id ?? Guid.NewGuid().ToString(), FIO = fio, PostId = postId ?? Guid.NewGuid().ToString(), BirthDate = birthDate ?? DateTime.UtcNow.AddYears(-20), EmploymentDate = employmentDate ?? DateTime.UtcNow, IsDeleted = isDeleted };
|
||||
dbContext.Workers.Add(worker);
|
||||
dbContext.SaveChanges();
|
||||
return worker;
|
||||
}
|
||||
|
||||
public static Buyer? GetBuyerFromDatabase(this AndDietCokeDbContext dbContext, string id) => dbContext.Buyers.FirstOrDefault(x => x.Id == id);
|
||||
|
||||
public static Post? GetPostFromDatabaseByPostId(this AndDietCokeDbContext dbContext, string id) => dbContext.Posts.FirstOrDefault(x => x.PostId == id && x.IsActual);
|
||||
|
||||
public static Post[] GetPostsFromDatabaseByPostId(this AndDietCokeDbContext dbContext, string id) => [.. dbContext.Posts.Where(x => x.PostId == id).OrderByDescending(x => x.ChangeDate)];
|
||||
|
||||
public static Dish? GetDishFromDatabaseById(this AndDietCokeDbContext dbContext, string id) => dbContext.Dishes.FirstOrDefault(x => x.Id == id);
|
||||
|
||||
public static Salary[] GetSalariesFromDatabaseByWorkerId(this AndDietCokeDbContext dbContext, string id) => [.. dbContext.Salaries.Where(x => x.WorkerId == id)];
|
||||
|
||||
public static Sale? GetSaleFromDatabaseById(this AndDietCokeDbContext dbContext, string id) => dbContext.Sales.Include(x => x.OrderDishes).FirstOrDefault(x => x.Id == id);
|
||||
|
||||
public static Sale[] GetSalesByBuyerId(this AndDietCokeDbContext dbContext, string? buyerId) => [.. dbContext.Sales.Include(x => x.OrderDishes).Where(x => x.BuyerId == buyerId)];
|
||||
|
||||
public static Worker? GetWorkerFromDatabaseById(this AndDietCokeDbContext dbContext, string id) => dbContext.Workers.FirstOrDefault(x => x.Id == id);
|
||||
|
||||
public static void RemoveBuyersFromDatabase(this AndDietCokeDbContext dbContext) => dbContext.ExecuteSqlRaw("TRUNCATE \"Buyers\" CASCADE;");
|
||||
|
||||
public static void RemovePostsFromDatabase(this AndDietCokeDbContext dbContext) => dbContext.ExecuteSqlRaw("TRUNCATE \"Posts\" CASCADE;");
|
||||
|
||||
public static void RemoveDishesFromDatabase(this AndDietCokeDbContext dbContext) => dbContext.ExecuteSqlRaw("TRUNCATE \"Dishes\" CASCADE;");
|
||||
|
||||
public static void RemoveSalariesFromDatabase(this AndDietCokeDbContext dbContext) => dbContext.ExecuteSqlRaw("TRUNCATE \"Salaries\" CASCADE;");
|
||||
|
||||
public static void RemoveSalesFromDatabase(this AndDietCokeDbContext dbContext) => dbContext.ExecuteSqlRaw("TRUNCATE \"Sales\" CASCADE;");
|
||||
|
||||
public static void RemoveWorkersFromDatabase(this AndDietCokeDbContext dbContext) => dbContext.ExecuteSqlRaw("TRUNCATE \"Workers\" CASCADE;");
|
||||
|
||||
private static void ExecuteSqlRaw(this AndDietCokeDbContext dbContext, string command) => dbContext.Database.ExecuteSqlRaw(command);
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
using AndDietCokeContracts.Infrastrusture;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.AspNetCore.Mvc.Testing;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace AndDietCokeTests.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);
|
||||
}
|
||||
}
|
||||
@@ -2,17 +2,14 @@
|
||||
using AndDietCokeContracts.Exceptions;
|
||||
using AndDietCokeContracts.StoragesContracts;
|
||||
using NUnit.Framework;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using AndDietCokeDatabase.Implementations;
|
||||
using AndDietCokeDatabase.Models;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using AndDietCokeTests.Infrastructure;
|
||||
|
||||
namespace AndDietCokeTests.StoragesContracts;
|
||||
|
||||
|
||||
[TestFixture]
|
||||
internal class BuyerStorageContractTests : BaseStorageContractTest
|
||||
{
|
||||
@@ -27,17 +24,17 @@ internal class BuyerStorageContractTests : BaseStorageContractTest
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
AndDietCokeDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Sales\" CASCADE;");
|
||||
AndDietCokeDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Workers\" CASCADE;");
|
||||
AndDietCokeDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Buyers\" CASCADE;");
|
||||
AndDietCokeDbContext.RemoveSalesFromDatabase();
|
||||
AndDietCokeDbContext.RemoveWorkersFromDatabase();
|
||||
AndDietCokeDbContext.RemoveBuyersFromDatabase();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_WhenHaveRecords_Test()
|
||||
{
|
||||
var buyer = InsertBuyerToDatabaseAndReturn(Guid.NewGuid().ToString(), "FIO", "+5-555-555-55-55", 10);
|
||||
InsertBuyerToDatabaseAndReturn(Guid.NewGuid().ToString(), "FIO", "+6-666-666-66-66", 10);
|
||||
InsertBuyerToDatabaseAndReturn(Guid.NewGuid().ToString(), "FIO", "+7-777-777-77-77", 10);
|
||||
var buyer = AndDietCokeDbContext.InsertBuyerToDatabaseAndReturn(phoneNumber: "+5-555-555-55-55");
|
||||
AndDietCokeDbContext.InsertBuyerToDatabaseAndReturn(phoneNumber: "+6-666-666-66-66");
|
||||
AndDietCokeDbContext.InsertBuyerToDatabaseAndReturn(phoneNumber: "+7-777-777-77-77");
|
||||
var list = _buyerStorageContract.GetList();
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(3));
|
||||
@@ -55,42 +52,42 @@ internal class BuyerStorageContractTests : BaseStorageContractTest
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenHaveRecord_Test()
|
||||
{
|
||||
var buyer = InsertBuyerToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
var buyer = AndDietCokeDbContext.InsertBuyerToDatabaseAndReturn();
|
||||
AssertElement(_buyerStorageContract.GetElementById(buyer.Id), buyer);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenNoRecord_Test()
|
||||
{
|
||||
InsertBuyerToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
AndDietCokeDbContext.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 = AndDietCokeDbContext.InsertBuyerToDatabaseAndReturn();
|
||||
AssertElement(_buyerStorageContract.GetElementByFIO(buyer.FIO), buyer);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementByFIO_WhenNoRecord_Test()
|
||||
{
|
||||
InsertBuyerToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
AndDietCokeDbContext.InsertBuyerToDatabaseAndReturn();
|
||||
Assert.That(() => _buyerStorageContract.GetElementByFIO("New Fio"), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementByPhoneNumber_WhenHaveRecord_Test()
|
||||
{
|
||||
var buyer = InsertBuyerToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
var buyer = AndDietCokeDbContext.InsertBuyerToDatabaseAndReturn();
|
||||
AssertElement(_buyerStorageContract.GetElementByPhoneNumber(buyer.PhoneNumber), buyer);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementByPhoneNumber_WhenNoRecord_Test()
|
||||
{
|
||||
InsertBuyerToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
AndDietCokeDbContext.InsertBuyerToDatabaseAndReturn();
|
||||
Assert.That(() => _buyerStorageContract.GetElementByPhoneNumber("+8-888-888-88-88"), Is.Null);
|
||||
}
|
||||
|
||||
@@ -99,14 +96,14 @@ internal class BuyerStorageContractTests : BaseStorageContractTest
|
||||
{
|
||||
var buyer = CreateModel(Guid.NewGuid().ToString());
|
||||
_buyerStorageContract.AddElement(buyer);
|
||||
AssertElement(GetBuyerFromDatabase(buyer.Id), buyer);
|
||||
AssertElement(AndDietCokeDbContext.GetBuyerFromDatabase(buyer.Id), buyer);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_WhenHaveRecordWithSameId_Test()
|
||||
{
|
||||
var buyer = CreateModel(Guid.NewGuid().ToString(), "New Fio", "+5-555-555-55-55");
|
||||
InsertBuyerToDatabaseAndReturn(buyer.Id);
|
||||
AndDietCokeDbContext.InsertBuyerToDatabaseAndReturn(buyer.Id);
|
||||
Assert.That(() => _buyerStorageContract.AddElement(buyer), Throws.TypeOf<ElementExistsException>());
|
||||
}
|
||||
|
||||
@@ -114,7 +111,7 @@ internal class BuyerStorageContractTests : BaseStorageContractTest
|
||||
public void Try_AddElement_WhenHaveRecordWithSamePhoneNumber_Test()
|
||||
{
|
||||
var buyer = CreateModel(Guid.NewGuid().ToString(), "New Fio", "+5-555-555-55-55");
|
||||
InsertBuyerToDatabaseAndReturn(Guid.NewGuid().ToString(), phoneNumber: buyer.PhoneNumber);
|
||||
AndDietCokeDbContext.InsertBuyerToDatabaseAndReturn(phoneNumber: buyer.PhoneNumber);
|
||||
Assert.That(() => _buyerStorageContract.AddElement(buyer), Throws.TypeOf<ElementExistsException>());
|
||||
}
|
||||
|
||||
@@ -122,9 +119,9 @@ internal class BuyerStorageContractTests : BaseStorageContractTest
|
||||
public void Try_UpdElement_Test()
|
||||
{
|
||||
var buyer = CreateModel(Guid.NewGuid().ToString(), "New Fio", "+5-555-555-55-55");
|
||||
InsertBuyerToDatabaseAndReturn(buyer.Id);
|
||||
AndDietCokeDbContext.InsertBuyerToDatabaseAndReturn(buyer.Id);
|
||||
_buyerStorageContract.UpdElement(buyer);
|
||||
AssertElement(GetBuyerFromDatabase(buyer.Id), buyer);
|
||||
AssertElement(AndDietCokeDbContext.GetBuyerFromDatabase(buyer.Id), buyer);
|
||||
}
|
||||
|
||||
[Test]
|
||||
@@ -137,39 +134,37 @@ internal class BuyerStorageContractTests : BaseStorageContractTest
|
||||
public void Try_UpdElement_WhenHaveRecordWithSamePhoneNumber_Test()
|
||||
{
|
||||
var buyer = CreateModel(Guid.NewGuid().ToString(), "New Fio", "+5-555-555-55-55");
|
||||
InsertBuyerToDatabaseAndReturn(buyer.Id, phoneNumber: "+7-777-777-77-77");
|
||||
InsertBuyerToDatabaseAndReturn(Guid.NewGuid().ToString(), phoneNumber: buyer.PhoneNumber);
|
||||
AndDietCokeDbContext.InsertBuyerToDatabaseAndReturn(buyer.Id, phoneNumber: "+7-777-777-77-77");
|
||||
AndDietCokeDbContext.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 = AndDietCokeDbContext.InsertBuyerToDatabaseAndReturn();
|
||||
_buyerStorageContract.DelElement(buyer.Id);
|
||||
var element = GetBuyerFromDatabase(buyer.Id);
|
||||
Assert.That(element, Is.Null);
|
||||
Assert.That(AndDietCokeDbContext.GetBuyerFromDatabase(buyer.Id), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_DelElement_WhenHaveSalesByThisBuyer_Test()
|
||||
{
|
||||
var buyer = InsertBuyerToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
var workerId = Guid.NewGuid().ToString();
|
||||
AndDietCokeDbContext.Workers.Add(new Worker() { Id = workerId, FIO = "test", PostId = Guid.NewGuid().ToString() });
|
||||
AndDietCokeDbContext.Sales.Add(new Sale() { Id = Guid.NewGuid().ToString(), WorkerId = workerId, BuyerId = buyer.Id, Sum = 10, IsConstantClient = true });
|
||||
AndDietCokeDbContext.Sales.Add(new Sale() { Id = Guid.NewGuid().ToString(), WorkerId = workerId, BuyerId = buyer.Id, Sum = 10, IsConstantClient = true });
|
||||
AndDietCokeDbContext.SaveChanges();
|
||||
var salesBeforeDelete = AndDietCokeDbContext.Sales.Where(x => x.BuyerId == buyer.Id).ToArray();
|
||||
var buyer = AndDietCokeDbContext.InsertBuyerToDatabaseAndReturn();
|
||||
var worker = AndDietCokeDbContext.InsertWorkerToDatabaseAndReturn();
|
||||
AndDietCokeDbContext.InsertSaleToDatabaseAndReturn(worker.Id, buyer.Id);
|
||||
AndDietCokeDbContext.InsertSaleToDatabaseAndReturn(worker.Id, buyer.Id);
|
||||
var salesBeforeDelete = AndDietCokeDbContext.GetSalesByBuyerId(buyer.Id);
|
||||
_buyerStorageContract.DelElement(buyer.Id);
|
||||
var element = GetBuyerFromDatabase(buyer.Id);
|
||||
var salesAfterDelete = AndDietCokeDbContext.Sales.Where(x => x.BuyerId == buyer.Id).ToArray();
|
||||
var element = AndDietCokeDbContext.GetBuyerFromDatabase(buyer.Id);
|
||||
var salesAfterDelete = AndDietCokeDbContext.GetSalesByBuyerId(buyer.Id);
|
||||
var salesNoBuyers = AndDietCokeDbContext.GetSalesByBuyerId(null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(element, Is.Null);
|
||||
Assert.That(salesBeforeDelete, Has.Length.EqualTo(2));
|
||||
Assert.That(salesAfterDelete, Is.Empty);
|
||||
Assert.That(AndDietCokeDbContext.Sales.Count(), Is.EqualTo(2));
|
||||
Assert.That(salesNoBuyers, Has.Length.EqualTo(2));
|
||||
});
|
||||
}
|
||||
|
||||
@@ -179,14 +174,6 @@ internal class BuyerStorageContractTests : BaseStorageContractTest
|
||||
Assert.That(() => _buyerStorageContract.DelElement(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
|
||||
}
|
||||
|
||||
private Buyer InsertBuyerToDatabaseAndReturn(string id, string fio = "test", string phoneNumber = "+7-777-777-77-77", double discountSize = 10)
|
||||
{
|
||||
var buyer = new Buyer() { Id = id, FIO = fio, PhoneNumber = phoneNumber, DiscountSize = discountSize };
|
||||
AndDietCokeDbContext.Buyers.Add(buyer);
|
||||
AndDietCokeDbContext.SaveChanges();
|
||||
return buyer;
|
||||
}
|
||||
|
||||
private static void AssertElement(BuyerDataModel? actual, Buyer expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
@@ -198,9 +185,8 @@ internal class BuyerStorageContractTests : BaseStorageContractTest
|
||||
});
|
||||
}
|
||||
|
||||
private static BuyerDataModel CreateModel(string id, string fio = "test", string phoneNumber = "+7-777-777-77-77") => new(id, fio, phoneNumber);
|
||||
|
||||
private Buyer? GetBuyerFromDatabase(string id) => AndDietCokeDbContext.Buyers.FirstOrDefault(x => x.Id == id);
|
||||
private static BuyerDataModel CreateModel(string id, string fio = "test", string phoneNumber = "+7-777-777-77-77")
|
||||
=> new(id, fio, phoneNumber);
|
||||
|
||||
private static void AssertElement(Buyer? actual, BuyerDataModel expected)
|
||||
{
|
||||
@@ -212,4 +198,4 @@ internal class BuyerStorageContractTests : BaseStorageContractTest
|
||||
Assert.That(actual.PhoneNumber, Is.EqualTo(expected.PhoneNumber));
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,7 @@ using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using static NUnit.Framework.Internal.OSPlatform;
|
||||
using AndDietCokeTests.Infrastructure;
|
||||
|
||||
namespace AndDietCokeTests.StoragesContracts;
|
||||
|
||||
@@ -28,15 +29,15 @@ internal class DishStorageContractTests : BaseStorageContractTest
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
AndDietCokeDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Dishes\" CASCADE;");
|
||||
AndDietCokeDbContext.RemoveDishesFromDatabase();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_WhenHaveRecords_Test()
|
||||
{
|
||||
var dish = InsertDishToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 1");
|
||||
InsertDishToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 2");
|
||||
InsertDishToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 3");
|
||||
var dish = AndDietCokeDbContext.InsertDishToDatabaseAndReturn(dishName: "name 1");
|
||||
AndDietCokeDbContext.InsertDishToDatabaseAndReturn(dishName: "name 2");
|
||||
AndDietCokeDbContext.InsertDishToDatabaseAndReturn(dishName: "name 3");
|
||||
var list = _dishStorageContract.GetList();
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(3));
|
||||
@@ -54,9 +55,9 @@ internal class DishStorageContractTests : BaseStorageContractTest
|
||||
[Test]
|
||||
public void Try_GetList_OnlyActual_Test()
|
||||
{
|
||||
InsertDishToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 1", isDeleted: true);
|
||||
InsertDishToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 2", isDeleted: false);
|
||||
InsertDishToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 3", isDeleted: false);
|
||||
AndDietCokeDbContext.InsertDishToDatabaseAndReturn(dishName: "name 1", isDeleted: true);
|
||||
AndDietCokeDbContext.InsertDishToDatabaseAndReturn(dishName: "name 2", isDeleted: false);
|
||||
AndDietCokeDbContext.InsertDishToDatabaseAndReturn(dishName: "name 3", isDeleted: false);
|
||||
var list = _dishStorageContract.GetList(onlyActive: true);
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
@@ -69,9 +70,9 @@ internal class DishStorageContractTests : BaseStorageContractTest
|
||||
[Test]
|
||||
public void Try_GetList_IncludeNoActual_Test()
|
||||
{
|
||||
InsertDishToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 1", isDeleted: true);
|
||||
InsertDishToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 2", isDeleted: true);
|
||||
InsertDishToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 3", isDeleted: false);
|
||||
AndDietCokeDbContext.InsertDishToDatabaseAndReturn(dishName: "name 1", isDeleted: true);
|
||||
AndDietCokeDbContext.InsertDishToDatabaseAndReturn(dishName: "name 2", isDeleted: true);
|
||||
AndDietCokeDbContext.InsertDishToDatabaseAndReturn(dishName: "name 3", isDeleted: false);
|
||||
var list = _dishStorageContract.GetList(onlyActive: false);
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
@@ -85,10 +86,10 @@ internal class DishStorageContractTests : BaseStorageContractTest
|
||||
[Test]
|
||||
public void Try_GetHistoryByDishId_WhenHaveRecords_Test()
|
||||
{
|
||||
var dish = InsertDishToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 1");
|
||||
InsertDishHistoryToDatabaseAndReturn(dish.Id, 20, DateTime.UtcNow.AddDays(-1));
|
||||
InsertDishHistoryToDatabaseAndReturn(dish.Id, 30, DateTime.UtcNow.AddMinutes(-10));
|
||||
InsertDishHistoryToDatabaseAndReturn(dish.Id, 40, DateTime.UtcNow.AddDays(1));
|
||||
var dish = AndDietCokeDbContext.InsertDishToDatabaseAndReturn();
|
||||
AndDietCokeDbContext.InsertDishHistoryToDatabaseAndReturn(dish.Id, 20, DateTime.UtcNow.AddDays(-1));
|
||||
AndDietCokeDbContext.InsertDishHistoryToDatabaseAndReturn(dish.Id, 30, DateTime.UtcNow.AddMinutes(-10));
|
||||
AndDietCokeDbContext.InsertDishHistoryToDatabaseAndReturn(dish.Id, 40, DateTime.UtcNow.AddDays(1));
|
||||
var list = _dishStorageContract.GetHistoryByDishId(dish.Id);
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(3));
|
||||
@@ -97,10 +98,10 @@ internal class DishStorageContractTests : BaseStorageContractTest
|
||||
[Test]
|
||||
public void Try_GetHistoryByDishId_WhenNoRecords_Test()
|
||||
{
|
||||
var dish = InsertDishToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 1");
|
||||
InsertDishHistoryToDatabaseAndReturn(dish.Id, 20, DateTime.UtcNow.AddDays(-1));
|
||||
InsertDishHistoryToDatabaseAndReturn(dish.Id, 30, DateTime.UtcNow.AddMinutes(-10));
|
||||
InsertDishHistoryToDatabaseAndReturn(dish.Id, 40, DateTime.UtcNow.AddDays(1));
|
||||
var dish = AndDietCokeDbContext.InsertDishToDatabaseAndReturn();
|
||||
AndDietCokeDbContext.InsertDishHistoryToDatabaseAndReturn(dish.Id, 20, DateTime.UtcNow.AddDays(-1));
|
||||
AndDietCokeDbContext.InsertDishHistoryToDatabaseAndReturn(dish.Id, 30, DateTime.UtcNow.AddMinutes(-10));
|
||||
AndDietCokeDbContext.InsertDishHistoryToDatabaseAndReturn(dish.Id, 40, DateTime.UtcNow.AddDays(1));
|
||||
var list = _dishStorageContract.GetHistoryByDishId(Guid.NewGuid().ToString());
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(0));
|
||||
@@ -109,42 +110,42 @@ internal class DishStorageContractTests : BaseStorageContractTest
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenHaveRecord_Test()
|
||||
{
|
||||
var dish = InsertDishToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
var dish = AndDietCokeDbContext.InsertDishToDatabaseAndReturn();
|
||||
AssertElement(_dishStorageContract.GetElementById(dish.Id), dish);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenNoRecord_Test()
|
||||
{
|
||||
InsertDishToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
AndDietCokeDbContext.InsertDishToDatabaseAndReturn();
|
||||
Assert.That(() => _dishStorageContract.GetElementById(Guid.NewGuid().ToString()), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenRecordHasDeleted_Test()
|
||||
public void Try_GetElementById_WhenRecordWasDeleted_Test()
|
||||
{
|
||||
var dish = InsertDishToDatabaseAndReturn(Guid.NewGuid().ToString(), isDeleted: true);
|
||||
var dish = AndDietCokeDbContext.InsertDishToDatabaseAndReturn(isDeleted: true);
|
||||
Assert.That(() => _dishStorageContract.GetElementById(dish.Id), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementByName_WhenHaveRecord_Test()
|
||||
{
|
||||
var dish = InsertDishToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
var dish = AndDietCokeDbContext.InsertDishToDatabaseAndReturn();
|
||||
AssertElement(_dishStorageContract.GetElementByName(dish.DishName), dish);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementByName_WhenNoRecord_Test()
|
||||
{
|
||||
InsertDishToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
AndDietCokeDbContext.InsertDishToDatabaseAndReturn();
|
||||
Assert.That(() => _dishStorageContract.GetElementByName("name"), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementByName_WhenRecordHasDeleted_Test()
|
||||
public void Try_GetElementByName_WhenRecordWasDeleted_Test()
|
||||
{
|
||||
var dish = InsertDishToDatabaseAndReturn(Guid.NewGuid().ToString(), isDeleted: true);
|
||||
var dish = AndDietCokeDbContext.InsertDishToDatabaseAndReturn(isDeleted: true);
|
||||
Assert.That(() => _dishStorageContract.GetElementById(dish.DishName), Is.Null);
|
||||
}
|
||||
|
||||
@@ -153,7 +154,7 @@ internal class DishStorageContractTests : BaseStorageContractTest
|
||||
{
|
||||
var dish = CreateModel(Guid.NewGuid().ToString(), isDeleted: false);
|
||||
_dishStorageContract.AddElement(dish);
|
||||
AssertElement(GetDishFromDatabaseById(dish.Id), dish);
|
||||
AssertElement(AndDietCokeDbContext.GetDishFromDatabaseById(dish.Id), dish);
|
||||
}
|
||||
|
||||
[Test]
|
||||
@@ -161,14 +162,14 @@ internal class DishStorageContractTests : BaseStorageContractTest
|
||||
{
|
||||
var dish = CreateModel(Guid.NewGuid().ToString(), isDeleted: true);
|
||||
Assert.That(() => _dishStorageContract.AddElement(dish), Throws.Nothing);
|
||||
AssertElement(GetDishFromDatabaseById(dish.Id), CreateModel(dish.Id, isDeleted: false));
|
||||
AssertElement(AndDietCokeDbContext.GetDishFromDatabaseById(dish.Id), CreateModel(dish.Id, isDeleted: false));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_WhenHaveRecordWithSameId_Test()
|
||||
{
|
||||
var dish = CreateModel(Guid.NewGuid().ToString());
|
||||
InsertDishToDatabaseAndReturn(dish.Id, dishName: "name unique");
|
||||
AndDietCokeDbContext.InsertDishToDatabaseAndReturn(dish.Id, dishName: "name unique");
|
||||
Assert.That(() => _dishStorageContract.AddElement(dish), Throws.TypeOf<ElementExistsException>());
|
||||
}
|
||||
|
||||
@@ -176,7 +177,7 @@ internal class DishStorageContractTests : BaseStorageContractTest
|
||||
public void Try_AddElement_WhenHaveRecordWithSameName_Test()
|
||||
{
|
||||
var dish = CreateModel(Guid.NewGuid().ToString(), "name unique", isDeleted: false);
|
||||
InsertDishToDatabaseAndReturn(Guid.NewGuid().ToString(), dishName: dish.DishName, isDeleted: false);
|
||||
AndDietCokeDbContext.InsertDishToDatabaseAndReturn(dishName: dish.DishName, isDeleted: false);
|
||||
Assert.That(() => _dishStorageContract.AddElement(dish), Throws.TypeOf<ElementExistsException>());
|
||||
}
|
||||
|
||||
@@ -184,7 +185,7 @@ internal class DishStorageContractTests : BaseStorageContractTest
|
||||
public void Try_AddElement_WhenHaveRecordWithSameNameButOneWasDeleted_Test()
|
||||
{
|
||||
var dish = CreateModel(Guid.NewGuid().ToString(), "name unique", isDeleted: false);
|
||||
InsertDishToDatabaseAndReturn(Guid.NewGuid().ToString(), dishName: dish.DishName, isDeleted: true);
|
||||
AndDietCokeDbContext.InsertDishToDatabaseAndReturn(dishName: dish.DishName, isDeleted: true);
|
||||
Assert.That(() => _dishStorageContract.AddElement(dish), Throws.Nothing);
|
||||
}
|
||||
|
||||
@@ -192,18 +193,18 @@ internal class DishStorageContractTests : BaseStorageContractTest
|
||||
public void Try_UpdElement_Test()
|
||||
{
|
||||
var dish = CreateModel(Guid.NewGuid().ToString(), isDeleted: false);
|
||||
InsertDishToDatabaseAndReturn(dish.Id, isDeleted: false);
|
||||
AndDietCokeDbContext.InsertDishToDatabaseAndReturn(id: dish.Id, isDeleted: false);
|
||||
_dishStorageContract.UpdElement(dish);
|
||||
AssertElement(GetDishFromDatabaseById(dish.Id), dish);
|
||||
AssertElement(AndDietCokeDbContext.GetDishFromDatabaseById(dish.Id), dish);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_UpdElement_WhenIsDeletedIsTrue_Test()
|
||||
{
|
||||
var dish = CreateModel(Guid.NewGuid().ToString(), isDeleted: true);
|
||||
InsertDishToDatabaseAndReturn(dish.Id, isDeleted: false);
|
||||
AndDietCokeDbContext.InsertDishToDatabaseAndReturn(dish.Id, isDeleted: false);
|
||||
_dishStorageContract.UpdElement(dish);
|
||||
AssertElement(GetDishFromDatabaseById(dish.Id), CreateModel(dish.Id, isDeleted: false));
|
||||
AssertElement(AndDietCokeDbContext.GetDishFromDatabaseById(dish.Id), CreateModel(dish.Id, isDeleted: false));
|
||||
}
|
||||
|
||||
[Test]
|
||||
@@ -216,8 +217,8 @@ internal class DishStorageContractTests : BaseStorageContractTest
|
||||
public void Try_UpdElement_WhenHaveRecordWithSameName_Test()
|
||||
{
|
||||
var dish = CreateModel(Guid.NewGuid().ToString(), "name unique", isDeleted: false);
|
||||
InsertDishToDatabaseAndReturn(dish.Id, dishName: "name");
|
||||
InsertDishToDatabaseAndReturn(Guid.NewGuid().ToString(), dishName: dish.DishName);
|
||||
AndDietCokeDbContext.InsertDishToDatabaseAndReturn(dish.Id, dishName: "name");
|
||||
AndDietCokeDbContext.InsertDishToDatabaseAndReturn(dishName: dish.DishName);
|
||||
Assert.That(() => _dishStorageContract.UpdElement(dish), Throws.TypeOf<ElementExistsException>());
|
||||
}
|
||||
|
||||
@@ -225,8 +226,8 @@ internal class DishStorageContractTests : BaseStorageContractTest
|
||||
public void Try_UpdElement_WhenHaveRecordWithSameNameButOneWasDeleted_Test()
|
||||
{
|
||||
var dish = CreateModel(Guid.NewGuid().ToString(), "name unique", isDeleted: false);
|
||||
InsertDishToDatabaseAndReturn(dish.Id, dishName: "name");
|
||||
InsertDishToDatabaseAndReturn(Guid.NewGuid().ToString(), dishName: dish.DishName, isDeleted: true);
|
||||
AndDietCokeDbContext.InsertDishToDatabaseAndReturn(dish.Id, dishName: "name");
|
||||
AndDietCokeDbContext.InsertDishToDatabaseAndReturn(dishName: dish.DishName, isDeleted: true);
|
||||
Assert.That(() => _dishStorageContract.UpdElement(dish), Throws.Nothing);
|
||||
}
|
||||
|
||||
@@ -234,16 +235,16 @@ internal class DishStorageContractTests : BaseStorageContractTest
|
||||
public void Try_UpdElement_WhenRecordWasDeleted_Test()
|
||||
{
|
||||
var dish = CreateModel(Guid.NewGuid().ToString());
|
||||
InsertDishToDatabaseAndReturn(dish.Id, isDeleted: true);
|
||||
AndDietCokeDbContext.InsertDishToDatabaseAndReturn(dish.Id, isDeleted: true);
|
||||
Assert.That(() => _dishStorageContract.UpdElement(dish), Throws.TypeOf<ElementNotFoundException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_DelElement_Test()
|
||||
{
|
||||
var dish = InsertDishToDatabaseAndReturn(Guid.NewGuid().ToString(), isDeleted: false);
|
||||
var dish = AndDietCokeDbContext.InsertDishToDatabaseAndReturn(isDeleted: false);
|
||||
_dishStorageContract.DelElement(dish.Id);
|
||||
var element = GetDishFromDatabaseById(dish.Id);
|
||||
var element = AndDietCokeDbContext.GetDishFromDatabaseById(dish.Id);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(element, Is.Not.Null);
|
||||
@@ -260,26 +261,10 @@ internal class DishStorageContractTests : BaseStorageContractTest
|
||||
[Test]
|
||||
public void Try_DelElement_WhenRecordWasDeleted_Test()
|
||||
{
|
||||
var dish = InsertDishToDatabaseAndReturn(Guid.NewGuid().ToString(), isDeleted: true);
|
||||
var dish = AndDietCokeDbContext.InsertDishToDatabaseAndReturn(isDeleted: true);
|
||||
Assert.That(() => _dishStorageContract.DelElement(dish.Id), Throws.TypeOf<ElementNotFoundException>());
|
||||
}
|
||||
|
||||
private Dish InsertDishToDatabaseAndReturn(string id, string dishName = "test", DishType dishType = DishType.Drink, double price = 1, bool isDeleted = false)
|
||||
{
|
||||
var dish = new Dish() { Id = id, DishName = dishName, DishType = dishType, Price = price, IsDeleted = isDeleted };
|
||||
AndDietCokeDbContext.Dishes.Add(dish);
|
||||
AndDietCokeDbContext.SaveChanges();
|
||||
return dish;
|
||||
}
|
||||
|
||||
private DishHistory InsertDishHistoryToDatabaseAndReturn(string dishId, double price, DateTime changeDate)
|
||||
{
|
||||
var dishHistory = new DishHistory() { Id = Guid.NewGuid().ToString(), DishId = dishId, OldPrice = price, ChangeDate = changeDate };
|
||||
AndDietCokeDbContext.DishHistories.Add(dishHistory);
|
||||
AndDietCokeDbContext.SaveChanges();
|
||||
return dishHistory;
|
||||
}
|
||||
|
||||
private static void AssertElement(DishDataModel? actual, Dish expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
@@ -296,8 +281,6 @@ internal class DishStorageContractTests : BaseStorageContractTest
|
||||
private static DishDataModel CreateModel(string id, string dishName = "test", DishType dishType = DishType.Drink, double price = 1, bool isDeleted = false)
|
||||
=> new(id, dishName, dishType, price, isDeleted);
|
||||
|
||||
private Dish? GetDishFromDatabaseById(string id) => AndDietCokeDbContext.Dishes.FirstOrDefault(x => x.Id == id);
|
||||
|
||||
private static void AssertElement(Dish? actual, DishDataModel expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
@@ -310,4 +293,4 @@ internal class DishStorageContractTests : BaseStorageContractTest
|
||||
Assert.That(actual.IsDeleted, Is.EqualTo(expected.IsDeleted));
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,7 @@ using System.Threading.Tasks;
|
||||
using AndDietCokeDatabase.Implementations;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using AndDietCokeDatabase.Models;
|
||||
using AndDietCokeTests.Infrastructure;
|
||||
|
||||
namespace AndDietCokeTests.StoragesContracts;
|
||||
|
||||
@@ -28,15 +29,15 @@ internal class PostStorageContractTests : BaseStorageContractTest
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
AndDietCokeDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Posts\" CASCADE;");
|
||||
AndDietCokeDbContext.RemovePostsFromDatabase();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_WhenHaveRecords_Test()
|
||||
{
|
||||
var post = InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 1", PostType.Chef, 20, true, DateTime.MinValue);
|
||||
InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 2", PostType.Chef, 20, true, DateTime.MinValue);
|
||||
InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 3", PostType.Chef, 20, true, DateTime.MinValue);
|
||||
var post = AndDietCokeDbContext.InsertPostToDatabaseAndReturn(postName: "name 1");
|
||||
AndDietCokeDbContext.InsertPostToDatabaseAndReturn(postName: "name 2");
|
||||
AndDietCokeDbContext.InsertPostToDatabaseAndReturn(postName: "name 3");
|
||||
var list = _postStorageContract.GetList();
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(3));
|
||||
@@ -51,44 +52,13 @@ internal class PostStorageContractTests : BaseStorageContractTest
|
||||
Assert.That(list, Is.Empty);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_OnlyActual_Test()
|
||||
{
|
||||
InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 1", isActual: true);
|
||||
InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 2", isActual: true);
|
||||
InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 3", isActual: false);
|
||||
var list = _postStorageContract.GetList(onlyActual: true);
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(list, Has.Count.EqualTo(2));
|
||||
Assert.That(!list.Any(x => !x.IsActual));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_IncludeNoActual_Test()
|
||||
{
|
||||
InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 1", isActual: true);
|
||||
InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 2", isActual: true);
|
||||
InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 3", isActual: false);
|
||||
var list = _postStorageContract.GetList(onlyActual: false);
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(list, Has.Count.EqualTo(3));
|
||||
Assert.That(list.Count(x => x.IsActual), Is.EqualTo(2));
|
||||
Assert.That(list.Count(x => !x.IsActual), Is.EqualTo(1));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetPostWithHistory_WhenHaveRecords_Test()
|
||||
{
|
||||
var postId = Guid.NewGuid().ToString();
|
||||
InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 1", isActual: true);
|
||||
InsertPostToDatabaseAndReturn(postId, "name 2", isActual: true);
|
||||
InsertPostToDatabaseAndReturn(postId, "name 2", isActual: false);
|
||||
AndDietCokeDbContext.InsertPostToDatabaseAndReturn(postName: "name 1", isActual: true);
|
||||
AndDietCokeDbContext.InsertPostToDatabaseAndReturn(postId, "name 2", isActual: true);
|
||||
AndDietCokeDbContext.InsertPostToDatabaseAndReturn(postId, "name 2", isActual: false);
|
||||
var list = _postStorageContract.GetPostWithHistory(postId);
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(2));
|
||||
@@ -97,12 +67,11 @@ internal class PostStorageContractTests : BaseStorageContractTest
|
||||
[Test]
|
||||
public void Try_GetPostWithHistory_WhenNoRecords_Test()
|
||||
{
|
||||
var nonExistentId = Guid.NewGuid().ToString();
|
||||
var postId = Guid.NewGuid().ToString();
|
||||
InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 1", isActual: true);
|
||||
InsertPostToDatabaseAndReturn(postId, "name 2", isActual: true);
|
||||
InsertPostToDatabaseAndReturn(postId, "name 2", isActual: false);
|
||||
var list = _postStorageContract.GetPostWithHistory(nonExistentId);
|
||||
AndDietCokeDbContext.InsertPostToDatabaseAndReturn(postName: "name 1", isActual: true);
|
||||
AndDietCokeDbContext.InsertPostToDatabaseAndReturn(postId, "name 2", isActual: true);
|
||||
AndDietCokeDbContext.InsertPostToDatabaseAndReturn(postId, "name 2", isActual: false);
|
||||
var list = _postStorageContract.GetPostWithHistory(Guid.NewGuid().ToString());
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(0));
|
||||
}
|
||||
@@ -110,81 +79,73 @@ internal class PostStorageContractTests : BaseStorageContractTest
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenHaveRecord_Test()
|
||||
{
|
||||
var post = InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
var post = AndDietCokeDbContext.InsertPostToDatabaseAndReturn();
|
||||
AssertElement(_postStorageContract.GetElementById(post.PostId), post);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenNoRecord_Test()
|
||||
{
|
||||
InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
AndDietCokeDbContext.InsertPostToDatabaseAndReturn();
|
||||
Assert.That(() => _postStorageContract.GetElementById(Guid.NewGuid().ToString()), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenRecordHasDeleted_Test()
|
||||
public void Try_GetElementById_WhenRecordWasDeleted_Test()
|
||||
{
|
||||
var post = InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), isActual: false);
|
||||
var post = AndDietCokeDbContext.InsertPostToDatabaseAndReturn(isActual: false);
|
||||
Assert.That(() => _postStorageContract.GetElementById(post.PostId), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenTrySearchById_Test()
|
||||
{
|
||||
var post = InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
var post = AndDietCokeDbContext.InsertPostToDatabaseAndReturn();
|
||||
Assert.That(() => _postStorageContract.GetElementById(post.Id), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementByName_WhenHaveRecord_Test()
|
||||
{
|
||||
var post = InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
var post = AndDietCokeDbContext.InsertPostToDatabaseAndReturn();
|
||||
AssertElement(_postStorageContract.GetElementByName(post.PostName), post);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementByName_WhenNoRecord_Test()
|
||||
{
|
||||
InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
AndDietCokeDbContext.InsertPostToDatabaseAndReturn();
|
||||
Assert.That(() => _postStorageContract.GetElementByName("name"), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementByName_WhenRecordHasDeleted_Test()
|
||||
public void Try_GetElementByName_WhenRecordWasDeleted_Test()
|
||||
{
|
||||
var post = InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), isActual: false);
|
||||
var post = AndDietCokeDbContext.InsertPostToDatabaseAndReturn(isActual: false);
|
||||
Assert.That(() => _postStorageContract.GetElementById(post.PostName), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_Test()
|
||||
{
|
||||
var post = CreateModel(Guid.NewGuid().ToString(), isActual: true);
|
||||
var post = CreateModel(Guid.NewGuid().ToString());
|
||||
_postStorageContract.AddElement(post);
|
||||
AssertElement(GetPostFromDatabaseByPostId(post.Id), post);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_WhenActualIsFalse_Test()
|
||||
{
|
||||
var post = CreateModel(Guid.NewGuid().ToString(), isActual: false);
|
||||
Assert.That(() => _postStorageContract.AddElement(post), Throws.Nothing);
|
||||
AssertElement(GetPostFromDatabaseByPostId(post.Id), CreateModel(post.Id, isActual: true));
|
||||
AssertElement(AndDietCokeDbContext.GetPostFromDatabaseByPostId(post.Id), post);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_WhenHaveRecordWithSameName_Test()
|
||||
{
|
||||
var post = CreateModel(Guid.NewGuid().ToString(), "name unique", isActual: true);
|
||||
InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), postName: post.PostName, isActual: true);
|
||||
var post = CreateModel(Guid.NewGuid().ToString(), "name unique");
|
||||
AndDietCokeDbContext.InsertPostToDatabaseAndReturn(postName: post.PostName, isActual: true);
|
||||
Assert.That(() => _postStorageContract.AddElement(post), Throws.TypeOf<ElementExistsException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_WhenHaveRecordWithSamePostIdAndActualIsTrue_Test()
|
||||
public void Try_AddElement_WhenHaveRecordWithSamePostId_Test()
|
||||
{
|
||||
var post = CreateModel(Guid.NewGuid().ToString(), isActual: true);
|
||||
InsertPostToDatabaseAndReturn(post.Id, isActual: true);
|
||||
var post = CreateModel(Guid.NewGuid().ToString());
|
||||
AndDietCokeDbContext.InsertPostToDatabaseAndReturn(post.Id, isActual: true);
|
||||
Assert.That(() => _postStorageContract.AddElement(post), Throws.TypeOf<ElementExistsException>());
|
||||
}
|
||||
|
||||
@@ -192,21 +153,13 @@ internal class PostStorageContractTests : BaseStorageContractTest
|
||||
public void Try_UpdElement_Test()
|
||||
{
|
||||
var post = CreateModel(Guid.NewGuid().ToString());
|
||||
InsertPostToDatabaseAndReturn(post.Id, isActual: true);
|
||||
AndDietCokeDbContext.InsertPostToDatabaseAndReturn(post.Id, isActual: true);
|
||||
_postStorageContract.UpdElement(post);
|
||||
var posts = AndDietCokeDbContext.Posts.Where(x => x.PostId == post.Id).OrderByDescending(x => x.ChangeDate);
|
||||
Assert.That(posts.Count(), Is.EqualTo(2));
|
||||
AssertElement(posts.First(), CreateModel(post.Id, isActual: true));
|
||||
AssertElement(posts.Last(), CreateModel(post.Id, isActual: false));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_UpdElement_WhenActualIsFalse_Test()
|
||||
{
|
||||
var post = CreateModel(Guid.NewGuid().ToString(), isActual: false);
|
||||
InsertPostToDatabaseAndReturn(post.Id, isActual: true);
|
||||
_postStorageContract.UpdElement(post);
|
||||
AssertElement(GetPostFromDatabaseByPostId(post.Id), CreateModel(post.Id, isActual: true));
|
||||
var posts = AndDietCokeDbContext.GetPostsFromDatabaseByPostId(post.Id);
|
||||
Assert.That(posts, Is.Not.Null);
|
||||
Assert.That(posts, Has.Length.EqualTo(2));
|
||||
AssertElement(posts[0], CreateModel(post.Id));
|
||||
AssertElement(posts[^1], CreateModel(post.Id));
|
||||
}
|
||||
|
||||
[Test]
|
||||
@@ -219,8 +172,8 @@ internal class PostStorageContractTests : BaseStorageContractTest
|
||||
public void Try_UpdElement_WhenHaveRecordWithSameName_Test()
|
||||
{
|
||||
var post = CreateModel(Guid.NewGuid().ToString(), "New Name");
|
||||
InsertPostToDatabaseAndReturn(post.Id, postName: "name");
|
||||
InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), postName: post.PostName);
|
||||
AndDietCokeDbContext.InsertPostToDatabaseAndReturn(post.Id, postName: "name");
|
||||
AndDietCokeDbContext.InsertPostToDatabaseAndReturn(postName: post.PostName);
|
||||
Assert.That(() => _postStorageContract.UpdElement(post), Throws.TypeOf<ElementExistsException>());
|
||||
}
|
||||
|
||||
@@ -228,21 +181,16 @@ internal class PostStorageContractTests : BaseStorageContractTest
|
||||
public void Try_UpdElement_WhenRecordWasDeleted_Test()
|
||||
{
|
||||
var post = CreateModel(Guid.NewGuid().ToString());
|
||||
InsertPostToDatabaseAndReturn(post.Id, isActual: false);
|
||||
AndDietCokeDbContext.InsertPostToDatabaseAndReturn(post.Id, isActual: false);
|
||||
Assert.That(() => _postStorageContract.UpdElement(post), Throws.TypeOf<ElementDeletedException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_DelElement_Test()
|
||||
{
|
||||
var post = InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), isActual: true);
|
||||
var post = AndDietCokeDbContext.InsertPostToDatabaseAndReturn(isActual: true);
|
||||
_postStorageContract.DelElement(post.PostId);
|
||||
var element = GetPostFromDatabaseByPostId(post.PostId);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(element, Is.Not.Null);
|
||||
Assert.That(!element!.IsActual);
|
||||
});
|
||||
Assert.That(AndDietCokeDbContext.GetPostFromDatabaseByPostId(post.PostId), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
@@ -254,16 +202,16 @@ internal class PostStorageContractTests : BaseStorageContractTest
|
||||
[Test]
|
||||
public void Try_DelElement_WhenRecordWasDeleted_Test()
|
||||
{
|
||||
var post = InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), isActual: false);
|
||||
var post = AndDietCokeDbContext.InsertPostToDatabaseAndReturn(isActual: false);
|
||||
Assert.That(() => _postStorageContract.DelElement(post.PostId), Throws.TypeOf<ElementDeletedException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_ResElement_Test()
|
||||
{
|
||||
var post = InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), isActual: false);
|
||||
var post = AndDietCokeDbContext.InsertPostToDatabaseAndReturn(isActual: false);
|
||||
_postStorageContract.ResElement(post.PostId);
|
||||
var element = GetPostFromDatabaseByPostId(post.PostId);
|
||||
var element = AndDietCokeDbContext.GetPostFromDatabaseByPostId(post.PostId);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(element, Is.Not.Null);
|
||||
@@ -280,18 +228,10 @@ internal class PostStorageContractTests : BaseStorageContractTest
|
||||
[Test]
|
||||
public void Try_ResElement_WhenRecordNotWasDeleted_Test()
|
||||
{
|
||||
var post = InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), isActual: true);
|
||||
var post = AndDietCokeDbContext.InsertPostToDatabaseAndReturn(isActual: true);
|
||||
Assert.That(() => _postStorageContract.ResElement(post.PostId), Throws.Nothing);
|
||||
}
|
||||
|
||||
private Post InsertPostToDatabaseAndReturn(string id, string postName = "test", PostType postType = PostType.Waiter, double salary = 10, bool isActual = true, DateTime? changeDate = null)
|
||||
{
|
||||
var post = new Post() { Id = Guid.NewGuid().ToString(), PostId = id, PostName = postName, PostType = postType, Salary = salary, IsActual = isActual, ChangeDate = changeDate ?? DateTime.UtcNow };
|
||||
AndDietCokeDbContext.Posts.Add(post);
|
||||
AndDietCokeDbContext.SaveChanges();
|
||||
return post;
|
||||
}
|
||||
|
||||
private static void AssertElement(PostDataModel? actual, Post expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
@@ -301,14 +241,13 @@ internal class PostStorageContractTests : BaseStorageContractTest
|
||||
Assert.That(actual.PostName, Is.EqualTo(expected.PostName));
|
||||
Assert.That(actual.PostType, Is.EqualTo(expected.PostType));
|
||||
Assert.That(actual.Salary, Is.EqualTo(expected.Salary));
|
||||
Assert.That(actual.IsActual, Is.EqualTo(expected.IsActual));
|
||||
});
|
||||
}
|
||||
|
||||
private static PostDataModel CreateModel(string postId, string postName = "test", PostType postType = PostType.Waiter, double salary = 10, bool isActual = false, DateTime? changeDate = null)
|
||||
=> new(postId, postName, postType, salary, isActual, changeDate ?? DateTime.UtcNow);
|
||||
|
||||
private Post? GetPostFromDatabaseByPostId(string id) => AndDietCokeDbContext.Posts.Where(x => x.PostId == id).OrderByDescending(x => x.ChangeDate).FirstOrDefault();
|
||||
private static PostDataModel CreateModel(string postId, string postName = "test", PostType postType = PostType.Packer, double salary = 10, bool isActive = true, DateTime? changeDate = null)
|
||||
{
|
||||
return new(postId, postName, postType, salary, isActive, changeDate ?? DateTime.Now);
|
||||
}
|
||||
|
||||
private static void AssertElement(Post? actual, PostDataModel expected)
|
||||
{
|
||||
@@ -319,7 +258,6 @@ internal class PostStorageContractTests : BaseStorageContractTest
|
||||
Assert.That(actual.PostName, Is.EqualTo(expected.PostName));
|
||||
Assert.That(actual.PostType, Is.EqualTo(expected.PostType));
|
||||
Assert.That(actual.Salary, Is.EqualTo(expected.Salary));
|
||||
Assert.That(actual.IsActual, Is.EqualTo(expected.IsActual));
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ using AndDietCokeDatabase.Implementations;
|
||||
using NUnit.Framework;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using AndDietCokeContracts.Enums;
|
||||
using AndDietCokeTests.Infrastructure;
|
||||
|
||||
namespace AndDietCokeTests.StoragesContracts;
|
||||
|
||||
@@ -21,26 +22,26 @@ internal class SaleStorageContractTests : BaseStorageContractTest
|
||||
public void SetUp()
|
||||
{
|
||||
_saletStorageContract = new SaleStorageContract(AndDietCokeDbContext);
|
||||
_buyer = InsertBuyerToDatabaseAndReturn();
|
||||
_worker = InsertWorkerToDatabaseAndReturn();
|
||||
_dish = InsertDishToDatabaseAndReturn();
|
||||
_buyer = AndDietCokeDbContext.InsertBuyerToDatabaseAndReturn();
|
||||
_worker = AndDietCokeDbContext.InsertWorkerToDatabaseAndReturn();
|
||||
_dish = AndDietCokeDbContext.InsertDishToDatabaseAndReturn();
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
AndDietCokeDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Sales\" CASCADE;");
|
||||
AndDietCokeDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Buyers\" CASCADE;");
|
||||
AndDietCokeDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Workers\" CASCADE;");
|
||||
AndDietCokeDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Dishes\" CASCADE;");
|
||||
AndDietCokeDbContext.RemoveSalesFromDatabase();
|
||||
AndDietCokeDbContext.RemoveWorkersFromDatabase();
|
||||
AndDietCokeDbContext.RemoveBuyersFromDatabase();
|
||||
AndDietCokeDbContext.RemoveDishesFromDatabase();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_WhenHaveRecords_Test()
|
||||
{
|
||||
var sale = InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, dishes: [(_dish.Id, 1)]);
|
||||
InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, dishes: [(_dish.Id, 5)]);
|
||||
InsertSaleToDatabaseAndReturn(_worker.Id, null, dishes: [(_dish.Id, 10)]);
|
||||
var sale = AndDietCokeDbContext.InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, dishes: [(_dish.Id, 1, 1.2)]);
|
||||
AndDietCokeDbContext.InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, dishes: [(_dish.Id, 5, 1.2)]);
|
||||
AndDietCokeDbContext.InsertSaleToDatabaseAndReturn(_worker.Id, null, dishes: [(_dish.Id, 10, 1.2)]);
|
||||
var list = _saletStorageContract.GetList();
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(3));
|
||||
@@ -58,10 +59,10 @@ internal class SaleStorageContractTests : BaseStorageContractTest
|
||||
[Test]
|
||||
public void Try_GetList_ByPeriod_Test()
|
||||
{
|
||||
InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(-3), dishes: [(_dish.Id, 1)]);
|
||||
InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(3), dishes: [(_dish.Id, 1)]);
|
||||
InsertSaleToDatabaseAndReturn(_worker.Id, null, saleDate: DateTime.UtcNow.AddDays(1).AddMinutes(-3), dishes: [(_dish.Id, 1)]);
|
||||
InsertSaleToDatabaseAndReturn(_worker.Id, null, saleDate: DateTime.UtcNow.AddDays(1).AddMinutes(3), dishes: [(_dish.Id, 1)]);
|
||||
AndDietCokeDbContext.InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(-3), dishes: [(_dish.Id, 1, 1.2)]);
|
||||
AndDietCokeDbContext.InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(3), dishes: [(_dish.Id, 1, 1.2)]);
|
||||
AndDietCokeDbContext.InsertSaleToDatabaseAndReturn(_worker.Id, null, saleDate: DateTime.UtcNow.AddDays(1).AddMinutes(-3), dishes: [(_dish.Id, 1, 1.2)]);
|
||||
AndDietCokeDbContext.InsertSaleToDatabaseAndReturn(_worker.Id, null, saleDate: DateTime.UtcNow.AddDays(1).AddMinutes(3), dishes: [(_dish.Id, 1, 1.2)]);
|
||||
var list = _saletStorageContract.GetList(startDate: DateTime.UtcNow.AddDays(-1), endDate: DateTime.UtcNow.AddDays(1));
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(2));
|
||||
@@ -70,10 +71,10 @@ internal class SaleStorageContractTests : BaseStorageContractTest
|
||||
[Test]
|
||||
public void Try_GetList_ByWorkerId_Test()
|
||||
{
|
||||
var worker = InsertWorkerToDatabaseAndReturn("Other worker");
|
||||
InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, dishes: [(_dish.Id, 1)]);
|
||||
InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, dishes: [(_dish.Id, 1)]);
|
||||
InsertSaleToDatabaseAndReturn(worker.Id, null, dishes: [(_dish.Id, 1)]);
|
||||
var worker = AndDietCokeDbContext.InsertWorkerToDatabaseAndReturn(fio: "Other worker");
|
||||
AndDietCokeDbContext.InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, dishes: [(_dish.Id, 1, 1.2)]);
|
||||
AndDietCokeDbContext.InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, dishes: [(_dish.Id, 1, 1.2)]);
|
||||
AndDietCokeDbContext.InsertSaleToDatabaseAndReturn(worker.Id, null, dishes: [(_dish.Id, 1, 1.2)]);
|
||||
var list = _saletStorageContract.GetList(workerId: _worker.Id);
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(2));
|
||||
@@ -83,11 +84,11 @@ internal class SaleStorageContractTests : BaseStorageContractTest
|
||||
[Test]
|
||||
public void Try_GetList_ByBuyerId_Test()
|
||||
{
|
||||
var buyer = InsertBuyerToDatabaseAndReturn("Other fio", "+8-888-888-88-88");
|
||||
InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, dishes: [(_dish.Id, 1)]);
|
||||
InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, dishes: [(_dish.Id, 1)]);
|
||||
InsertSaleToDatabaseAndReturn(_worker.Id, buyer.Id, dishes: [(_dish.Id, 1)]);
|
||||
InsertSaleToDatabaseAndReturn(_worker.Id, null, dishes: [(_dish.Id, 1)]);
|
||||
var buyer = AndDietCokeDbContext.InsertBuyerToDatabaseAndReturn(fio: "Other fio", phoneNumber: "+8-888-888-88-88");
|
||||
AndDietCokeDbContext.InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, dishes: [(_dish.Id, 1, 1.2)]);
|
||||
AndDietCokeDbContext.InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, dishes: [(_dish.Id, 1, 1.2)]);
|
||||
AndDietCokeDbContext.InsertSaleToDatabaseAndReturn(_worker.Id, buyer.Id, dishes: [(_dish.Id, 1, 1.2)]);
|
||||
AndDietCokeDbContext.InsertSaleToDatabaseAndReturn(_worker.Id, null, dishes: [(_dish.Id, 1, 1.2)]);
|
||||
var list = _saletStorageContract.GetList(buyerId: _buyer.Id);
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(2));
|
||||
@@ -97,30 +98,30 @@ internal class SaleStorageContractTests : BaseStorageContractTest
|
||||
[Test]
|
||||
public void Try_GetList_ByDishId_Test()
|
||||
{
|
||||
var dish = InsertDishToDatabaseAndReturn("Other name");
|
||||
InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, dishes: [(_dish.Id, 5)]);
|
||||
InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, dishes: [(_dish.Id, 1), (dish.Id, 4)]);
|
||||
InsertSaleToDatabaseAndReturn(_worker.Id, null, dishes: [(dish.Id, 1)]);
|
||||
InsertSaleToDatabaseAndReturn(_worker.Id, null, dishes: [(dish.Id, 1), (_dish.Id, 1)]);
|
||||
var dish = AndDietCokeDbContext.InsertDishToDatabaseAndReturn( dishName: "Other name");
|
||||
AndDietCokeDbContext.InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, dishes: [(_dish.Id, 5, 1.2)]);
|
||||
AndDietCokeDbContext.InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, dishes: [(_dish.Id, 1, 1.2), (dish.Id, 4, 1.2)]);
|
||||
AndDietCokeDbContext.InsertSaleToDatabaseAndReturn(_worker.Id, null, dishes: [(dish.Id, 1, 1.2)]);
|
||||
AndDietCokeDbContext.InsertSaleToDatabaseAndReturn(_worker.Id, null, dishes: [(dish.Id, 1, 1.2), (_dish.Id, 1, 1.2)]);
|
||||
var list = _saletStorageContract.GetList(dishId: _dish.Id);
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(3));
|
||||
Assert.That(list.All(x => x.Dishes.Any(y => y.DishId == _dish.Id)));
|
||||
Assert.That(list.All(x => x.Dishes!.Any(y => y.DishId == _dish.Id)));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_ByAllParameters_Test()
|
||||
{
|
||||
var worker = InsertWorkerToDatabaseAndReturn("Other worker");
|
||||
var buyer = InsertBuyerToDatabaseAndReturn("Other fio", "+8-888-888-88-88");
|
||||
var dish = InsertDishToDatabaseAndReturn("Other name");
|
||||
InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(-3), dishes: [(_dish.Id, 1)]);
|
||||
InsertSaleToDatabaseAndReturn(worker.Id, null, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(3), dishes: [(_dish.Id, 1)]);
|
||||
InsertSaleToDatabaseAndReturn(worker.Id, _buyer.Id, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(3), dishes: [(_dish.Id, 1)]);
|
||||
InsertSaleToDatabaseAndReturn(worker.Id, _buyer.Id, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(3), dishes: [(dish.Id, 1)]);
|
||||
InsertSaleToDatabaseAndReturn(_worker.Id, buyer.Id, saleDate: DateTime.UtcNow.AddDays(1).AddMinutes(-3), dishes: [(_dish.Id, 1)]);
|
||||
InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, saleDate: DateTime.UtcNow.AddDays(1).AddMinutes(-3), dishes: [(dish.Id, 1)]);
|
||||
InsertSaleToDatabaseAndReturn(worker.Id, null, saleDate: DateTime.UtcNow.AddDays(1).AddMinutes(-3), dishes: [(_dish.Id, 1)]);
|
||||
var worker = AndDietCokeDbContext.InsertWorkerToDatabaseAndReturn(fio: "Other worker");
|
||||
var buyer = AndDietCokeDbContext.InsertBuyerToDatabaseAndReturn(fio: "Other fio", phoneNumber: "+8-888-888-88-88");
|
||||
var dish = AndDietCokeDbContext.InsertDishToDatabaseAndReturn(dishName: "Other name");
|
||||
AndDietCokeDbContext.InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(-3), dishes: [(_dish.Id, 1, 1.2)]);
|
||||
AndDietCokeDbContext.InsertSaleToDatabaseAndReturn(worker.Id, null, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(3), dishes: [(_dish.Id, 1, 1.2)]);
|
||||
AndDietCokeDbContext.InsertSaleToDatabaseAndReturn(worker.Id, _buyer.Id, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(3), dishes: [(_dish.Id, 1, 1.2)]);
|
||||
AndDietCokeDbContext.InsertSaleToDatabaseAndReturn(worker.Id, _buyer.Id, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(3), dishes: [(dish.Id, 1, 1.2)]);
|
||||
AndDietCokeDbContext.InsertSaleToDatabaseAndReturn(_worker.Id, buyer.Id, saleDate: DateTime.UtcNow.AddDays(1).AddMinutes(-3), dishes: [(_dish.Id, 1, 1.2)]);
|
||||
AndDietCokeDbContext.InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, saleDate: DateTime.UtcNow.AddDays(1).AddMinutes(-3), dishes: [(dish.Id, 1, 1.2)]);
|
||||
AndDietCokeDbContext.InsertSaleToDatabaseAndReturn(worker.Id, null, saleDate: DateTime.UtcNow.AddDays(1).AddMinutes(-3), dishes: [(_dish.Id, 1, 1.2)]);
|
||||
var list = _saletStorageContract.GetList(startDate: DateTime.UtcNow.AddDays(-1), endDate: DateTime.UtcNow.AddDays(1), workerId: _worker.Id, buyerId: _buyer.Id, dishId: dish.Id);
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(1));
|
||||
@@ -129,46 +130,46 @@ internal class SaleStorageContractTests : BaseStorageContractTest
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenHaveRecord_Test()
|
||||
{
|
||||
var sale = InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, dishes: [(_dish.Id, 1)]);
|
||||
var sale = AndDietCokeDbContext.InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, dishes: [(_dish.Id, 1, 1.2)]);
|
||||
AssertElement(_saletStorageContract.GetElementById(sale.Id), sale);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenNoRecord_Test()
|
||||
{
|
||||
InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, dishes: [(_dish.Id, 1)]);
|
||||
AndDietCokeDbContext.InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, dishes: [(_dish.Id, 1, 1.2)]);
|
||||
Assert.That(() => _saletStorageContract.GetElementById(Guid.NewGuid().ToString()), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenRecordHasCanceled_Test()
|
||||
{
|
||||
var sale = InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, dishes: [(_dish.Id, 1)], isCancel: true);
|
||||
var sale = AndDietCokeDbContext.InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, dishes: [(_dish.Id, 1, 1.2)], isCancel: true);
|
||||
AssertElement(_saletStorageContract.GetElementById(sale.Id), sale);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_Test()
|
||||
{
|
||||
var sale = CreateModel(Guid.NewGuid().ToString(), _worker.Id, _buyer.Id, 1, true, false, [_dish.Id]);
|
||||
var sale = CreateModel(Guid.NewGuid().ToString(), _worker.Id, _buyer.Id, 0, true, false, [_dish.Id]);
|
||||
_saletStorageContract.AddElement(sale);
|
||||
AssertElement(GetSaleFromDatabaseById(sale.Id), sale);
|
||||
AssertElement(AndDietCokeDbContext.GetSaleFromDatabaseById(sale.Id), sale);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_WhenIsDeletedIsTrue_Test()
|
||||
{
|
||||
var sale = CreateModel(Guid.NewGuid().ToString(), _worker.Id, _buyer.Id, 1, true, false, [_dish.Id]);
|
||||
var sale = CreateModel(Guid.NewGuid().ToString(), _worker.Id, _buyer.Id, 0, true, true, [_dish.Id]);
|
||||
Assert.That(() => _saletStorageContract.AddElement(sale), Throws.Nothing);
|
||||
AssertElement(GetSaleFromDatabaseById(sale.Id), CreateModel(sale.Id, _worker.Id, _buyer.Id, 1, true, false, [_dish.Id]));
|
||||
AssertElement(AndDietCokeDbContext.GetSaleFromDatabaseById(sale.Id), CreateModel(sale.Id, _worker.Id, _buyer.Id, 0, true, false, [_dish.Id]));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_DelElement_Test()
|
||||
{
|
||||
var sale = InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, dishes: [(_dish.Id, 1)], isCancel: false);
|
||||
var sale = AndDietCokeDbContext.InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, dishes: [(_dish.Id, 1, 1.2)], isCancel: false);
|
||||
_saletStorageContract.DelElement(sale.Id);
|
||||
var element = GetSaleFromDatabaseById(sale.Id);
|
||||
var element = AndDietCokeDbContext.GetSaleFromDatabaseById(sale.Id);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(element, Is.Not.Null);
|
||||
@@ -185,49 +186,10 @@ internal class SaleStorageContractTests : BaseStorageContractTest
|
||||
[Test]
|
||||
public void Try_DelElement_WhenRecordWasCanceled_Test()
|
||||
{
|
||||
var sale = InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, dishes: [(_dish.Id, 1)], isCancel: true);
|
||||
var sale = AndDietCokeDbContext.InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, dishes: [(_dish.Id, 1, 1.2)], isCancel: true);
|
||||
Assert.That(() => _saletStorageContract.DelElement(sale.Id), Throws.TypeOf<ElementDeletedException>());
|
||||
}
|
||||
|
||||
private Buyer InsertBuyerToDatabaseAndReturn(string fio = "test", string phoneNumber = "+7-777-777-77-77")
|
||||
{
|
||||
var buyer = new Buyer() { Id = Guid.NewGuid().ToString(), FIO = fio, PhoneNumber = phoneNumber, DiscountSize = 10 };
|
||||
AndDietCokeDbContext.Buyers.Add(buyer);
|
||||
AndDietCokeDbContext.SaveChanges();
|
||||
return buyer;
|
||||
}
|
||||
|
||||
private Worker InsertWorkerToDatabaseAndReturn(string fio = "test")
|
||||
{
|
||||
var worker = new Worker() { Id = Guid.NewGuid().ToString(), FIO = fio, PostId = Guid.NewGuid().ToString() };
|
||||
AndDietCokeDbContext.Workers.Add(worker);
|
||||
AndDietCokeDbContext.SaveChanges();
|
||||
return worker;
|
||||
}
|
||||
|
||||
private Dish InsertDishToDatabaseAndReturn(string dishName = "test", DishType dishType = DishType.Base, double price = 1, bool isDeleted = false)
|
||||
{
|
||||
var dish = new Dish() { Id = Guid.NewGuid().ToString(), DishName = dishName, DishType = dishType, Price = price, IsDeleted = isDeleted };
|
||||
AndDietCokeDbContext.Dishes.Add(dish);
|
||||
AndDietCokeDbContext.SaveChanges();
|
||||
return dish;
|
||||
}
|
||||
|
||||
private Sale InsertSaleToDatabaseAndReturn(string workerId, string? buyerId, DateTime? saleDate = null, double sum = 1, bool isConstantClient = true, bool isCancel = false, List<(string, int)>? dishes = null)
|
||||
{
|
||||
var sale = new Sale() { WorkerId = workerId, BuyerId = buyerId, SaleDate = saleDate ?? DateTime.UtcNow, Sum = sum, IsConstantClient = isConstantClient, IsCancel = isCancel, OrderDishes = [] };
|
||||
if (dishes is not null)
|
||||
{
|
||||
foreach (var elem in dishes)
|
||||
{
|
||||
sale.OrderDishes.Add(new OrderDish { DishId = elem.Item1, OrderId = sale.Id, Count = elem.Item2 });
|
||||
}
|
||||
}
|
||||
AndDietCokeDbContext.Sales.Add(sale);
|
||||
AndDietCokeDbContext.SaveChanges();
|
||||
return sale;
|
||||
}
|
||||
|
||||
private static void AssertElement(SaleDataModel? actual, Sale expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
@@ -236,6 +198,8 @@ internal class SaleStorageContractTests : BaseStorageContractTest
|
||||
Assert.That(actual.Id, Is.EqualTo(expected.Id));
|
||||
Assert.That(actual.WorkerId, Is.EqualTo(expected.WorkerId));
|
||||
Assert.That(actual.BuyerId, Is.EqualTo(expected.BuyerId));
|
||||
Assert.That(actual.Sum, Is.EqualTo(expected.Sum));
|
||||
Assert.That(actual.IsConstantClient, Is.EqualTo(expected.IsConstantClient));
|
||||
Assert.That(actual.IsCancel, Is.EqualTo(expected.IsCancel));
|
||||
});
|
||||
|
||||
@@ -260,12 +224,10 @@ internal class SaleStorageContractTests : BaseStorageContractTest
|
||||
|
||||
private static SaleDataModel CreateModel(string id, string workerId, string? buyerId, double sum, bool isConstantClient, bool isCancel, List<string> dishIds)
|
||||
{
|
||||
var dishes = dishIds.Select(x => new OrderDishDataModel(id, x, 1)).ToList();
|
||||
return new(id, workerId, buyerId, sum, isConstantClient, isCancel, dishes);
|
||||
var dishes = dishIds.Select(x => new OrderDishDataModel(id, x, 1, 1.1)).ToList();
|
||||
return new(id, workerId, buyerId, isConstantClient, isCancel, dishes);
|
||||
}
|
||||
|
||||
private Sale? GetSaleFromDatabaseById(string id) => AndDietCokeDbContext.Sales.Include(x => x.OrderDishes).FirstOrDefault(x => x.Id == id);
|
||||
|
||||
private static void AssertElement(Sale? actual, SaleDataModel expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
@@ -274,6 +236,8 @@ internal class SaleStorageContractTests : BaseStorageContractTest
|
||||
Assert.That(actual.Id, Is.EqualTo(expected.Id));
|
||||
Assert.That(actual.WorkerId, Is.EqualTo(expected.WorkerId));
|
||||
Assert.That(actual.BuyerId, Is.EqualTo(expected.BuyerId));
|
||||
Assert.That(actual.Sum, Is.EqualTo(expected.Sum));
|
||||
Assert.That(actual.IsConstantClient, Is.EqualTo(expected.IsConstantClient));
|
||||
Assert.That(actual.IsCancel, Is.EqualTo(expected.IsCancel));
|
||||
});
|
||||
|
||||
@@ -287,6 +251,7 @@ internal class SaleStorageContractTests : BaseStorageContractTest
|
||||
{
|
||||
Assert.That(actual.OrderDishes[i].DishId, Is.EqualTo(expected.Dishes[i].DishId));
|
||||
Assert.That(actual.OrderDishes[i].Count, Is.EqualTo(expected.Dishes[i].Count));
|
||||
Assert.That(actual.OrderDishes[i].Price, Is.EqualTo(expected.Dishes[i].Price));
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -295,4 +260,4 @@ internal class SaleStorageContractTests : BaseStorageContractTest
|
||||
Assert.That(actual.OrderDishes, Is.Null);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@ using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using AndDietCokeTests.Infrastructure;
|
||||
|
||||
namespace AndDietCokeTests.StoragesContracts;
|
||||
|
||||
@@ -28,19 +29,19 @@ internal class WorkerStorageContractTests : BaseStorageContractTest
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
AndDietCokeDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Workers\" CASCADE;");
|
||||
AndDietCokeDbContext.RemoveWorkersFromDatabase();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_WhenHaveRecords_Test()
|
||||
{
|
||||
var worker = InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 1");
|
||||
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 2");
|
||||
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 3");
|
||||
var worker = AndDietCokeDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 1");
|
||||
AndDietCokeDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 2");
|
||||
AndDietCokeDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 3");
|
||||
var list = _workerStorageContract.GetList();
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(3));
|
||||
AssertElement(list.First(), worker);
|
||||
AssertElement(list.First(x => x.FIO == worker.FIO), worker);
|
||||
}
|
||||
|
||||
[Test]
|
||||
@@ -55,9 +56,9 @@ internal class WorkerStorageContractTests : BaseStorageContractTest
|
||||
public void Try_GetList_ByPostId_Test()
|
||||
{
|
||||
var postId = Guid.NewGuid().ToString();
|
||||
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 1", postId);
|
||||
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 2", postId);
|
||||
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 3");
|
||||
AndDietCokeDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 1", postId: postId);
|
||||
AndDietCokeDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 2", postId: postId);
|
||||
AndDietCokeDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 3");
|
||||
var list = _workerStorageContract.GetList(postId: postId);
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(2));
|
||||
@@ -67,10 +68,10 @@ internal class WorkerStorageContractTests : BaseStorageContractTest
|
||||
[Test]
|
||||
public void Try_GetList_ByBirthDate_Test()
|
||||
{
|
||||
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 1", birthDate: DateTime.UtcNow.AddYears(-25));
|
||||
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 2", birthDate: DateTime.UtcNow.AddYears(-21));
|
||||
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 3", birthDate: DateTime.UtcNow.AddYears(-20));
|
||||
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 4", birthDate: DateTime.UtcNow.AddYears(-19));
|
||||
AndDietCokeDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 1", birthDate: DateTime.UtcNow.AddYears(-25));
|
||||
AndDietCokeDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 2", birthDate: DateTime.UtcNow.AddYears(-21));
|
||||
AndDietCokeDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 3", birthDate: DateTime.UtcNow.AddYears(-20));
|
||||
AndDietCokeDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 4", birthDate: DateTime.UtcNow.AddYears(-19));
|
||||
var list = _workerStorageContract.GetList(fromBirthDate: DateTime.UtcNow.AddYears(-21).AddMinutes(-1), toBirthDate: DateTime.UtcNow.AddYears(-20).AddMinutes(1));
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(2));
|
||||
@@ -79,10 +80,10 @@ internal class WorkerStorageContractTests : BaseStorageContractTest
|
||||
[Test]
|
||||
public void Try_GetList_ByEmploymentDate_Test()
|
||||
{
|
||||
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 1", employmentDate: DateTime.UtcNow.AddDays(-2));
|
||||
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 2", employmentDate: DateTime.UtcNow.AddDays(-1));
|
||||
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 3", employmentDate: DateTime.UtcNow.AddDays(1));
|
||||
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 4", employmentDate: DateTime.UtcNow.AddDays(2));
|
||||
AndDietCokeDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 1", employmentDate: DateTime.UtcNow.AddDays(-2));
|
||||
AndDietCokeDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 2", employmentDate: DateTime.UtcNow.AddDays(-1));
|
||||
AndDietCokeDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 3", employmentDate: DateTime.UtcNow.AddDays(1));
|
||||
AndDietCokeDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 4", employmentDate: DateTime.UtcNow.AddDays(2));
|
||||
var list = _workerStorageContract.GetList(fromEmploymentDate: DateTime.UtcNow.AddDays(-1).AddMinutes(-1), toEmploymentDate: DateTime.UtcNow.AddDays(1).AddMinutes(1));
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(2));
|
||||
@@ -92,10 +93,10 @@ internal class WorkerStorageContractTests : BaseStorageContractTest
|
||||
public void Try_GetList_ByAllParameters_Test()
|
||||
{
|
||||
var postId = Guid.NewGuid().ToString();
|
||||
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 1", postId, birthDate: DateTime.UtcNow.AddYears(-25), employmentDate: DateTime.UtcNow.AddDays(-2));
|
||||
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 2", postId, birthDate: DateTime.UtcNow.AddYears(-22), employmentDate: DateTime.UtcNow.AddDays(-1));
|
||||
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 3", postId, birthDate: DateTime.UtcNow.AddYears(-21), employmentDate: DateTime.UtcNow.AddDays(-1));
|
||||
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 4", birthDate: DateTime.UtcNow.AddYears(-20), employmentDate: DateTime.UtcNow.AddDays(1));
|
||||
AndDietCokeDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 1", postId: postId, birthDate: DateTime.UtcNow.AddYears(-25), employmentDate: DateTime.UtcNow.AddDays(-2));
|
||||
AndDietCokeDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 2", postId: postId, birthDate: DateTime.UtcNow.AddYears(-22), employmentDate: DateTime.UtcNow.AddDays(-1));
|
||||
AndDietCokeDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 3", postId: postId, birthDate: DateTime.UtcNow.AddYears(-21), employmentDate: DateTime.UtcNow.AddDays(-1));
|
||||
AndDietCokeDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 4", birthDate: DateTime.UtcNow.AddYears(-20), employmentDate: DateTime.UtcNow.AddDays(1));
|
||||
var list = _workerStorageContract.GetList(postId: postId, fromBirthDate: DateTime.UtcNow.AddYears(-21).AddMinutes(-1), toBirthDate: DateTime.UtcNow.AddYears(-20).AddMinutes(1), fromEmploymentDate: DateTime.UtcNow.AddDays(-1).AddMinutes(-1), toEmploymentDate: DateTime.UtcNow.AddDays(1).AddMinutes(1));
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(1));
|
||||
@@ -104,7 +105,7 @@ internal class WorkerStorageContractTests : BaseStorageContractTest
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenHaveRecord_Test()
|
||||
{
|
||||
var worker = InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
var worker = AndDietCokeDbContext.InsertWorkerToDatabaseAndReturn();
|
||||
AssertElement(_workerStorageContract.GetElementById(worker.Id), worker);
|
||||
}
|
||||
|
||||
@@ -117,7 +118,7 @@ internal class WorkerStorageContractTests : BaseStorageContractTest
|
||||
[Test]
|
||||
public void Try_GetElementByFIO_WhenHaveRecord_Test()
|
||||
{
|
||||
var worker = InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
var worker = AndDietCokeDbContext.InsertWorkerToDatabaseAndReturn();
|
||||
AssertElement(_workerStorageContract.GetElementByFIO(worker.FIO), worker);
|
||||
}
|
||||
|
||||
@@ -132,14 +133,14 @@ internal class WorkerStorageContractTests : BaseStorageContractTest
|
||||
{
|
||||
var worker = CreateModel(Guid.NewGuid().ToString());
|
||||
_workerStorageContract.AddElement(worker);
|
||||
AssertElement(GetWorkerFromDatabase(worker.Id), worker);
|
||||
AssertElement(AndDietCokeDbContext.GetWorkerFromDatabaseById(worker.Id), worker);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_WhenHaveRecordWithSameId_Test()
|
||||
{
|
||||
var worker = CreateModel(Guid.NewGuid().ToString());
|
||||
InsertWorkerToDatabaseAndReturn(worker.Id);
|
||||
AndDietCokeDbContext.InsertWorkerToDatabaseAndReturn(worker.Id);
|
||||
Assert.That(() => _workerStorageContract.AddElement(worker), Throws.TypeOf<ElementExistsException>());
|
||||
}
|
||||
|
||||
@@ -147,9 +148,9 @@ internal class WorkerStorageContractTests : BaseStorageContractTest
|
||||
public void Try_UpdElement_Test()
|
||||
{
|
||||
var worker = CreateModel(Guid.NewGuid().ToString(), "New Fio");
|
||||
InsertWorkerToDatabaseAndReturn(worker.Id);
|
||||
AndDietCokeDbContext.InsertWorkerToDatabaseAndReturn(worker.Id);
|
||||
_workerStorageContract.UpdElement(worker);
|
||||
AssertElement(GetWorkerFromDatabase(worker.Id), worker);
|
||||
AssertElement(AndDietCokeDbContext.GetWorkerFromDatabaseById(worker.Id), worker);
|
||||
}
|
||||
|
||||
[Test]
|
||||
@@ -162,16 +163,16 @@ internal class WorkerStorageContractTests : BaseStorageContractTest
|
||||
public void Try_UpdElement_WhenNoRecordWasDeleted_Test()
|
||||
{
|
||||
var worker = CreateModel(Guid.NewGuid().ToString());
|
||||
InsertWorkerToDatabaseAndReturn(worker.Id, isDeleted: true);
|
||||
AndDietCokeDbContext.InsertWorkerToDatabaseAndReturn(worker.Id, isDeleted: true);
|
||||
Assert.That(() => _workerStorageContract.UpdElement(worker), Throws.TypeOf<ElementNotFoundException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_DelElement_Test()
|
||||
{
|
||||
var worker = InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
var worker = AndDietCokeDbContext.InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
_workerStorageContract.DelElement(worker.Id);
|
||||
var element = GetWorkerFromDatabase(worker.Id);
|
||||
var element = AndDietCokeDbContext.GetWorkerFromDatabaseById(worker.Id);
|
||||
Assert.That(element, Is.Not.Null);
|
||||
Assert.That(element.IsDeleted);
|
||||
}
|
||||
@@ -186,18 +187,10 @@ internal class WorkerStorageContractTests : BaseStorageContractTest
|
||||
public void Try_DelElement_WhenNoRecordWasDeleted_Test()
|
||||
{
|
||||
var worker = CreateModel(Guid.NewGuid().ToString());
|
||||
InsertWorkerToDatabaseAndReturn(worker.Id, isDeleted: true);
|
||||
AndDietCokeDbContext.InsertWorkerToDatabaseAndReturn(worker.Id, isDeleted: true);
|
||||
Assert.That(() => _workerStorageContract.DelElement(worker.Id), Throws.TypeOf<ElementNotFoundException>());
|
||||
}
|
||||
|
||||
private Worker InsertWorkerToDatabaseAndReturn(string id, string fio = "test", string? postId = null, DateTime? birthDate = null, DateTime? employmentDate = null, bool isDeleted = false)
|
||||
{
|
||||
var worker = new Worker() { Id = id, FIO = fio, PostId = postId ?? Guid.NewGuid().ToString(), BirthDate = birthDate ?? DateTime.UtcNow.AddYears(-20), EmploymentDate = employmentDate ?? DateTime.UtcNow, IsDeleted = isDeleted };
|
||||
AndDietCokeDbContext.Workers.Add(worker);
|
||||
AndDietCokeDbContext.SaveChanges();
|
||||
return worker;
|
||||
}
|
||||
|
||||
private static void AssertElement(WorkerDataModel? actual, Worker expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
@@ -215,8 +208,6 @@ internal class WorkerStorageContractTests : BaseStorageContractTest
|
||||
private static WorkerDataModel CreateModel(string id, string fio = "fio", string? postId = null, DateTime? birthDate = null, DateTime? employmentDate = null, bool isDeleted = false) =>
|
||||
new(id, fio, postId ?? Guid.NewGuid().ToString(), birthDate ?? DateTime.UtcNow.AddYears(-20), employmentDate ?? DateTime.UtcNow, isDeleted);
|
||||
|
||||
private Worker? GetWorkerFromDatabase(string id) => AndDietCokeDbContext.Workers.FirstOrDefault(x => x.Id == id);
|
||||
|
||||
private static void AssertElement(Worker? actual, WorkerDataModel expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
@@ -230,4 +221,4 @@ internal class WorkerStorageContractTests : BaseStorageContractTest
|
||||
Assert.That(actual.IsDeleted, Is.EqualTo(expected.IsDeleted));
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
using AndDietCokeDatabase;
|
||||
using AndDietCokeTests.Infrastructure;
|
||||
using Microsoft.AspNetCore.Mvc.Testing;
|
||||
using Microsoft.AspNetCore.TestHost;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Serilog;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace AndDietCokeTests.WebApiControllersTests;
|
||||
|
||||
internal class BaseWebApiControllerTest
|
||||
{
|
||||
private WebApplicationFactory<Program> _webApplication;
|
||||
|
||||
protected HttpClient HttpClient { get; private set; }
|
||||
|
||||
protected AndDietCokeDbContext AndDietCokeDbContext { 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}");
|
||||
|
||||
AndDietCokeDbContext = _webApplication.Services.GetRequiredService<AndDietCokeDbContext>();
|
||||
AndDietCokeDbContext.Database.EnsureDeleted();
|
||||
AndDietCokeDbContext.Database.EnsureCreated();
|
||||
}
|
||||
|
||||
[OneTimeTearDown]
|
||||
public void OneTimeTearDown()
|
||||
{
|
||||
AndDietCokeDbContext?.Database.EnsureDeleted();
|
||||
AndDietCokeDbContext?.Dispose();
|
||||
HttpClient?.Dispose();
|
||||
_webApplication?.Dispose();
|
||||
}
|
||||
|
||||
protected static async Task<T?> GetModelFromResponseAsync<T>(HttpResponseMessage response) =>
|
||||
JsonSerializer.Deserialize<T>(await response.Content.ReadAsStringAsync(), JsonSerializerOptions);
|
||||
|
||||
protected static StringContent MakeContent(object model) =>
|
||||
new(JsonSerializer.Serialize(model), Encoding.UTF8, "application/json");
|
||||
}
|
||||
@@ -0,0 +1,374 @@
|
||||
using AndDietCokeContracts.BindingModels;
|
||||
using AndDietCokeContracts.ViewModels;
|
||||
using AndDietCokeDatabase.Models;
|
||||
using AndDietCokeTests.Infrastructure;
|
||||
using NUnit.Framework;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace AndDietCokeTests.WebApiControllersTests;
|
||||
|
||||
[TestFixture]
|
||||
internal class BuyerControllerTests : BaseWebApiControllerTest
|
||||
{
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
AndDietCokeDbContext.RemoveSalesFromDatabase();
|
||||
AndDietCokeDbContext.RemoveWorkersFromDatabase();
|
||||
AndDietCokeDbContext.RemoveBuyersFromDatabase();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_WhenHaveRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var buyer = AndDietCokeDbContext.InsertBuyerToDatabaseAndReturn(phoneNumber: "+5-555-555-55-55");
|
||||
AndDietCokeDbContext.InsertBuyerToDatabaseAndReturn(phoneNumber: "+6-666-666-66-66");
|
||||
AndDietCokeDbContext.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 = AndDietCokeDbContext.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
|
||||
AndDietCokeDbContext.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 = AndDietCokeDbContext.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
|
||||
AndDietCokeDbContext.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 = AndDietCokeDbContext.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
|
||||
AndDietCokeDbContext.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
|
||||
AndDietCokeDbContext.InsertBuyerToDatabaseAndReturn();
|
||||
var buyerModel = CreateBindingModel();
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/buyers", MakeContent(buyerModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
AssertElement(AndDietCokeDbContext.GetBuyerFromDatabase(buyerModel.Id!), buyerModel);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenHaveRecordWithSameId_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var buyerModel = CreateBindingModel();
|
||||
AndDietCokeDbContext.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();
|
||||
AndDietCokeDbContext.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" };
|
||||
var buyerModelWithFioIncorrect = new BuyerBindingModel { Id = Guid.NewGuid().ToString(), FIO = string.Empty, PhoneNumber = "+7-111-111-11-11"};
|
||||
var buyerModelWithPhoneNumberIncorrect = new BuyerBindingModel { Id = Guid.NewGuid().ToString(), FIO = "fio", PhoneNumber = "+7-111-111-11-11"};
|
||||
//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");
|
||||
AndDietCokeDbContext.InsertBuyerToDatabaseAndReturn(buyerModel.Id);
|
||||
//Act
|
||||
var response = await HttpClient.PutAsync($"/api/buyers", MakeContent(buyerModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
AndDietCokeDbContext.ChangeTracker.Clear();
|
||||
AssertElement(AndDietCokeDbContext.GetBuyerFromDatabase(buyerModel.Id!), buyerModel);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WhenNoFoundRecord_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var buyerModel = CreateBindingModel(fio: "new fio");
|
||||
AndDietCokeDbContext.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");
|
||||
AndDietCokeDbContext.InsertBuyerToDatabaseAndReturn(buyerModel.Id);
|
||||
AndDietCokeDbContext.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"};
|
||||
var buyerModelWithFioIncorrect = new BuyerBindingModel { Id = Guid.NewGuid().ToString(), FIO = string.Empty, PhoneNumber = "+7-111-111-11-11"};
|
||||
var buyerModelWithPhoneNumberIncorrect = new BuyerBindingModel { Id = Guid.NewGuid().ToString(), FIO = "fio", PhoneNumber = "+7-111-111-11-11"};
|
||||
//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();
|
||||
AndDietCokeDbContext.InsertBuyerToDatabaseAndReturn(buyerId);
|
||||
//Act
|
||||
var response = await HttpClient.DeleteAsync($"/api/buyers/{buyerId}");
|
||||
//Assert
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
Assert.That(AndDietCokeDbContext.GetBuyerFromDatabase(buyerId), Is.Null);
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Delete_WhenHaveSalesByThisBuyer_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var buyer = AndDietCokeDbContext.InsertBuyerToDatabaseAndReturn();
|
||||
var worker = AndDietCokeDbContext.InsertWorkerToDatabaseAndReturn();
|
||||
AndDietCokeDbContext.InsertSaleToDatabaseAndReturn(worker.Id, buyer.Id);
|
||||
AndDietCokeDbContext.InsertSaleToDatabaseAndReturn(worker.Id, buyer.Id);
|
||||
var salesBeforeDelete = AndDietCokeDbContext.GetSalesByBuyerId(buyer.Id);
|
||||
//Act
|
||||
var response = await HttpClient.DeleteAsync($"/api/buyers/{buyer.Id}");
|
||||
//Assert
|
||||
AndDietCokeDbContext.ChangeTracker.Clear();
|
||||
var element = AndDietCokeDbContext.GetBuyerFromDatabase(buyer.Id);
|
||||
var salesAfterDelete = AndDietCokeDbContext.GetSalesByBuyerId(buyer.Id);
|
||||
var salesNoBuyers = AndDietCokeDbContext.GetSalesByBuyerId(null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
Assert.That(element, Is.Null);
|
||||
Assert.That(salesBeforeDelete, Has.Length.EqualTo(2));
|
||||
Assert.That(salesAfterDelete, Is.Empty);
|
||||
Assert.That(salesNoBuyers, Has.Length.EqualTo(2));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Delete_WhenNoFoundRecord_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
AndDietCokeDbContext.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
|
||||
};
|
||||
|
||||
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));
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,483 @@
|
||||
using AndDietCokeContracts.BindingModels;
|
||||
using AndDietCokeContracts.Enums;
|
||||
using AndDietCokeContracts.ViewModels;
|
||||
using AndDietCokeDatabase.Models;
|
||||
using AndDietCokeTests.Infrastructure;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace AndDietCokeTests.WebApiControllersTests;
|
||||
|
||||
[TestFixture]
|
||||
internal class DishControllerTests : BaseWebApiControllerTest
|
||||
{
|
||||
|
||||
[SetUp]
|
||||
public void SetUp()
|
||||
{
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
AndDietCokeDbContext.RemoveDishesFromDatabase();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_WhenHaveRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var dish = AndDietCokeDbContext.InsertDishToDatabaseAndReturn(dishName: "name 1");
|
||||
AndDietCokeDbContext.InsertDishToDatabaseAndReturn(dishName: "name 2");
|
||||
AndDietCokeDbContext.InsertDishToDatabaseAndReturn(dishName: "name 3");
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync("/api/dishes/getrecords?includeDeleted=false");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<DishViewModel>>(response);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(3));
|
||||
});
|
||||
AssertElement(data.First(x => x.Id == dish.Id), dish);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_WhenNoRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync("/api/dishes/getrecords?includeDeleted=false");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<DishViewModel>>(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
|
||||
AndDietCokeDbContext.InsertDishToDatabaseAndReturn(dishName: "name 1", isDeleted: true);
|
||||
AndDietCokeDbContext.InsertDishToDatabaseAndReturn(dishName: "name 2", isDeleted: false);
|
||||
AndDietCokeDbContext.InsertDishToDatabaseAndReturn(dishName: "name 3", isDeleted: false);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync("/api/dishes/getrecords?includeDeleted=false");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<DishViewModel>>(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
|
||||
AndDietCokeDbContext.InsertDishToDatabaseAndReturn(dishName: "name 1", isDeleted: true);
|
||||
AndDietCokeDbContext.InsertDishToDatabaseAndReturn(dishName: "name 2", isDeleted: true);
|
||||
AndDietCokeDbContext.InsertDishToDatabaseAndReturn(dishName: "name 3", isDeleted: false);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync("/api/dishes/getrecords?includeDeleted=true");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<DishViewModel>>(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 GetHistoryByDishId_WhenHaveRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var dish = AndDietCokeDbContext.InsertDishToDatabaseAndReturn();
|
||||
AndDietCokeDbContext.InsertDishHistoryToDatabaseAndReturn(dish.Id, 20, DateTime.UtcNow.AddDays(-1));
|
||||
AndDietCokeDbContext.InsertDishHistoryToDatabaseAndReturn(dish.Id, 30, DateTime.UtcNow.AddMinutes(-10));
|
||||
var history = AndDietCokeDbContext.InsertDishHistoryToDatabaseAndReturn(dish.Id, 40, DateTime.UtcNow.AddDays(1));
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/dishes/gethistory?id={dish.Id}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<DishHistoryViewModel>>(response);
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(3));
|
||||
AssertElement(data[0], history);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetHistoryByDishId_WhenNoRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var dish = AndDietCokeDbContext.InsertDishToDatabaseAndReturn();
|
||||
AndDietCokeDbContext.InsertDishHistoryToDatabaseAndReturn(dish.Id, 20, DateTime.UtcNow.AddDays(-1));
|
||||
AndDietCokeDbContext.InsertDishHistoryToDatabaseAndReturn(dish.Id, 30, DateTime.UtcNow.AddMinutes(-10));
|
||||
AndDietCokeDbContext.InsertDishHistoryToDatabaseAndReturn(dish.Id, 40, DateTime.UtcNow.AddDays(1));
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/dishes/gethistory?id={Guid.NewGuid()}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<DishViewModel>>(response);
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(0));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetHistoryByDishId_WhenDishIdIsNotGuid_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/dishes/gethistory?id=id");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ById_WhenHaveRecord_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var dish = AndDietCokeDbContext.InsertDishToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/dishes/getrecord/{dish.Id}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
AssertElement(await GetModelFromResponseAsync<DishViewModel>(response), dish);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ById_WhenNoRecord_ShouldNotFound_Test()
|
||||
{
|
||||
//Arrange
|
||||
AndDietCokeDbContext.InsertDishToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/dishes/getrecord/{Guid.NewGuid()}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ById_WhenRecordWasDeleted_ShouldNotFound_Test()
|
||||
{
|
||||
//Arrange
|
||||
var dish = AndDietCokeDbContext.InsertDishToDatabaseAndReturn(isDeleted: true);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/dishes/getrecord/{dish.Id}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ByName_WhenHaveRecord_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var dish = AndDietCokeDbContext.InsertDishToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/dishes/getrecord/{dish.DishName}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
AssertElement(await GetModelFromResponseAsync<DishViewModel>(response), dish);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ByName_WhenNoRecord_ShouldNotFound_Test()
|
||||
{
|
||||
//Arrange
|
||||
AndDietCokeDbContext.InsertDishToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/dishes/getrecord/New%20Name");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ByName_WhenRecordWasDeleted_ShouldNotFound_Test()
|
||||
{
|
||||
//Arrange
|
||||
var dish = AndDietCokeDbContext.InsertDishToDatabaseAndReturn(isDeleted: true);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/dishes/getrecord/{dish.DishName}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
AndDietCokeDbContext.InsertDishToDatabaseAndReturn();
|
||||
var dishModel = CreateModel();
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/dishes/register", MakeContent(dishModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
AssertElement(AndDietCokeDbContext.GetDishFromDatabaseById(dishModel.Id!), dishModel);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenHaveRecordWithSameId_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var dishModel = CreateModel();
|
||||
AndDietCokeDbContext.InsertDishToDatabaseAndReturn(dishModel.Id);
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/dishes/register", MakeContent(dishModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenHaveRecordWithSameName_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var dishModel = CreateModel(dishName: "unique name");
|
||||
AndDietCokeDbContext.InsertDishToDatabaseAndReturn(dishName: dishModel.DishName!);
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/dishes/register", MakeContent(dishModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenDataIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var dishModelWithIdIncorrect = new DishBindingModel { Id = "Id",Price = 100, DishType = DishType.Dessert.ToString() };
|
||||
var dishModelWithNameIncorrect = new DishBindingModel { Id = Guid.NewGuid().ToString(),Price = 100, DishType = DishType.Dessert.ToString() };
|
||||
var dishModelWithDishTypeIncorrect = new DishBindingModel { Id = Guid.NewGuid().ToString(), Price = 100, DishType = string.Empty };
|
||||
var dishModelWithPriceIncorrect = new DishBindingModel { Id = Guid.NewGuid().ToString(), Price = 0, DishType = DishType.Dessert.ToString() };
|
||||
//Act
|
||||
var responseWithIdIncorrect = await HttpClient.PostAsync($"/api/dishes/register", MakeContent(dishModelWithIdIncorrect));
|
||||
var responseWithNameIncorrect = await HttpClient.PostAsync($"/api/dishes/register", MakeContent(dishModelWithNameIncorrect));
|
||||
var responseWithDishTypeIncorrect = await HttpClient.PostAsync($"/api/dishes/register", MakeContent(dishModelWithDishTypeIncorrect));
|
||||
var responseWithPriceIncorrect = await HttpClient.PostAsync($"/api/dishes/register", MakeContent(dishModelWithPriceIncorrect));
|
||||
//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(responseWithDishTypeIncorrect.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/dishes/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/dishes/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 dishModel = CreateModel();
|
||||
AndDietCokeDbContext.InsertDishToDatabaseAndReturn(dishModel.Id);
|
||||
//Act
|
||||
var response = await HttpClient.PutAsync($"/api/dishes/changeinfo", MakeContent(dishModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
AndDietCokeDbContext.ChangeTracker.Clear();
|
||||
AssertElement(AndDietCokeDbContext.GetDishFromDatabaseById(dishModel.Id!), dishModel);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WhenNoFoundRecord_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var dishModel = CreateModel();
|
||||
AndDietCokeDbContext.InsertDishToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.PutAsync($"/api/dishes/changeinfo", MakeContent(dishModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WhenHaveRecordWithSameName_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var dishModel = CreateModel(dishName: "unique name");
|
||||
AndDietCokeDbContext.InsertDishToDatabaseAndReturn(dishModel.Id);
|
||||
AndDietCokeDbContext.InsertDishToDatabaseAndReturn(dishName: dishModel.DishName!);
|
||||
//Act
|
||||
var response = await HttpClient.PutAsync($"/api/dishes/changeinfo", MakeContent(dishModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WhenRecordWasDeleted_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var dishModel = CreateModel();
|
||||
AndDietCokeDbContext.InsertDishToDatabaseAndReturn(dishModel.Id, isDeleted: true);
|
||||
//Act
|
||||
var response = await HttpClient.PutAsync($"/api/dishes/changeinfo", MakeContent(dishModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WhenDataIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var dishModelWithIdIncorrect = new DishBindingModel { Id = "Id", Price = 100, DishType = DishType.Dessert.ToString() };
|
||||
var dishModelWithNameIncorrect = new DishBindingModel { Id = Guid.NewGuid().ToString(), Price = 100, DishType = DishType.Dessert.ToString() };
|
||||
var dishModelWithDishTypeIncorrect = new DishBindingModel { Id = Guid.NewGuid().ToString(), Price = 100, DishType = string.Empty };
|
||||
var dishModelWithPriceIncorrect = new DishBindingModel { Id = Guid.NewGuid().ToString(), Price = 0, DishType = DishType.Dessert.ToString() };
|
||||
//Act
|
||||
var responseWithIdIncorrect = await HttpClient.PutAsync($"/api/dishes/changeinfo", MakeContent(dishModelWithIdIncorrect));
|
||||
var responseWithNameIncorrect = await HttpClient.PutAsync($"/api/dishes/changeinfo", MakeContent(dishModelWithNameIncorrect));
|
||||
var responseWithDishTypeIncorrect = await HttpClient.PutAsync($"/api/dishes/changeinfo", MakeContent(dishModelWithDishTypeIncorrect));
|
||||
var responseWithPriceIncorrect = await HttpClient.PutAsync($"/api/dishes/changeinfo", MakeContent(dishModelWithPriceIncorrect));
|
||||
//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(responseWithDishTypeIncorrect.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/dishes/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/dishes/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 dishId = Guid.NewGuid().ToString();
|
||||
AndDietCokeDbContext.InsertDishToDatabaseAndReturn(dishId);
|
||||
//Act
|
||||
var response = await HttpClient.DeleteAsync($"/api/dishes/delete/{dishId}");
|
||||
AndDietCokeDbContext.ChangeTracker.Clear();
|
||||
//Assert
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
Assert.That(AndDietCokeDbContext.GetDishFromDatabaseById(dishId)!.IsDeleted);
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Delete_WhenNoFoundRecord_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
AndDietCokeDbContext.InsertDishToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.DeleteAsync($"/api/dishes/delete/{Guid.NewGuid()}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Delete_WhenRecordWasDeleted_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var dishId = AndDietCokeDbContext.InsertDishToDatabaseAndReturn(isDeleted: true).Id;
|
||||
//Act
|
||||
var response = await HttpClient.DeleteAsync($"/api/dishes/delete/{dishId}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Delete_WhenSendWrongFormatData_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.DeleteAsync($"/api/dishes/delete/id");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
private static void AssertElement(DishViewModel? actual, Dish expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.Id, Is.EqualTo(expected.Id));
|
||||
Assert.That(actual.DishName, Is.EqualTo(expected.DishName));
|
||||
Assert.That(actual.DishType, Is.EqualTo(expected.DishType.ToString()));
|
||||
Assert.That(actual.Price, Is.EqualTo(expected.Price));
|
||||
Assert.That(actual.IsDeleted, Is.EqualTo(expected.IsDeleted));
|
||||
});
|
||||
}
|
||||
|
||||
private static void AssertElement(DishHistoryViewModel? actual, DishHistory expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.DishName, Is.EqualTo(expected.Dish!.DishName));
|
||||
Assert.That(actual.OldPrice, Is.EqualTo(expected.OldPrice));
|
||||
Assert.That(actual.ChangeDate.ToString(), Is.EqualTo(expected.ChangeDate.ToString()));
|
||||
});
|
||||
}
|
||||
|
||||
private static DishBindingModel CreateModel(string? id = null, string dishName = "name", DishType dishType = DishType.Base, double price = 1)
|
||||
=> new()
|
||||
{
|
||||
Id = id ?? Guid.NewGuid().ToString(),
|
||||
DishName = dishName,
|
||||
DishType = dishType.ToString(),
|
||||
Price = price
|
||||
};
|
||||
|
||||
private static void AssertElement(Dish? actual, DishBindingModel expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.Id, Is.EqualTo(expected.Id));
|
||||
Assert.That(actual.DishName, Is.EqualTo(expected.DishName));
|
||||
Assert.That(actual.DishType.ToString(), Is.EqualTo(expected.DishType));
|
||||
Assert.That(actual.Price, Is.EqualTo(expected.Price));
|
||||
Assert.That(!actual.IsDeleted);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,461 @@
|
||||
using AndDietCokeContracts.BindingModels;
|
||||
using AndDietCokeContracts.Enums;
|
||||
using AndDietCokeContracts.ViewModels;
|
||||
using AndDietCokeDatabase.Models;
|
||||
using AndDietCokeTests.Infrastructure;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace AndDietCokeTests.WebApiControllersTests;
|
||||
|
||||
[TestFixture]
|
||||
internal class PostControllerTests : BaseWebApiControllerTest
|
||||
{
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
AndDietCokeDbContext.RemovePostsFromDatabase();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetRecords_WhenHaveRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var post = AndDietCokeDbContext.InsertPostToDatabaseAndReturn(postName: "name 1");
|
||||
AndDietCokeDbContext.InsertPostToDatabaseAndReturn(postName: "name 2");
|
||||
AndDietCokeDbContext.InsertPostToDatabaseAndReturn(postName: "name 3");
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync("/api/posts");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<PostViewModel>>(response);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(3));
|
||||
});
|
||||
AssertElement(data.First(x => x.Id == post.PostId), post);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetHistory_WhenHaveRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var postId = Guid.NewGuid().ToString();
|
||||
AndDietCokeDbContext.InsertPostToDatabaseAndReturn(postName: "name 1", isActual: true);
|
||||
var post = AndDietCokeDbContext.InsertPostToDatabaseAndReturn(postId, "name 2", isActual: true);
|
||||
AndDietCokeDbContext.InsertPostToDatabaseAndReturn(postId, "name 2", isActual: false);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/posthistory/{postId}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<PostViewModel>>(response);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(2));
|
||||
});
|
||||
AssertElement(data.First(x => x.Id == post.PostId), post);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetHistory_WhenNoRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var postId = Guid.NewGuid().ToString();
|
||||
AndDietCokeDbContext.InsertPostToDatabaseAndReturn(postName: "name 1", isActual: true);
|
||||
AndDietCokeDbContext.InsertPostToDatabaseAndReturn(postId, "name 2", isActual: true);
|
||||
AndDietCokeDbContext.InsertPostToDatabaseAndReturn(postId, "name 2", isActual: false);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/posthistory/{Guid.NewGuid()}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<PostViewModel>>(response);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(0));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetHistory_WhenWrongData_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/posthistory/id");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ById_WhenHaveRecord_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var post = AndDietCokeDbContext.InsertPostToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/posts/{post.PostId}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
AssertElement(await GetModelFromResponseAsync<PostViewModel>(response), post);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ById_WhenNoRecord_ShouldNotFound_Test()
|
||||
{
|
||||
//Arrange
|
||||
AndDietCokeDbContext.InsertPostToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/posts/{Guid.NewGuid()}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ById_WhenRecordWasDeleted_ShouldNotFound_Test()
|
||||
{
|
||||
//Arrange
|
||||
var post = AndDietCokeDbContext.InsertPostToDatabaseAndReturn(isActual: false);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/posts/{post.PostId}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ByName_WhenHaveRecord_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var post = AndDietCokeDbContext.InsertPostToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/posts/{post.PostName}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
AssertElement(await GetModelFromResponseAsync<PostViewModel>(response), post);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ByName_WhenNoRecord_ShouldNotFound_Test()
|
||||
{
|
||||
//Arrange
|
||||
AndDietCokeDbContext.InsertPostToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/posts/New%20Name");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ByName_WhenRecordWasDeleted_ShouldNotFound_Test()
|
||||
{
|
||||
//Arrange
|
||||
var post = AndDietCokeDbContext.InsertPostToDatabaseAndReturn(isActual: false);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/posts/{post.PostName}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
AndDietCokeDbContext.InsertPostToDatabaseAndReturn();
|
||||
var postModel = CreateModel();
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/posts", MakeContent(postModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
AssertElement(AndDietCokeDbContext.GetPostFromDatabaseByPostId(postModel.Id!), postModel);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenHaveRecordWithSameId_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var postModel = CreateModel();
|
||||
AndDietCokeDbContext.InsertPostToDatabaseAndReturn(postModel.Id);
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/posts", MakeContent(postModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenHaveRecordWithSameName_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var postModel = CreateModel(postName: "unique name");
|
||||
AndDietCokeDbContext.InsertPostToDatabaseAndReturn(postName: postModel.PostName!);
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/posts", MakeContent(postModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenDataIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var postModelWithIdIncorrect = new PostBindingModel { Id = "Id", PostName = "name", PostType = PostType.Packer.ToString(), Salary = 10 };
|
||||
var postModelWithNameIncorrect = new PostBindingModel { Id = Guid.NewGuid().ToString(), PostName = string.Empty, PostType = PostType.Packer.ToString(), Salary = 10 };
|
||||
var postModelWithPostTypeIncorrect = new PostBindingModel { Id = Guid.NewGuid().ToString(), PostName = string.Empty, PostType = string.Empty, Salary = 10 };
|
||||
var postModelWithSalaryIncorrect = new PostBindingModel { Id = Guid.NewGuid().ToString(), PostName = string.Empty, PostType = PostType.Packer.ToString(), Salary = -10 };
|
||||
//Act
|
||||
var responseWithIdIncorrect = await HttpClient.PostAsync($"/api/posts", MakeContent(postModelWithIdIncorrect));
|
||||
var responseWithNameIncorrect = await HttpClient.PostAsync($"/api/posts", MakeContent(postModelWithNameIncorrect));
|
||||
var responseWithPostTypeIncorrect = await HttpClient.PostAsync($"/api/posts", MakeContent(postModelWithPostTypeIncorrect));
|
||||
var responseWithSalaryIncorrect = await HttpClient.PostAsync($"/api/posts", MakeContent(postModelWithSalaryIncorrect));
|
||||
//Assert
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(responseWithIdIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Id is incorrect");
|
||||
Assert.That(responseWithNameIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Name is incorrect");
|
||||
Assert.That(responseWithPostTypeIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Type is incorrect");
|
||||
Assert.That(responseWithSalaryIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Salary is incorrect");
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenSendEmptyData_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/posts", MakeContent(string.Empty));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenSendWrongFormatData_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/posts", MakeContent(new { Data = "test", Position = 10 }));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var postModel = CreateModel();
|
||||
AndDietCokeDbContext.InsertPostToDatabaseAndReturn(postModel.Id);
|
||||
//Act
|
||||
var response = await HttpClient.PutAsync($"/api/posts", MakeContent(postModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
AndDietCokeDbContext.ChangeTracker.Clear();
|
||||
AssertElement(AndDietCokeDbContext.GetPostFromDatabaseByPostId(postModel.Id!), postModel);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WhenNoFoundRecord_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var postModel = CreateModel();
|
||||
AndDietCokeDbContext.InsertPostToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.PutAsync($"/api/posts", MakeContent(postModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WhenRecordWasDeleted_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var postModel = CreateModel();
|
||||
AndDietCokeDbContext.InsertPostToDatabaseAndReturn(postModel.Id, isActual: false);
|
||||
//Act
|
||||
var response = await HttpClient.PutAsync($"/api/posts", MakeContent(postModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WhenHaveRecordWithSameName_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var postModel = CreateModel(postName: "unique name");
|
||||
AndDietCokeDbContext.InsertPostToDatabaseAndReturn(postModel.Id);
|
||||
AndDietCokeDbContext.InsertPostToDatabaseAndReturn(postName: postModel.PostName!);
|
||||
//Act
|
||||
var response = await HttpClient.PutAsync($"/api/posts", MakeContent(postModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WhenDataIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var postModelWithIdIncorrect = new PostBindingModel { Id = "Id", PostName = "name", PostType = PostType.Packer.ToString(), Salary = 10 };
|
||||
var postModelWithNameIncorrect = new PostBindingModel { Id = Guid.NewGuid().ToString(), PostName = string.Empty, PostType = PostType.Packer.ToString(), Salary = 10 };
|
||||
var postModelWithPostTypeIncorrect = new PostBindingModel { Id = Guid.NewGuid().ToString(), PostName = string.Empty, PostType = string.Empty, Salary = 10 };
|
||||
var postModelWithSalaryIncorrect = new PostBindingModel { Id = Guid.NewGuid().ToString(), PostName = string.Empty, PostType = PostType.Packer.ToString(), Salary = -10 };
|
||||
//Act
|
||||
var responseWithIdIncorrect = await HttpClient.PutAsync($"/api/posts", MakeContent(postModelWithIdIncorrect));
|
||||
var responseWithNameIncorrect = await HttpClient.PutAsync($"/api/posts", MakeContent(postModelWithNameIncorrect));
|
||||
var responseWithPostTypeIncorrect = await HttpClient.PutAsync($"/api/posts", MakeContent(postModelWithPostTypeIncorrect));
|
||||
var responseWithSalaryIncorrect = await HttpClient.PutAsync($"/api/posts", MakeContent(postModelWithSalaryIncorrect));
|
||||
//Assert
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(responseWithIdIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Id is incorrect");
|
||||
Assert.That(responseWithNameIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Name is incorrect");
|
||||
Assert.That(responseWithPostTypeIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Type is incorrect");
|
||||
Assert.That(responseWithSalaryIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Salary is incorrect");
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WhenSendEmptyData_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.PutAsync($"/api/posts", MakeContent(string.Empty));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WhenSendWrongFormatData_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.PutAsync($"/api/posts", MakeContent(new { Data = "test", Position = 10 }));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Delete_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var postId = AndDietCokeDbContext.InsertPostToDatabaseAndReturn().PostId;
|
||||
//Act
|
||||
var response = await HttpClient.DeleteAsync($"/api/posts/{postId}");
|
||||
//Assert
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
Assert.That(AndDietCokeDbContext.GetPostFromDatabaseByPostId(postId), Is.Null);
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Delete_WhenNoFoundRecord_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
AndDietCokeDbContext.InsertPostToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.DeleteAsync($"/api/posts/{Guid.NewGuid()}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Delete_WhenRecordWasDeleted_Test()
|
||||
{
|
||||
//Arrange
|
||||
var postId = AndDietCokeDbContext.InsertPostToDatabaseAndReturn(isActual: false).PostId;
|
||||
//Act
|
||||
var response = await HttpClient.DeleteAsync($"/api/posts/{postId}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Delete_WhenSendWrongFormatData_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.DeleteAsync($"/api/posts/id");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Patch_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var postId = AndDietCokeDbContext.InsertPostToDatabaseAndReturn(isActual: false).PostId;
|
||||
//Act
|
||||
var response = await HttpClient.PatchAsync($"/api/posts/{postId}", null);
|
||||
//Assert
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
Assert.That(AndDietCokeDbContext.GetPostFromDatabaseByPostId(postId), Is.Not.Null);
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Patch_WhenNoFoundRecord_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
AndDietCokeDbContext.InsertPostToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.PatchAsync($"/api/posts/{Guid.NewGuid()}", null);
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Patch_WhenRecordNotWasDeleted_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var postId = AndDietCokeDbContext.InsertPostToDatabaseAndReturn().PostId;
|
||||
//Act
|
||||
var response = await HttpClient.PatchAsync($"/api/posts/{postId}", null);
|
||||
//Assert
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
Assert.That(AndDietCokeDbContext.GetPostFromDatabaseByPostId(postId), Is.Not.Null);
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Patch_WhenSendWrongFormatData_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.PatchAsync($"/api/posts/id", null);
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
private static void AssertElement(PostViewModel? actual, Post expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.Id, Is.EqualTo(expected.PostId));
|
||||
Assert.That(actual.PostName, Is.EqualTo(expected.PostName));
|
||||
Assert.That(actual.PostType, Is.EqualTo(expected.PostType.ToString()));
|
||||
Assert.That(actual.Salary, Is.EqualTo(expected.Salary));
|
||||
});
|
||||
}
|
||||
|
||||
private static PostBindingModel CreateModel(string? postId = null, string postName = "name", PostType postType = PostType.Packer, double salary = 10)
|
||||
=> new()
|
||||
{
|
||||
Id = postId ?? Guid.NewGuid().ToString(),
|
||||
PostName = postName,
|
||||
PostType = postType.ToString(),
|
||||
Salary = salary
|
||||
};
|
||||
|
||||
private static void AssertElement(Post? actual, PostBindingModel expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.PostId, Is.EqualTo(expected.Id));
|
||||
Assert.That(actual.PostName, Is.EqualTo(expected.PostName));
|
||||
Assert.That(actual.PostType.ToString(), Is.EqualTo(expected.PostType));
|
||||
Assert.That(actual.Salary, Is.EqualTo(expected.Salary));
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
using AndDietCokeContracts.ViewModels;
|
||||
using AndDietCokeTests.Infrastructure;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace AndDietCokeTests.WebApiControllersTests;
|
||||
|
||||
[TestFixture]
|
||||
internal class SalaryControllerTests : BaseWebApiControllerTest
|
||||
{
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
AndDietCokeDbContext.RemovePostsFromDatabase();
|
||||
AndDietCokeDbContext.RemoveSalesFromDatabase();
|
||||
AndDietCokeDbContext.RemoveSalariesFromDatabase();
|
||||
AndDietCokeDbContext.RemoveWorkersFromDatabase();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_WhenHaveRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var worker = AndDietCokeDbContext.InsertWorkerToDatabaseAndReturn();
|
||||
var salary = AndDietCokeDbContext.InsertSalaryToDatabaseAndReturn(worker.Id, workerSalary: 100);
|
||||
AndDietCokeDbContext.InsertSalaryToDatabaseAndReturn(worker.Id);
|
||||
AndDietCokeDbContext.InsertSalaryToDatabaseAndReturn(worker.Id);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/salary/getrecords?fromDate={DateTime.UtcNow.AddDays(-10):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(10):MM/dd/yyyy HH:mm:ss}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<SalaryViewModel>>(response);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(3));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_WhenNoRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/salary/getrecords?fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<SalaryViewModel>>(response);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(0));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_OnlyForCertainPeriod_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var worker = AndDietCokeDbContext.InsertWorkerToDatabaseAndReturn();
|
||||
AndDietCokeDbContext.InsertSalaryToDatabaseAndReturn(worker.Id, salaryDate: DateTime.UtcNow.AddDays(-2));
|
||||
AndDietCokeDbContext.InsertSalaryToDatabaseAndReturn(worker.Id, salaryDate: DateTime.UtcNow.AddDays(-1).AddMinutes(5));
|
||||
AndDietCokeDbContext.InsertSalaryToDatabaseAndReturn(worker.Id, salaryDate: DateTime.UtcNow.AddDays(1).AddMinutes(-5));
|
||||
AndDietCokeDbContext.InsertSalaryToDatabaseAndReturn(worker.Id, salaryDate: DateTime.UtcNow.AddDays(-2));
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/salary/getrecords?fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<SalaryViewModel>>(response);
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Has.Count.EqualTo(2));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_WhenDatesAreIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/salary/getrecords?fromDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_ByWorker_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var worker1 = AndDietCokeDbContext.InsertWorkerToDatabaseAndReturn("fio","+7(555)555-55-55");
|
||||
var worker2 = AndDietCokeDbContext.InsertWorkerToDatabaseAndReturn("new fio", "+7(333)333-33-33");
|
||||
|
||||
AndDietCokeDbContext.InsertSalaryToDatabaseAndReturn(worker1.Id);
|
||||
AndDietCokeDbContext.InsertSalaryToDatabaseAndReturn(worker1.Id);
|
||||
|
||||
AndDietCokeDbContext.InsertSalaryToDatabaseAndReturn(worker2.Id);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/salary/getrecordsbyworker?fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}&workerId={worker1.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.WorkerId == worker1.Id));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_ByWorker_OnlyForCertainPeriod_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var worker1 = AndDietCokeDbContext.InsertWorkerToDatabaseAndReturn("fio", "+7(555)555-55-55");
|
||||
var worker2 = AndDietCokeDbContext.InsertWorkerToDatabaseAndReturn("new fio", "+7(333)333-33-33");
|
||||
AndDietCokeDbContext.InsertSalaryToDatabaseAndReturn(worker1.Id, salaryDate: DateTime.UtcNow.AddDays(-2));
|
||||
AndDietCokeDbContext.InsertSalaryToDatabaseAndReturn(worker1.Id, salaryDate: DateTime.UtcNow.AddDays(-1).AddMinutes(5));
|
||||
AndDietCokeDbContext.InsertSalaryToDatabaseAndReturn(worker2.Id, salaryDate: DateTime.UtcNow.AddDays(-1).AddMinutes(5));
|
||||
AndDietCokeDbContext.InsertSalaryToDatabaseAndReturn(worker1.Id, salaryDate: DateTime.UtcNow.AddDays(1).AddMinutes(-5));
|
||||
AndDietCokeDbContext.InsertSalaryToDatabaseAndReturn(worker2.Id, salaryDate: DateTime.UtcNow.AddDays(1).AddMinutes(-5));
|
||||
AndDietCokeDbContext.InsertSalaryToDatabaseAndReturn(worker1.Id, salaryDate: DateTime.UtcNow.AddDays(-2));
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/salary/getrecordsbyworker?fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}&workerId={worker1.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.WorkerId == worker1.Id));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_ByWorker_WhenDatesAreIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var worker = AndDietCokeDbContext.InsertWorkerToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/salary/getrecordsbyworker?fromDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&workerId={worker.Id}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_ByWorker_WhenIdIsNotGuid_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/salary/getrecordsbyworker?fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}&workerId=id");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Calculate_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var post = AndDietCokeDbContext.InsertPostToDatabaseAndReturn(salary: 1000);
|
||||
var worker = AndDietCokeDbContext.InsertWorkerToDatabaseAndReturn(postId: post.PostId);
|
||||
var sale = AndDietCokeDbContext.InsertSaleToDatabaseAndReturn(worker.Id);
|
||||
|
||||
var expectedSum = sale.Sum * 0.1 + post.Salary;
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/salary/calculate?date={DateTime.UtcNow:MM/dd/yyyy}", null);
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
var salaries = AndDietCokeDbContext.GetSalariesFromDatabaseByWorkerId(worker.Id);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(salaries, Has.Length.EqualTo(1));
|
||||
Assert.That(salaries.First().WorkerSalary, Is.EqualTo(expectedSum));
|
||||
Assert.That(salaries.First().SalaryDate.Month, Is.EqualTo(DateTime.UtcNow.Month));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Calculate_WhenAllWorkersWithoutSales_ShouldSuccess_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/salary/calculate?date={DateTime.UtcNow:MM/dd/yyyy}", null);
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
var salaries = AndDietCokeDbContext.Salaries.ToArray();
|
||||
Assert.That(salaries, Has.Length.EqualTo(0));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Calculate_WhenWorkerWithoutSales_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var post = AndDietCokeDbContext.InsertPostToDatabaseAndReturn(salary: 1000);
|
||||
var worker1 = AndDietCokeDbContext.InsertWorkerToDatabaseAndReturn("fio 1", post.PostId,"+7(555)555-55-55");
|
||||
var worker2 = AndDietCokeDbContext.InsertWorkerToDatabaseAndReturn("fio 2", post.PostId, "+7(333)333-33-33");
|
||||
var sale = AndDietCokeDbContext.InsertSaleToDatabaseAndReturn(worker1.Id);
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/salary/calculate?date={DateTime.UtcNow:MM/dd/yyyy}", null);
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
var salary1 = AndDietCokeDbContext.GetSalariesFromDatabaseByWorkerId(worker1.Id).First().WorkerSalary;
|
||||
var salary2 = AndDietCokeDbContext.GetSalariesFromDatabaseByWorkerId(worker2.Id).First().WorkerSalary;
|
||||
Assert.That(salary1, Is.Not.EqualTo(salary2));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Calculate_WhenWorkerWithoutPost_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
AndDietCokeDbContext.InsertPostToDatabaseAndReturn();
|
||||
var worker = AndDietCokeDbContext.InsertWorkerToDatabaseAndReturn(postId: Guid.NewGuid().ToString());
|
||||
var sale = AndDietCokeDbContext.InsertSaleToDatabaseAndReturn(worker.Id);
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/salary/calculate?date={DateTime.UtcNow:MM/dd/yyyy}", null);
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,504 @@
|
||||
using AndDietCokeContracts.BindingModels;
|
||||
using AndDietCokeContracts.ViewModels;
|
||||
using AndDietCokeDatabase.Models;
|
||||
using AndDietCokeTests.Infrastructure;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace AndDietCokeTests.WebApiControllersTests;
|
||||
|
||||
[TestFixture]
|
||||
internal class SaleControllerTests : BaseWebApiControllerTest
|
||||
{
|
||||
private string _buyerId;
|
||||
private string _workerId;
|
||||
private string _dishId;
|
||||
|
||||
[SetUp]
|
||||
public void SetUp()
|
||||
{
|
||||
_buyerId = AndDietCokeDbContext.InsertBuyerToDatabaseAndReturn().Id;
|
||||
_workerId = AndDietCokeDbContext.InsertWorkerToDatabaseAndReturn().Id;
|
||||
_dishId = AndDietCokeDbContext.InsertDishToDatabaseAndReturn().Id;
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
AndDietCokeDbContext.RemoveSalesFromDatabase();
|
||||
AndDietCokeDbContext.RemoveWorkersFromDatabase();
|
||||
AndDietCokeDbContext.RemoveBuyersFromDatabase();
|
||||
AndDietCokeDbContext.RemoveDishesFromDatabase();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_WhenHaveRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var sale = AndDietCokeDbContext.InsertSaleToDatabaseAndReturn(_workerId, buyerId: _buyerId, sum: 10, dishes: [(_dishId, 10, 1.1)]);
|
||||
AndDietCokeDbContext.InsertSaleToDatabaseAndReturn(_workerId, dishes: [(_dishId, 10, 1.1)]);
|
||||
AndDietCokeDbContext.InsertSaleToDatabaseAndReturn(_workerId, dishes: [(_dishId, 10, 1.1)]);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/sales/getrecords?fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<SaleViewModel>>(response);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(3));
|
||||
});
|
||||
AssertElement(data.First(x => x.Sum == sale.Sum), sale);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_WhenNoRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/sales/getrecords?fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<SaleViewModel>>(response);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(0));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_ByPeriod_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
AndDietCokeDbContext.InsertSaleToDatabaseAndReturn(_workerId, _buyerId, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(-3), dishes: [(_dishId, 1, 1.1)]);
|
||||
AndDietCokeDbContext.InsertSaleToDatabaseAndReturn(_workerId, _buyerId, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(3), dishes: [(_dishId, 1, 1.1)]);
|
||||
AndDietCokeDbContext.InsertSaleToDatabaseAndReturn(_workerId, null, saleDate: DateTime.UtcNow.AddDays(1).AddMinutes(-3), dishes: [(_dishId, 1, 1.1)]);
|
||||
AndDietCokeDbContext.InsertSaleToDatabaseAndReturn(_workerId, null, saleDate: DateTime.UtcNow.AddDays(1).AddMinutes(3), dishes: [(_dishId, 1, 1.1)]);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/sales/getrecords?fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<SaleViewModel>>(response);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(2));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_ByPeriod_WhenDateIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/sales/getrecords?fromDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_ByWorkerId_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var worker = AndDietCokeDbContext.InsertWorkerToDatabaseAndReturn(fio: "Other worker");
|
||||
AndDietCokeDbContext.InsertSaleToDatabaseAndReturn(_workerId, _buyerId, dishes: [(_dishId, 1, 1.1)]);
|
||||
AndDietCokeDbContext.InsertSaleToDatabaseAndReturn(_workerId, _buyerId, dishes: [(_dishId, 1, 1.1)]);
|
||||
AndDietCokeDbContext.InsertSaleToDatabaseAndReturn(worker.Id, null, dishes: [(_dishId, 1, 1.1)]);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/sales/getworkerrecords?id={_workerId}&fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<SaleViewModel>>(response);
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Has.Count.EqualTo(2));
|
||||
Assert.That(data.All(x => x.WorkerId == _workerId));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_ByWorkerId_WhenNoRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var worker = AndDietCokeDbContext.InsertWorkerToDatabaseAndReturn(fio: "Other worker");
|
||||
AndDietCokeDbContext.InsertSaleToDatabaseAndReturn(_workerId, _buyerId, dishes: [(_dishId, 1, 1.1)]);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/sales/getworkerrecords?id={worker.Id}&fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<SaleViewModel>>(response);
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(0));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_ByWorkerId_WhenDateIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/sales/getworkerrecords?id={_workerId}&fromDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_ByWorkerId_WhenIdIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/sales/getworkerrecords?id=Id&fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_ByBuyerId_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var buyer = AndDietCokeDbContext.InsertBuyerToDatabaseAndReturn(fio: "Other fio", phoneNumber: "+8-888-888-88-88");
|
||||
AndDietCokeDbContext.InsertSaleToDatabaseAndReturn(_workerId, _buyerId, dishes: [(_dishId, 1, 1.1)]);
|
||||
AndDietCokeDbContext.InsertSaleToDatabaseAndReturn(_workerId, _buyerId, dishes: [(_dishId, 1, 1.1)]);
|
||||
AndDietCokeDbContext.InsertSaleToDatabaseAndReturn(_workerId, buyer.Id, dishes: [(_dishId, 1, 1.1)]);
|
||||
AndDietCokeDbContext.InsertSaleToDatabaseAndReturn(_workerId, null, dishes: [(_dishId, 1, 1.1)]);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/sales/getbuyerrecords?id={_buyerId}&fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<SaleViewModel>>(response);
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Has.Count.EqualTo(2));
|
||||
Assert.That(data.All(x => x.BuyerId == _buyerId));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_ByBuyerId_WhenNoRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var buyer = AndDietCokeDbContext.InsertBuyerToDatabaseAndReturn(fio: "Other buyer", phoneNumber: "+8-888-888-88-88");
|
||||
AndDietCokeDbContext.InsertSaleToDatabaseAndReturn(_workerId, _buyerId, dishes: [(_dishId, 1, 1.1)]);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/sales/getbuyerrecords?id={buyer.Id}&fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<SaleViewModel>>(response);
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(0));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_ByBuyerId_WhenDateIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/sales/getbuyerrecords?id={_buyerId}&fromDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_ByBuyerId_WhenIdIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/sales/getbuyerrecords?id=Id&fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_ByDishId_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var dish = AndDietCokeDbContext.InsertDishToDatabaseAndReturn(dishName: "Other name");
|
||||
AndDietCokeDbContext.InsertSaleToDatabaseAndReturn(_workerId, _buyerId, dishes: [(_dishId, 5, 1.1)]);
|
||||
AndDietCokeDbContext.InsertSaleToDatabaseAndReturn(_workerId, _buyerId, dishes: [(_dishId, 1, 1.1), (dish.Id, 4, 1.1)]);
|
||||
AndDietCokeDbContext.InsertSaleToDatabaseAndReturn(_workerId, null, dishes: [(dish.Id, 1, 1.1)]);
|
||||
AndDietCokeDbContext.InsertSaleToDatabaseAndReturn(_workerId, null, dishes: [(dish.Id, 1, 1.1), (_dishId, 1, 1.1)]);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/sales/getdishrecords?id={_dishId}&fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<SaleViewModel>>(response);
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Has.Count.EqualTo(3));
|
||||
Assert.That(data.All(x => x.Dishes.Any(y => y.DishId == _dishId)));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_ByDishId_WhenNoRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var dish = AndDietCokeDbContext.InsertDishToDatabaseAndReturn(dishName: "Other dish");
|
||||
AndDietCokeDbContext.InsertSaleToDatabaseAndReturn(_workerId, _buyerId, dishes: [(_dishId, 1, 1.1)]);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/sales/getdishrecords?id={dish.Id}&fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<SaleViewModel>>(response);
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(0));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_ByDishId_WhenDateIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/sales/getdishrecords?id={_dishId}&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_ByDishId_WhenIdIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/sales/getdishrecords?id=Id&fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ById_WhenHaveRecord_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var sale = AndDietCokeDbContext.InsertSaleToDatabaseAndReturn(_workerId, _buyerId, dishes: [(_dishId, 5, 1.1)]);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/sales/getrecord/{sale.Id}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
AssertElement(await GetModelFromResponseAsync<SaleViewModel>(response), sale);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ById_WhenNoRecord_ShouldNotFound_Test()
|
||||
{
|
||||
//Arrange
|
||||
AndDietCokeDbContext.InsertSaleToDatabaseAndReturn(_workerId, _buyerId, dishes: [(_dishId, 5, 1.1)]);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/sales/getrecord/{Guid.NewGuid()}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ById_WhenRecordHasCanceled_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var sale = AndDietCokeDbContext.InsertSaleToDatabaseAndReturn(_workerId, _buyerId, dishes: [(_dishId, 1, 1.2)], isCancel: true);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/sales/getrecord/{sale.Id}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ById_WhenIdIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/sales/getrecord/Id");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
AndDietCokeDbContext.InsertSaleToDatabaseAndReturn(_workerId, null, dishes: [(_dishId, 5, 1.1)]);
|
||||
var saleModel = CreateModel(_workerId, _buyerId, _dishId);
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/sales/sale", MakeContent(saleModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
AssertElement(AndDietCokeDbContext.GetSalesByBuyerId(_buyerId)[0], saleModel);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenNoBuyer_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
AndDietCokeDbContext.InsertSaleToDatabaseAndReturn(_workerId, _buyerId, dishes: [(_dishId, 5, 1.1)]);
|
||||
var saleModel = CreateModel(_workerId, null, _dishId);
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/sales/sale", MakeContent(saleModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
AssertElement(AndDietCokeDbContext.GetSalesByBuyerId(null)[0], saleModel);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenDataIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var saleId = Guid.NewGuid().ToString();
|
||||
var saleModelWithIdIncorrect = new SaleBindingModel { Id = "Id", WorkerId = _workerId, BuyerId = _buyerId, DiscountType = 1, Dishes = [new OrderDishBindingModel { SaleId = saleId, DishId = _dishId, Count = 10, Price = 1.1 }] };
|
||||
var saleModelWithWorkerIdIncorrect = new SaleBindingModel { Id = saleId, WorkerId = "Id", BuyerId = _buyerId, DiscountType = 1, Dishes = [new OrderDishBindingModel { SaleId = saleId, DishId = _dishId, Count = 10, Price = 1.1 }] };
|
||||
var saleModelWithBuyerIdIncorrect = new SaleBindingModel { Id = saleId, WorkerId = _workerId, BuyerId = "Id", DiscountType = 1, Dishes = [new OrderDishBindingModel { SaleId = saleId, DishId = _dishId, Count = 10, Price = 1.1 }] };
|
||||
var saleModelWithDishesIncorrect = new SaleBindingModel { Id = saleId, WorkerId = _workerId, BuyerId = _buyerId, DiscountType = 1, Dishes = null };
|
||||
var saleModelWithDishIdIncorrect = new SaleBindingModel { Id = saleId, WorkerId = _workerId, BuyerId = _buyerId, DiscountType = 1, Dishes = [new OrderDishBindingModel { SaleId = saleId, DishId = "Id", Count = 10, Price = 1.1 }] };
|
||||
var saleModelWithCountIncorrect = new SaleBindingModel { Id = saleId, WorkerId = _workerId, BuyerId = _buyerId, DiscountType = 1, Dishes = [new OrderDishBindingModel { SaleId = saleId, DishId = _dishId, Count = -10, Price = 1.1 }] };
|
||||
var saleModelWithPriceIncorrect = new SaleBindingModel { Id = saleId, WorkerId = _workerId, BuyerId = _buyerId, DiscountType = 1, Dishes = [new OrderDishBindingModel { SaleId = saleId, DishId = _dishId, Count = 10, Price = -1.1 }] };
|
||||
//Act
|
||||
var responseWithIdIncorrect = await HttpClient.PostAsync($"/api/sales/sale", MakeContent(saleModelWithIdIncorrect));
|
||||
var responseWithWorkerIdIncorrect = await HttpClient.PostAsync($"/api/sales/sale", MakeContent(saleModelWithWorkerIdIncorrect));
|
||||
var responseWithBuyerIdIncorrect = await HttpClient.PostAsync($"/api/sales/sale", MakeContent(saleModelWithBuyerIdIncorrect));
|
||||
var responseWithDishesIncorrect = await HttpClient.PostAsync($"/api/sales/sale", MakeContent(saleModelWithDishesIncorrect));
|
||||
var responseWithDishIdIncorrect = await HttpClient.PostAsync($"/api/sales/sale", MakeContent(saleModelWithDishIdIncorrect));
|
||||
var responseWithCountIncorrect = await HttpClient.PostAsync($"/api/sales/sale", MakeContent(saleModelWithCountIncorrect));
|
||||
var responseWithPriceIncorrect = await HttpClient.PostAsync($"/api/sales/sale", MakeContent(saleModelWithPriceIncorrect));
|
||||
//Assert
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(responseWithIdIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "WorkerId is incorrect");
|
||||
Assert.That(responseWithWorkerIdIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "WorkerId is incorrect");
|
||||
Assert.That(responseWithBuyerIdIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "BuyerId is incorrect");
|
||||
Assert.That(responseWithDishesIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Dishes is incorrect");
|
||||
Assert.That(responseWithDishIdIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "DishId is incorrect");
|
||||
Assert.That(responseWithCountIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Count is incorrect");
|
||||
Assert.That(responseWithPriceIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Price is incorrect");
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenSendEmptyData_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/sales/sale", MakeContent(string.Empty));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenSendWrongFormatData_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/sales/sale", MakeContent(new { Data = "test", Position = 10 }));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Delete_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var sale = AndDietCokeDbContext.InsertSaleToDatabaseAndReturn(_workerId, _buyerId, dishes: [(_dishId, 5, 1.1)]);
|
||||
//Act
|
||||
var response = await HttpClient.DeleteAsync($"/api/sales/cancel/{sale.Id}");
|
||||
AndDietCokeDbContext.ChangeTracker.Clear();
|
||||
//Assert
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
Assert.That(AndDietCokeDbContext.GetSaleFromDatabaseById(sale.Id)!.IsCancel);
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Delete_WhenNoFoundRecord_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
AndDietCokeDbContext.InsertSaleToDatabaseAndReturn(_workerId, _buyerId, dishes: [(_dishId, 5, 1.1)]);
|
||||
//Act
|
||||
var response = await HttpClient.DeleteAsync($"/api/sales/cancel/{Guid.NewGuid()}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Delete_WhenIsCanceled_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var sale = AndDietCokeDbContext.InsertSaleToDatabaseAndReturn(_workerId, _buyerId, dishes: [(_dishId, 5, 1.1)], isCancel: true);
|
||||
//Act
|
||||
var response = await HttpClient.DeleteAsync($"/api/sales/cancel/{sale.Id}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Delete_WhenSendWrongFormatData_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.DeleteAsync($"/api/sales/cancel/id");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
private static void AssertElement(SaleViewModel? actual, Sale expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.Id, Is.EqualTo(expected.Id));
|
||||
Assert.That(actual.WorkerFIO, Is.EqualTo(expected.Worker!.FIO));
|
||||
Assert.That(actual.BuyerFIO, Is.EqualTo(expected.Buyer?.FIO));
|
||||
Assert.That(actual.IsCancel, Is.EqualTo(expected.IsCancel));
|
||||
});
|
||||
|
||||
if (expected.OrderDishes is not null)
|
||||
{
|
||||
Assert.That(actual.Dishes, Is.Not.Null);
|
||||
Assert.That(actual.Dishes, Has.Count.EqualTo(expected.OrderDishes.Count));
|
||||
for (int i = 0; i < actual.Dishes.Count; ++i)
|
||||
{
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.Dishes[i].DishName, Is.EqualTo(expected.OrderDishes[i].Dish!.DishName));
|
||||
Assert.That(actual.Dishes[i].Count, Is.EqualTo(expected.OrderDishes[i].Count));
|
||||
});
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
Assert.That(actual.Dishes, Is.Null);
|
||||
}
|
||||
}
|
||||
|
||||
private static SaleBindingModel CreateModel(string workerId, string? buyerId, string dishId, string? id = null, int count = 1, double price = 1.1)
|
||||
{
|
||||
var saleId = id ?? Guid.NewGuid().ToString();
|
||||
return new()
|
||||
{
|
||||
Id = saleId,
|
||||
WorkerId = workerId,
|
||||
BuyerId = buyerId,
|
||||
Dishes = [new OrderDishBindingModel { SaleId = saleId, DishId = dishId, Count = count, Price = price }]
|
||||
};
|
||||
}
|
||||
|
||||
private static void AssertElement(Sale? actual, SaleBindingModel expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.WorkerId, Is.EqualTo(expected.WorkerId));
|
||||
Assert.That(actual.BuyerId, Is.EqualTo(expected.BuyerId));
|
||||
Assert.That(!actual.IsCancel);
|
||||
});
|
||||
|
||||
if (expected.Dishes is not null)
|
||||
{
|
||||
Assert.That(actual.OrderDishes, Is.Not.Null);
|
||||
Assert.That(actual.OrderDishes, Has.Count.EqualTo(expected.Dishes.Count));
|
||||
for (int i = 0; i < actual.OrderDishes.Count; ++i)
|
||||
{
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.OrderDishes[i].DishId, Is.EqualTo(expected.Dishes[i].DishId));
|
||||
Assert.That(actual.OrderDishes[i].Count, Is.EqualTo(expected.Dishes[i].Count));
|
||||
Assert.That(actual.OrderDishes[i].Price, Is.EqualTo(expected.Dishes[i].Price));
|
||||
});
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
Assert.That(actual.OrderDishes, Is.Null);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,513 @@
|
||||
using AndDietCokeContracts.BindingModels;
|
||||
using AndDietCokeContracts.ViewModels;
|
||||
using AndDietCokeDatabase.Models;
|
||||
using AndDietCokeTests.Infrastructure;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace AndDietCokeTests.WebApiControllersTests;
|
||||
|
||||
[TestFixture]
|
||||
internal class WorkerControllerTests : BaseWebApiControllerTest
|
||||
{
|
||||
private Post _post;
|
||||
|
||||
[SetUp]
|
||||
public void SetUp()
|
||||
{
|
||||
_post = AndDietCokeDbContext.InsertPostToDatabaseAndReturn();
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
AndDietCokeDbContext.RemovePostsFromDatabase();
|
||||
AndDietCokeDbContext.RemoveWorkersFromDatabase();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_WhenHaveRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var worker = AndDietCokeDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 1", postId: _post.PostId)
|
||||
.AddPost(_post);
|
||||
AndDietCokeDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 2", postId: _post.PostId);
|
||||
AndDietCokeDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 3", postId: _post.PostId);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync("/api/workers/getrecords");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<WorkerViewModel>>(response);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(3));
|
||||
});
|
||||
AssertElement(data.First(x => x.Id == worker.Id), worker);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_WhenNoRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync("/api/workers/getrecords");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<WorkerViewModel>>(response);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(0));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_OnlyActual_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
AndDietCokeDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 1", postId: _post.PostId, isDeleted: true);
|
||||
AndDietCokeDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 2", postId: _post.PostId, isDeleted: false);
|
||||
AndDietCokeDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 3", postId: _post.PostId, isDeleted: false);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync("/api/workers/getrecords?includeDeleted=false");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<WorkerViewModel>>(response);
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Has.Count.EqualTo(2));
|
||||
Assert.That(data.All(x => !x.IsDeleted));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_IncludeNoActual_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
AndDietCokeDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 1", postId: _post.PostId, isDeleted: true);
|
||||
AndDietCokeDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 2", postId: _post.PostId, isDeleted: true);
|
||||
AndDietCokeDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 3", postId: _post.PostId, isDeleted: false);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync("/api/workers/getrecords?includeDeleted=true");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<WorkerViewModel>>(response);
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Has.Count.EqualTo(3));
|
||||
Assert.That(data.Any(x => x.IsDeleted));
|
||||
Assert.That(data.Any(x => !x.IsDeleted));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_ByPostId_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
AndDietCokeDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 1", postId: _post.PostId);
|
||||
AndDietCokeDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 2", postId: _post.PostId);
|
||||
AndDietCokeDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 3", postId: _post.PostId, isDeleted: true);
|
||||
AndDietCokeDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 4");
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/workers/getpostrecords?id={_post.PostId}&includeDeleted=true");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<WorkerViewModel>>(response);
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Has.Count.EqualTo(3));
|
||||
Assert.That(data.All(x => x.PostId == _post.PostId));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_ByPostId_WhenNoRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
AndDietCokeDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 1", postId: _post.PostId);
|
||||
AndDietCokeDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 4");
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/workers/getpostrecords?id={Guid.NewGuid()}&includeDeleted=true");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<WorkerViewModel>>(response);
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(0));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_ByPostId_WhenIdIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/workers/getpostrecords?id=id&includeDeleted=true");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_ByBirthDate_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
AndDietCokeDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 1", birthDate: DateTime.UtcNow.AddYears(-25));
|
||||
AndDietCokeDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 2", birthDate: DateTime.UtcNow.AddYears(-21));
|
||||
AndDietCokeDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 3", birthDate: DateTime.UtcNow.AddYears(-20), isDeleted: true);
|
||||
AndDietCokeDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 4", birthDate: DateTime.UtcNow.AddYears(-19));
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/workers/getbirthdaterecords?fromDate={DateTime.UtcNow.AddYears(-21).AddMinutes(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddYears(-20).AddMinutes(1):MM/dd/yyyy HH:mm:ss}&includeDeleted=true");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<WorkerViewModel>>(response);
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Has.Count.EqualTo(2));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_ByBirthDate_WhenDateIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/workers/getbirthdaterecords?fromDate={DateTime.UtcNow.AddMinutes(1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddMinutes(-1):MM/dd/yyyy HH:mm:ss}&includeDeleted=true");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_ByEmploymentDate_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
AndDietCokeDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 1", employmentDate: DateTime.UtcNow.AddDays(-2));
|
||||
AndDietCokeDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 2", employmentDate: DateTime.UtcNow.AddDays(-1));
|
||||
AndDietCokeDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 3", employmentDate: DateTime.UtcNow.AddDays(1), isDeleted: true);
|
||||
AndDietCokeDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 4", employmentDate: DateTime.UtcNow.AddDays(2));
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/workers/getemploymentrecords?fromDate={DateTime.UtcNow.AddDays(-1).AddMinutes(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1).AddMinutes(1):MM/dd/yyyy HH:mm:ss}&includeDeleted=true");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<WorkerViewModel>>(response);
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Has.Count.EqualTo(2));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_ByEmploymentDate_WhenDateIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/workers/getemploymentrecords?fromDate={DateTime.UtcNow.AddMinutes(1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddMinutes(-1):MM/dd/yyyy HH:mm:ss}&includeDeleted=true");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ById_WhenHaveRecord_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var worker = AndDietCokeDbContext.InsertWorkerToDatabaseAndReturn(postId: _post.PostId).AddPost(_post);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/workers/getrecord/{worker.Id}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
AssertElement(await GetModelFromResponseAsync<WorkerViewModel>(response), worker);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ById_WhenNoRecord_ShouldNotFound_Test()
|
||||
{
|
||||
//Arrange
|
||||
AndDietCokeDbContext.InsertWorkerToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/workers/getrecord/{Guid.NewGuid()}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ById_WhenRecordWasDeleted_ShouldNotFound_Test()
|
||||
{
|
||||
//Arrange
|
||||
var worker = AndDietCokeDbContext.InsertWorkerToDatabaseAndReturn(postId: _post.PostId, isDeleted: true);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/workers/getrecord/{worker.Id}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ByFIO_WhenHaveRecord_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var worker = AndDietCokeDbContext.InsertWorkerToDatabaseAndReturn(postId: _post.PostId).AddPost(_post);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/workers/getrecord/{worker.FIO}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
AssertElement(await GetModelFromResponseAsync<WorkerViewModel>(response), worker);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ByFIO_WhenNoRecord_ShouldNotFound_Test()
|
||||
{
|
||||
//Arrange
|
||||
AndDietCokeDbContext.InsertWorkerToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/workers/getrecord/New%20Fio");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ByFIO_WhenRecordWasDeleted_ShouldNotFound_Test()
|
||||
{
|
||||
//Arrange
|
||||
var worker = AndDietCokeDbContext.InsertWorkerToDatabaseAndReturn(postId: _post.PostId, isDeleted: true);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/workers/getrecord/{worker.FIO}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
AndDietCokeDbContext.InsertWorkerToDatabaseAndReturn();
|
||||
var workerModel = CreateModel(_post.Id);
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/workers/register", MakeContent(workerModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
AssertElement(AndDietCokeDbContext.GetWorkerFromDatabaseById(workerModel.Id!), workerModel);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenHaveRecordWithSameId_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var workerModel = CreateModel(_post.Id);
|
||||
AndDietCokeDbContext.InsertWorkerToDatabaseAndReturn(workerModel.Id);
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/workers/register", MakeContent(workerModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenDataIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var workerModelWithIdIncorrect = new WorkerBindingModel { Id = "Id", FIO = "fio", BirthDate = DateTime.UtcNow.AddYears(-22), EmploymentDate = DateTime.UtcNow.AddDays(-5), PostId = _post.Id };
|
||||
var workerModelWithFioIncorrect = new WorkerBindingModel { Id = Guid.NewGuid().ToString(), FIO = string.Empty, BirthDate = DateTime.UtcNow.AddYears(-22), EmploymentDate = DateTime.UtcNow.AddDays(-5), PostId = _post.Id };
|
||||
var workerModelWithPostIdIncorrect = new WorkerBindingModel { Id = Guid.NewGuid().ToString(), FIO = "fio", BirthDate = DateTime.UtcNow.AddYears(-22), EmploymentDate = DateTime.UtcNow.AddDays(-5), PostId = "Id" };
|
||||
var workerModelWithBirthDateIncorrect = new WorkerBindingModel { Id = Guid.NewGuid().ToString(), FIO = "fio", BirthDate = DateTime.UtcNow.AddYears(-15), EmploymentDate = DateTime.UtcNow.AddDays(-5), PostId = _post.Id };
|
||||
//Act
|
||||
var responseWithIdIncorrect = await HttpClient.PostAsync($"/api/workers/register", MakeContent(workerModelWithIdIncorrect));
|
||||
var responseWithFioIncorrect = await HttpClient.PostAsync($"/api/workers/register", MakeContent(workerModelWithFioIncorrect));
|
||||
var responseWithPostIdIncorrect = await HttpClient.PostAsync($"/api/workers/register", MakeContent(workerModelWithPostIdIncorrect));
|
||||
var responseWithBirthDateIncorrect = await HttpClient.PostAsync($"/api/workers/register", MakeContent(workerModelWithBirthDateIncorrect));
|
||||
//Assert
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(responseWithIdIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Id is incorrect");
|
||||
Assert.That(responseWithFioIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Fio is incorrect");
|
||||
Assert.That(responseWithPostIdIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "PostId is incorrect");
|
||||
Assert.That(responseWithBirthDateIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "BirthDate is incorrect");
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenSendEmptyData_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/workers/register", MakeContent(string.Empty));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenSendWrongFormatData_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/workers/register", MakeContent(new { Data = "test", Position = 10 }));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var workerModel = CreateModel(_post.Id);
|
||||
AndDietCokeDbContext.InsertWorkerToDatabaseAndReturn(workerModel.Id);
|
||||
//Act
|
||||
var response = await HttpClient.PutAsync($"/api/workers/changeinfo", MakeContent(workerModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
AndDietCokeDbContext.ChangeTracker.Clear();
|
||||
AssertElement(AndDietCokeDbContext.GetWorkerFromDatabaseById(workerModel.Id!), workerModel);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WhenNoFoundRecord_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var workerModel = CreateModel(_post.Id, fio: "new fio");
|
||||
AndDietCokeDbContext.InsertWorkerToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.PutAsync($"/api/workers/changeinfo", MakeContent(workerModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WhenRecordWasDeleted_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var workerModel = CreateModel(_post.Id, fio: "new fio");
|
||||
AndDietCokeDbContext.InsertWorkerToDatabaseAndReturn(workerModel.Id, isDeleted: true);
|
||||
//Act
|
||||
var response = await HttpClient.PutAsync($"/api/workers/changeinfo", MakeContent(workerModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WhenDataIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var workerModelWithIdIncorrect = new WorkerBindingModel { Id = "Id", FIO = "fio", BirthDate = DateTime.UtcNow.AddYears(-22), EmploymentDate = DateTime.UtcNow.AddDays(-5), PostId = _post.Id };
|
||||
var workerModelWithFioIncorrect = new WorkerBindingModel { Id = Guid.NewGuid().ToString(), FIO = string.Empty, BirthDate = DateTime.UtcNow.AddYears(-22), EmploymentDate = DateTime.UtcNow.AddDays(-5), PostId = _post.Id };
|
||||
var workerModelWithPostIdIncorrect = new WorkerBindingModel { Id = Guid.NewGuid().ToString(), FIO = "fio", BirthDate = DateTime.UtcNow.AddYears(-22), EmploymentDate = DateTime.UtcNow.AddDays(-5), PostId = "Id" };
|
||||
var workerModelWithBirthDateIncorrect = new WorkerBindingModel { Id = Guid.NewGuid().ToString(), FIO = "fio", BirthDate = DateTime.UtcNow.AddYears(-15), EmploymentDate = DateTime.UtcNow.AddDays(-5), PostId = _post.Id };
|
||||
//Act
|
||||
var responseWithIdIncorrect = await HttpClient.PutAsync($"/api/workers/changeinfo", MakeContent(workerModelWithIdIncorrect));
|
||||
var responseWithFioIncorrect = await HttpClient.PutAsync($"/api/workers/changeinfo", MakeContent(workerModelWithFioIncorrect));
|
||||
var responseWithPostIdIncorrect = await HttpClient.PutAsync($"/api/workers/changeinfo", MakeContent(workerModelWithPostIdIncorrect));
|
||||
var responseWithBirthDateIncorrect = await HttpClient.PutAsync($"/api/workers/changeinfo", MakeContent(workerModelWithBirthDateIncorrect));
|
||||
//Assert
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(responseWithIdIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Id is incorrect");
|
||||
Assert.That(responseWithFioIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Fio is incorrect");
|
||||
Assert.That(responseWithPostIdIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "PostId is incorrect");
|
||||
Assert.That(responseWithBirthDateIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "BirthDate is incorrect");
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WhenSendEmptyData_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.PutAsync($"/api/workers/changeinfo", MakeContent(string.Empty));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WhenSendWrongFormatData_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.PutAsync($"/api/workers/changeinfo", MakeContent(new { Data = "test", Position = 10 }));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Delete_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var workerId = Guid.NewGuid().ToString();
|
||||
AndDietCokeDbContext.InsertWorkerToDatabaseAndReturn(workerId);
|
||||
//Act
|
||||
var response = await HttpClient.DeleteAsync($"/api/workers/delete/{workerId}");
|
||||
AndDietCokeDbContext.ChangeTracker.Clear();
|
||||
//Assert
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
Assert.That(AndDietCokeDbContext.GetWorkerFromDatabaseById(workerId)!.IsDeleted);
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Delete_WhenNoFoundRecord_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
AndDietCokeDbContext.InsertWorkerToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.DeleteAsync($"/api/workers/delete/{Guid.NewGuid()}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Delete_WhenSendWrongFormatData_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.DeleteAsync($"/api/workers/delete/id");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Delete_WhenRecordWasDeleted_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var workerId = AndDietCokeDbContext.InsertWorkerToDatabaseAndReturn(isDeleted: true).Id;
|
||||
//Act
|
||||
var response = await HttpClient.DeleteAsync($"/api/workers/delete/{workerId}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
private static void AssertElement(WorkerViewModel? actual, Worker expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.Id, Is.EqualTo(expected.Id));
|
||||
Assert.That(actual.PostId, Is.EqualTo(expected.PostId));
|
||||
Assert.That(actual.PostName, Is.EqualTo(expected.Post!.PostName));
|
||||
Assert.That(actual.FIO, Is.EqualTo(expected.FIO));
|
||||
Assert.That(actual.BirthDate.ToString(), Is.EqualTo(expected.BirthDate.ToString()));
|
||||
Assert.That(actual.EmploymentDate.ToString(), Is.EqualTo(expected.EmploymentDate.ToString()));
|
||||
Assert.That(actual.IsDeleted, Is.EqualTo(expected.IsDeleted));
|
||||
});
|
||||
}
|
||||
|
||||
private static WorkerBindingModel CreateModel(string postId, string? id = null, string fio = "fio", DateTime? birthDate = null, DateTime? employmentDate = null)
|
||||
{
|
||||
return new()
|
||||
{
|
||||
Id = id ?? Guid.NewGuid().ToString(),
|
||||
FIO = fio,
|
||||
BirthDate = birthDate ?? DateTime.UtcNow.AddYears(-22),
|
||||
EmploymentDate = employmentDate ?? DateTime.UtcNow.AddDays(-5),
|
||||
PostId = postId
|
||||
};
|
||||
}
|
||||
|
||||
private static void AssertElement(Worker? actual, WorkerBindingModel expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.Id, Is.EqualTo(expected.Id));
|
||||
Assert.That(actual.PostId, Is.EqualTo(expected.PostId));
|
||||
Assert.That(actual.FIO, Is.EqualTo(expected.FIO));
|
||||
Assert.That(actual.BirthDate.ToString(), Is.EqualTo(expected.BirthDate.ToString()));
|
||||
Assert.That(actual.EmploymentDate.ToString(), Is.EqualTo(expected.EmploymentDate.ToString()));
|
||||
Assert.That(!actual.IsDeleted);
|
||||
});
|
||||
}
|
||||
}
|
||||
24
AndDietCokeProject/AndDietCokeTests/appsettings.json
Normal file
24
AndDietCokeProject/AndDietCokeTests/appsettings.json
Normal file
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
}
|
||||
},
|
||||
"Serilog": {
|
||||
"Using": [ "Serilog.Sinks.File" ],
|
||||
"MinimumLevel": {
|
||||
"Default": "Information"
|
||||
},
|
||||
"WriteTo": [
|
||||
{
|
||||
"Name": "File",
|
||||
"Args": {
|
||||
"path": "../logs/anddietcoke-.log",
|
||||
"rollingInterval": "Day",
|
||||
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} {CorrelationId} {Level:u3} {Username} {Message:lj}{Exception}{NewLine}"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
189
AndDietCokeProject/AndDietCokeWebApi/Adapters/BuyerAdapter.cs
Normal file
189
AndDietCokeProject/AndDietCokeWebApi/Adapters/BuyerAdapter.cs
Normal file
@@ -0,0 +1,189 @@
|
||||
using AndDietCokeContracts.AdapterContracts.OperationResponses;
|
||||
using AndDietCokeContracts.AdapterContracts;
|
||||
using AndDietCokeContracts.BindingModels;
|
||||
using AndDietCokeContracts.BisnessLogicsContracts;
|
||||
using AndDietCokeContracts.DataModels;
|
||||
using AndDietCokeContracts.Exceptions;
|
||||
using AndDietCokeContracts.ViewModels;
|
||||
using AutoMapper;
|
||||
|
||||
namespace AndDietCokeWebApi.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);
|
||||
}
|
||||
}
|
||||
}
|
||||
233
AndDietCokeProject/AndDietCokeWebApi/Adapters/DishAdapter.cs
Normal file
233
AndDietCokeProject/AndDietCokeWebApi/Adapters/DishAdapter.cs
Normal file
@@ -0,0 +1,233 @@
|
||||
using AndDietCokeContracts.AdapterContracts;
|
||||
using AndDietCokeContracts.AdapterContracts.OperationResponses;
|
||||
using AndDietCokeContracts.BindingModels;
|
||||
using AndDietCokeContracts.BisnessLogicsContracts;
|
||||
using AndDietCokeContracts.DataModels;
|
||||
using AndDietCokeContracts.Exceptions;
|
||||
using AndDietCokeContracts.ViewModels;
|
||||
using AutoMapper;
|
||||
|
||||
namespace AndDietCokeWebApi.Adapters;
|
||||
|
||||
public class DishAdapter : IDishAdapter
|
||||
{
|
||||
private readonly IDishBusinessLogicContract _dishBusinessLogicContract;
|
||||
|
||||
private readonly ILogger _logger;
|
||||
|
||||
private readonly Mapper _mapper;
|
||||
|
||||
public DishAdapter(IDishBusinessLogicContract dishBusinessLogicContract, ILogger<DishAdapter> logger)
|
||||
{
|
||||
_dishBusinessLogicContract = dishBusinessLogicContract;
|
||||
_logger = logger;
|
||||
var config = new MapperConfiguration(cfg =>
|
||||
{
|
||||
cfg.CreateMap<DishBindingModel, DishDataModel>();
|
||||
cfg.CreateMap<DishDataModel, DishViewModel>();
|
||||
cfg.CreateMap<DishHistoryDataModel, DishHistoryViewModel>();
|
||||
});
|
||||
_mapper = new Mapper(config);
|
||||
}
|
||||
|
||||
public DishOperationResponse GetList(bool includeDeleted)
|
||||
{
|
||||
try
|
||||
{
|
||||
return DishOperationResponse.OK([.. _dishBusinessLogicContract.GetAllDishes(!includeDeleted).Select(x => _mapper.Map<DishViewModel>(x))]);
|
||||
}
|
||||
catch (NullListException)
|
||||
{
|
||||
_logger.LogError("NullListException");
|
||||
return DishOperationResponse.NotFound("The list is not initialized");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return DishOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return DishOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public DishOperationResponse GetHistory(string id)
|
||||
{
|
||||
try
|
||||
{
|
||||
return DishOperationResponse.OK([.. _dishBusinessLogicContract.GetDishHistoryByDish(id).Select(x => _mapper.Map<DishHistoryViewModel>(x))]);
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return DishOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (NullListException)
|
||||
{
|
||||
_logger.LogError("NullListException");
|
||||
return DishOperationResponse.NotFound("The list is not initialized");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return DishOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return DishOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public DishOperationResponse GetElement(string data)
|
||||
{
|
||||
try
|
||||
{
|
||||
return DishOperationResponse.OK(_mapper.Map<DishViewModel>(_dishBusinessLogicContract.GetDishByData(data)));
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return DishOperationResponse.BadRequest("Data is empty");
|
||||
}
|
||||
catch (ElementNotFoundException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementNotFoundException");
|
||||
return DishOperationResponse.NotFound($"Not found element by data {data}");
|
||||
}
|
||||
catch (ElementDeletedException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementDeletedException");
|
||||
return DishOperationResponse.BadRequest($"Element by data: {data} was deleted");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return DishOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return DishOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public DishOperationResponse RegisterDish(DishBindingModel dishModel)
|
||||
{
|
||||
try
|
||||
{
|
||||
_dishBusinessLogicContract.InsertDish(_mapper.Map<DishDataModel>(dishModel));
|
||||
return DishOperationResponse.NoContent();
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return DishOperationResponse.BadRequest("Data is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return DishOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (ElementExistsException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementExistsException");
|
||||
return DishOperationResponse.BadRequest(ex.Message);
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return DishOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return DishOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public DishOperationResponse ChangeDishInfo(DishBindingModel dishModel)
|
||||
{
|
||||
try
|
||||
{
|
||||
_dishBusinessLogicContract.UpdateDish(_mapper.Map<DishDataModel>(dishModel));
|
||||
return DishOperationResponse.NoContent();
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return DishOperationResponse.BadRequest("Data is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return DishOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (ElementNotFoundException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementNotFoundException");
|
||||
return DishOperationResponse.BadRequest($"Not found element by Id {dishModel.Id}");
|
||||
}
|
||||
catch (ElementExistsException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementExistsException");
|
||||
return DishOperationResponse.BadRequest(ex.Message);
|
||||
}
|
||||
catch (ElementDeletedException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementDeletedException");
|
||||
return DishOperationResponse.BadRequest($"Element by id: {dishModel.Id} was deleted");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return DishOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return DishOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public DishOperationResponse RemoveDish(string id)
|
||||
{
|
||||
try
|
||||
{
|
||||
_dishBusinessLogicContract.DeleteDish(id);
|
||||
return DishOperationResponse.NoContent();
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return DishOperationResponse.BadRequest("Id is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return DishOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (ElementNotFoundException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementNotFoundException");
|
||||
return DishOperationResponse.BadRequest($"Not found element by id: {id}");
|
||||
}
|
||||
catch (ElementDeletedException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementDeletedException");
|
||||
return DishOperationResponse.BadRequest($"Element by id: {id} was deleted");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return DishOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return DishOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
266
AndDietCokeProject/AndDietCokeWebApi/Adapters/PostAdapter.cs
Normal file
266
AndDietCokeProject/AndDietCokeWebApi/Adapters/PostAdapter.cs
Normal file
@@ -0,0 +1,266 @@
|
||||
using AndDietCokeContracts.AdapterContracts.OperationResponses;
|
||||
using AndDietCokeContracts.AdapterContracts;
|
||||
using AndDietCokeContracts.BindingModels;
|
||||
using AndDietCokeContracts.BisnessLogicsContracts;
|
||||
using AndDietCokeContracts.DataModels;
|
||||
using AndDietCokeContracts.Exceptions;
|
||||
using AndDietCokeContracts.ViewModels;
|
||||
using AutoMapper;
|
||||
|
||||
namespace AndDietCokeWebApi.Adapters;
|
||||
|
||||
public class PostAdapter : IPostAdapter
|
||||
{
|
||||
private readonly IPostBusinessLogicContract _postBusinessLogicContract;
|
||||
|
||||
private readonly ILogger _logger;
|
||||
|
||||
private readonly Mapper _mapper;
|
||||
|
||||
public PostAdapter(IPostBusinessLogicContract postBusinessLogicContract, ILogger<PostAdapter> logger)
|
||||
{
|
||||
_postBusinessLogicContract = postBusinessLogicContract;
|
||||
_logger = logger;
|
||||
var config = new MapperConfiguration(cfg =>
|
||||
{
|
||||
cfg.CreateMap<PostBindingModel, PostDataModel>();
|
||||
cfg.CreateMap<PostDataModel, PostViewModel>();
|
||||
});
|
||||
_mapper = new Mapper(config);
|
||||
}
|
||||
|
||||
public PostOperationResponse GetList()
|
||||
{
|
||||
try
|
||||
{
|
||||
return PostOperationResponse.OK([.. _postBusinessLogicContract.GetAllPosts(true).Select(x => _mapper.Map<PostViewModel>(x))]);
|
||||
}
|
||||
catch (NullListException)
|
||||
{
|
||||
_logger.LogError("NullListException");
|
||||
return PostOperationResponse.NotFound("The list is not initialized");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return PostOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return PostOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public PostOperationResponse GetHistory(string id)
|
||||
{
|
||||
try
|
||||
{
|
||||
return PostOperationResponse.OK([.. _postBusinessLogicContract.GetAllDataOfPost(id).Select(x => _mapper.Map<PostViewModel>(x))]);
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return PostOperationResponse.BadRequest("Data is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return PostOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return PostOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return PostOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public PostOperationResponse GetElement(string data)
|
||||
{
|
||||
try
|
||||
{
|
||||
return PostOperationResponse.OK(_mapper.Map<PostViewModel>(_postBusinessLogicContract.GetPostByData(data)));
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return PostOperationResponse.BadRequest("Data is empty");
|
||||
}
|
||||
catch (ElementNotFoundException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementNotFoundException");
|
||||
return PostOperationResponse.NotFound($"Not found element by data {data}");
|
||||
}
|
||||
catch (ElementDeletedException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementDeletedException");
|
||||
return PostOperationResponse.BadRequest($"Element by data: {data} was deleted");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return PostOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return PostOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public PostOperationResponse RegisterPost(PostBindingModel postModel)
|
||||
{
|
||||
try
|
||||
{
|
||||
_postBusinessLogicContract.InsertPost(_mapper.Map<PostDataModel>(postModel));
|
||||
return PostOperationResponse.NoContent();
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return PostOperationResponse.BadRequest("Data is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return PostOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (ElementExistsException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementExistsException");
|
||||
return PostOperationResponse.BadRequest(ex.Message);
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return PostOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return PostOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public PostOperationResponse ChangePostInfo(PostBindingModel postModel)
|
||||
{
|
||||
try
|
||||
{
|
||||
_postBusinessLogicContract.UpdatePost(_mapper.Map<PostDataModel>(postModel));
|
||||
return PostOperationResponse.NoContent();
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return PostOperationResponse.BadRequest("Data is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return PostOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (ElementNotFoundException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementNotFoundException");
|
||||
return PostOperationResponse.BadRequest($"Not found element by Id {postModel.Id}");
|
||||
}
|
||||
catch (ElementExistsException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementExistsException");
|
||||
return PostOperationResponse.BadRequest(ex.Message);
|
||||
}
|
||||
catch (ElementDeletedException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementDeletedException");
|
||||
return PostOperationResponse.BadRequest($"Element by id: {postModel.Id} was deleted");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return PostOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return PostOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public PostOperationResponse RemovePost(string id)
|
||||
{
|
||||
try
|
||||
{
|
||||
_postBusinessLogicContract.DeletePost(id);
|
||||
return PostOperationResponse.NoContent();
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return PostOperationResponse.BadRequest("Id is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return PostOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (ElementNotFoundException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementNotFoundException");
|
||||
return PostOperationResponse.BadRequest($"Not found element by id: {id}");
|
||||
}
|
||||
catch (ElementDeletedException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementDeletedException");
|
||||
return PostOperationResponse.BadRequest($"Element by id: {id} was deleted");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return PostOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return PostOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public PostOperationResponse RestorePost(string id)
|
||||
{
|
||||
try
|
||||
{
|
||||
_postBusinessLogicContract.RestorePost(id);
|
||||
return PostOperationResponse.NoContent();
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return PostOperationResponse.BadRequest("Id is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return PostOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (ElementNotFoundException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementNotFoundException");
|
||||
return PostOperationResponse.BadRequest($"Not found element by id: {id}");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return PostOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return PostOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
119
AndDietCokeProject/AndDietCokeWebApi/Adapters/SalaryAdapter.cs
Normal file
119
AndDietCokeProject/AndDietCokeWebApi/Adapters/SalaryAdapter.cs
Normal file
@@ -0,0 +1,119 @@
|
||||
using AndDietCokeContracts.AdapterContracts;
|
||||
using AndDietCokeContracts.AdapterContracts.OperationResponses;
|
||||
using AndDietCokeContracts.BisnessLogicsContracts;
|
||||
using AndDietCokeContracts.DataModels;
|
||||
using AndDietCokeContracts.Exceptions;
|
||||
using AndDietCokeContracts.ViewModels;
|
||||
using AutoMapper;
|
||||
|
||||
namespace AndDietCokeWebApi.Adapters;
|
||||
|
||||
public class SalaryAdapter : ISalaryAdapter
|
||||
{
|
||||
private readonly ISalaryBusinessLogicContract _salaryBusinessLogicContract;
|
||||
|
||||
private readonly ILogger _logger;
|
||||
|
||||
private readonly Mapper _mapper;
|
||||
|
||||
public SalaryAdapter(ISalaryBusinessLogicContract salaryBusinessLogicContract, ILogger<SalaryAdapter> logger)
|
||||
{
|
||||
_salaryBusinessLogicContract = salaryBusinessLogicContract;
|
||||
_logger = logger;
|
||||
var config = new MapperConfiguration(cfg =>
|
||||
{
|
||||
cfg.CreateMap<SalaryDataModel, SalaryViewModel>();
|
||||
});
|
||||
_mapper = new Mapper(config);
|
||||
}
|
||||
|
||||
public SalaryOperationResponse GetListByPeriod(DateTime fromDate, DateTime toDate)
|
||||
{
|
||||
try
|
||||
{
|
||||
return SalaryOperationResponse.OK([.. _salaryBusinessLogicContract.GetAllSalariesByPeriod(fromDate, toDate).Select(x => _mapper.Map<SalaryViewModel>(x))]);
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return SalaryOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (IncorrectDatesException ex)
|
||||
{
|
||||
_logger.LogError(ex, "IncorrectDatesException");
|
||||
return SalaryOperationResponse.BadRequest($"Incorrect dates: {ex.Message}");
|
||||
}
|
||||
catch (NullListException)
|
||||
{
|
||||
_logger.LogError("NullListException");
|
||||
return SalaryOperationResponse.NotFound("The list is not initialized");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return SalaryOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return SalaryOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public SalaryOperationResponse GetListByPeriodByEmployee(DateTime fromDate, DateTime toDate, string workerId)
|
||||
{
|
||||
try
|
||||
{
|
||||
return SalaryOperationResponse.OK([.. _salaryBusinessLogicContract.GetAllSalariesByPeriodByWorker(fromDate, toDate, workerId).Select(x => _mapper.Map<SalaryViewModel>(x))]);
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return SalaryOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (IncorrectDatesException ex)
|
||||
{
|
||||
_logger.LogError(ex, "IncorrectDatesException");
|
||||
return SalaryOperationResponse.BadRequest($"Incorrect dates: {ex.Message}");
|
||||
}
|
||||
catch (NullListException)
|
||||
{
|
||||
_logger.LogError("NullListException");
|
||||
return SalaryOperationResponse.NotFound("The list is not initialized");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return SalaryOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return SalaryOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public SalaryOperationResponse CalculateSalary(DateTime date)
|
||||
{
|
||||
try
|
||||
{
|
||||
_salaryBusinessLogicContract.CalculateSalaryByMounth(date);
|
||||
return SalaryOperationResponse.NoContent();
|
||||
}
|
||||
catch (NullListException)
|
||||
{
|
||||
_logger.LogError("NullListException");
|
||||
return SalaryOperationResponse.NotFound("The list is not initialized");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return SalaryOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return SalaryOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
262
AndDietCokeProject/AndDietCokeWebApi/Adapters/SaleAdapter.cs
Normal file
262
AndDietCokeProject/AndDietCokeWebApi/Adapters/SaleAdapter.cs
Normal file
@@ -0,0 +1,262 @@
|
||||
using AndDietCokeContracts.AdapterContracts;
|
||||
using AndDietCokeContracts.AdapterContracts.OperationResponses;
|
||||
using AndDietCokeContracts.BindingModels;
|
||||
using AndDietCokeContracts.BisnessLogicsContracts;
|
||||
using AndDietCokeContracts.DataModels;
|
||||
using AndDietCokeContracts.Exceptions;
|
||||
using AndDietCokeContracts.ViewModels;
|
||||
using AutoMapper;
|
||||
|
||||
namespace AndDietCokeWebApi.Adapters;
|
||||
|
||||
public class SaleAdapter : ISaleAdapter
|
||||
{
|
||||
private readonly ISaleBusinessLogicContract _saleBusinessLogicContract;
|
||||
|
||||
private readonly ILogger _logger;
|
||||
|
||||
private readonly Mapper _mapper;
|
||||
|
||||
public SaleAdapter(ISaleBusinessLogicContract saleBusinessLogicContract, ILogger<SaleAdapter> logger)
|
||||
{
|
||||
_saleBusinessLogicContract = saleBusinessLogicContract;
|
||||
_logger = logger;
|
||||
var config = new MapperConfiguration(cfg =>
|
||||
{
|
||||
cfg.CreateMap<SaleBindingModel, SaleDataModel>();
|
||||
cfg.CreateMap<SaleDataModel, SaleViewModel>();
|
||||
cfg.CreateMap<OrderDishBindingModel, OrderDishDataModel>();
|
||||
cfg.CreateMap<OrderDishDataModel, OrderDishViewModel>();
|
||||
});
|
||||
_mapper = new Mapper(config);
|
||||
}
|
||||
|
||||
public SaleOperationResponse GetList(DateTime fromDate, DateTime toDate)
|
||||
{
|
||||
try
|
||||
{
|
||||
return SaleOperationResponse.OK([.. _saleBusinessLogicContract.GetAllSalesByPeriod(fromDate, toDate).Select(x => _mapper.Map<SaleViewModel>(x))]);
|
||||
}
|
||||
catch (IncorrectDatesException ex)
|
||||
{
|
||||
_logger.LogError(ex, "IncorrectDatesException");
|
||||
return SaleOperationResponse.BadRequest($"Incorrect dates: {ex.Message}");
|
||||
}
|
||||
catch (NullListException)
|
||||
{
|
||||
_logger.LogError("NullListException");
|
||||
return SaleOperationResponse.NotFound("The list is not initialized");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return SaleOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return SaleOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public SaleOperationResponse GetWorkerList(string id, DateTime fromDate, DateTime toDate)
|
||||
{
|
||||
try
|
||||
{
|
||||
return SaleOperationResponse.OK([.. _saleBusinessLogicContract.GetAllSalesByWorkerByPeriod(id, fromDate, toDate).Select(x => _mapper.Map<SaleViewModel>(x))]);
|
||||
}
|
||||
catch (IncorrectDatesException ex)
|
||||
{
|
||||
_logger.LogError(ex, "IncorrectDatesException");
|
||||
return SaleOperationResponse.BadRequest($"Incorrect dates: {ex.Message}");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return SaleOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (NullListException)
|
||||
{
|
||||
_logger.LogError("NullListException");
|
||||
return SaleOperationResponse.NotFound("The list is not initialized");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return SaleOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return SaleOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public SaleOperationResponse GetBuyerList(string id, DateTime fromDate, DateTime toDate)
|
||||
{
|
||||
try
|
||||
{
|
||||
return SaleOperationResponse.OK([.. _saleBusinessLogicContract.GetAllSalesByBuyerByPeriod(id, fromDate, toDate).Select(x => _mapper.Map<SaleViewModel>(x))]);
|
||||
}
|
||||
catch (IncorrectDatesException ex)
|
||||
{
|
||||
_logger.LogError(ex, "IncorrectDatesException");
|
||||
return SaleOperationResponse.BadRequest($"Incorrect dates: {ex.Message}");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return SaleOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (NullListException)
|
||||
{
|
||||
_logger.LogError("NullListException");
|
||||
return SaleOperationResponse.NotFound("The list is not initialized");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return SaleOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return SaleOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public SaleOperationResponse GetDishList(string id, DateTime fromDate, DateTime toDate)
|
||||
{
|
||||
try
|
||||
{
|
||||
return SaleOperationResponse.OK([.. _saleBusinessLogicContract.GetAllSalesByDishByPeriod(id, fromDate, toDate).Select(x => _mapper.Map<SaleViewModel>(x))]);
|
||||
}
|
||||
catch (IncorrectDatesException ex)
|
||||
{
|
||||
_logger.LogError(ex, "IncorrectDatesException");
|
||||
return SaleOperationResponse.BadRequest($"Incorrect dates: {ex.Message}");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return SaleOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (NullListException)
|
||||
{
|
||||
_logger.LogError("NullListException");
|
||||
return SaleOperationResponse.NotFound("The list is not initialized");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return SaleOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return SaleOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public SaleOperationResponse GetElement(string id)
|
||||
{
|
||||
try
|
||||
{
|
||||
return SaleOperationResponse.OK(_mapper.Map<SaleViewModel>(_saleBusinessLogicContract.GetSaleByData(id)));
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return SaleOperationResponse.BadRequest("Data is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return SaleOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (ElementNotFoundException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementNotFoundException");
|
||||
return SaleOperationResponse.NotFound($"Not found element by data {id}");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return SaleOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return SaleOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public SaleOperationResponse MakeSale(SaleBindingModel saleModel)
|
||||
{
|
||||
try
|
||||
{
|
||||
var data = _mapper.Map<SaleDataModel>(saleModel);
|
||||
_saleBusinessLogicContract.InsertSale(_mapper.Map<SaleDataModel>(saleModel));
|
||||
return SaleOperationResponse.NoContent();
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return SaleOperationResponse.BadRequest("Data is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return SaleOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return SaleOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return SaleOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public SaleOperationResponse CancelSale(string id)
|
||||
{
|
||||
try
|
||||
{
|
||||
_saleBusinessLogicContract.CancelSale(id);
|
||||
return SaleOperationResponse.NoContent();
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return SaleOperationResponse.BadRequest("Id is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return SaleOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (ElementNotFoundException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementNotFoundException");
|
||||
return SaleOperationResponse.BadRequest($"Not found element by id: {id}");
|
||||
}
|
||||
catch (ElementDeletedException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementDeletedException");
|
||||
return SaleOperationResponse.BadRequest($"Element by id: {id} was deleted");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return SaleOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return SaleOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
278
AndDietCokeProject/AndDietCokeWebApi/Adapters/WorkerAdapter.cs
Normal file
278
AndDietCokeProject/AndDietCokeWebApi/Adapters/WorkerAdapter.cs
Normal file
@@ -0,0 +1,278 @@
|
||||
using AndDietCokeContracts.AdapterContracts.OperationResponses;
|
||||
using AndDietCokeContracts.AdapterContracts;
|
||||
using AndDietCokeContracts.BindingModels;
|
||||
using AndDietCokeContracts.BisnessLogicsContracts;
|
||||
using AndDietCokeContracts.DataModels;
|
||||
using AndDietCokeContracts.Exceptions;
|
||||
using AndDietCokeContracts.ViewModels;
|
||||
using AutoMapper;
|
||||
|
||||
namespace AndDietCokeWebApi.Adapters;
|
||||
|
||||
public class WorkerAdapter : IWorkerAdapter
|
||||
{
|
||||
private readonly IWorkerBusinessLogicContract _buyerBusinessLogicContract;
|
||||
|
||||
private readonly ILogger _logger;
|
||||
|
||||
private readonly Mapper _mapper;
|
||||
|
||||
public WorkerAdapter(IWorkerBusinessLogicContract workerBusinessLogicContract, ILogger<WorkerAdapter> logger)
|
||||
{
|
||||
_buyerBusinessLogicContract = workerBusinessLogicContract;
|
||||
_logger = logger;
|
||||
var config = new MapperConfiguration(cfg =>
|
||||
{
|
||||
cfg.CreateMap<WorkerBindingModel, WorkerDataModel>();
|
||||
cfg.CreateMap<WorkerDataModel, WorkerViewModel>();
|
||||
});
|
||||
_mapper = new Mapper(config);
|
||||
}
|
||||
|
||||
public WorkerOperationResponse GetList(bool includeDeleted)
|
||||
{
|
||||
try
|
||||
{
|
||||
return WorkerOperationResponse.OK([.. _buyerBusinessLogicContract.GetAllWorkers(!includeDeleted).Select(x => _mapper.Map<WorkerViewModel>(x))]);
|
||||
}
|
||||
catch (NullListException)
|
||||
{
|
||||
_logger.LogError("NullListException");
|
||||
return WorkerOperationResponse.NotFound("The list is not initialized");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return WorkerOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return WorkerOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public WorkerOperationResponse GetPostList(string id, bool includeDeleted)
|
||||
{
|
||||
try
|
||||
{
|
||||
return WorkerOperationResponse.OK([.. _buyerBusinessLogicContract.GetAllWorkersByPost(id, !includeDeleted).Select(x => _mapper.Map<WorkerViewModel>(x))]);
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return WorkerOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (NullListException)
|
||||
{
|
||||
_logger.LogError("NullListException");
|
||||
return WorkerOperationResponse.NotFound("The list is not initialized");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return WorkerOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return WorkerOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public WorkerOperationResponse GetListByBirthDate(DateTime fromDate, DateTime toDate, bool includeDeleted)
|
||||
{
|
||||
try
|
||||
{
|
||||
return WorkerOperationResponse.OK([.. _buyerBusinessLogicContract.GetAllWorkersByBirthDate(fromDate, toDate, !includeDeleted).Select(x => _mapper.Map<WorkerViewModel>(x))]);
|
||||
}
|
||||
catch (IncorrectDatesException ex)
|
||||
{
|
||||
_logger.LogError(ex, "IncorrectDatesException");
|
||||
return WorkerOperationResponse.BadRequest($"Incorrect dates: {ex.Message}");
|
||||
}
|
||||
catch (NullListException)
|
||||
{
|
||||
_logger.LogError("NullListException");
|
||||
return WorkerOperationResponse.NotFound("The list is not initialized");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return WorkerOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return WorkerOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public WorkerOperationResponse GetListByEmploymentDate(DateTime fromDate, DateTime toDate, bool includeDeleted)
|
||||
{
|
||||
try
|
||||
{
|
||||
return WorkerOperationResponse.OK([.. _buyerBusinessLogicContract.GetAllWorkersByEmploymentDate(fromDate, toDate, !includeDeleted).Select(x => _mapper.Map<WorkerViewModel>(x))]);
|
||||
}
|
||||
catch (IncorrectDatesException ex)
|
||||
{
|
||||
_logger.LogError(ex, "IncorrectDatesException");
|
||||
return WorkerOperationResponse.BadRequest($"Incorrect dates: {ex.Message}");
|
||||
}
|
||||
catch (NullListException)
|
||||
{
|
||||
_logger.LogError("NullListException");
|
||||
return WorkerOperationResponse.NotFound("The list is not initialized");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return WorkerOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return WorkerOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public WorkerOperationResponse GetElement(string data)
|
||||
{
|
||||
try
|
||||
{
|
||||
return WorkerOperationResponse.OK(_mapper.Map<WorkerViewModel>(_buyerBusinessLogicContract.GetWorkerByData(data)));
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return WorkerOperationResponse.BadRequest("Data is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return WorkerOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (ElementNotFoundException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementNotFoundException");
|
||||
return WorkerOperationResponse.NotFound($"Not found element by data {data}");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return WorkerOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return WorkerOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public WorkerOperationResponse RegisterWorker(WorkerBindingModel workerModel)
|
||||
{
|
||||
try
|
||||
{
|
||||
_buyerBusinessLogicContract.InsertWorker(_mapper.Map<WorkerDataModel>(workerModel));
|
||||
return WorkerOperationResponse.NoContent();
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return WorkerOperationResponse.BadRequest("Data is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return WorkerOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (ElementExistsException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementExistsException");
|
||||
return WorkerOperationResponse.BadRequest(ex.Message);
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return WorkerOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return WorkerOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public WorkerOperationResponse ChangeWorkerInfo(WorkerBindingModel workerModel)
|
||||
{
|
||||
try
|
||||
{
|
||||
_buyerBusinessLogicContract.UpdateWorker(_mapper.Map<WorkerDataModel>(workerModel));
|
||||
return WorkerOperationResponse.NoContent();
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return WorkerOperationResponse.BadRequest("Data is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return WorkerOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (ElementNotFoundException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementNotFoundException");
|
||||
return WorkerOperationResponse.BadRequest($"Not found element by Id {workerModel.Id}");
|
||||
}
|
||||
catch (ElementExistsException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementExistsException");
|
||||
return WorkerOperationResponse.BadRequest(ex.Message);
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return WorkerOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return WorkerOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public WorkerOperationResponse RemoveWorker(string id)
|
||||
{
|
||||
try
|
||||
{
|
||||
_buyerBusinessLogicContract.DeleteWorker(id);
|
||||
return WorkerOperationResponse.NoContent();
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return WorkerOperationResponse.BadRequest("Id is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return WorkerOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (ElementNotFoundException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementNotFoundException");
|
||||
return WorkerOperationResponse.BadRequest($"Not found element by id: {id}");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return WorkerOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return WorkerOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net9.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<LangVersion>preview</LangVersion>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="9.0.4" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="9.0.4" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="9.0.4" />
|
||||
<PackageReference Include="NSwag.AspNetCore" Version="14.3.0" />
|
||||
<PackageReference Include="NUnit" Version="4.3.2" />
|
||||
<PackageReference Include="Serilog.AspNetCore" Version="9.0.0" />
|
||||
<PackageReference Include="Swashbuckle.AspNetCore" Version="8.1.1" />
|
||||
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="8.8.0" />
|
||||
<PackageReference Include="System.Security.Claims" Version="4.3.0" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\AndDietCokeBuisnessLogic\AndDietCokeBuisnessLogic.csproj" />
|
||||
<ProjectReference Include="..\AndDietCokeDatabase\AndDietCokeDatabase.csproj" />
|
||||
<ProjectReference Include="..\AndDietCokeProject\AndDietCokeContracts.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<InternalsVisibleTo Include="AndDietCokeTests" />
|
||||
<InternalsVisibleTo Include="DynamicProxyGenAssembly2" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
12
AndDietCokeProject/AndDietCokeWebApi/AuthOptions.cs
Normal file
12
AndDietCokeProject/AndDietCokeWebApi/AuthOptions.cs
Normal file
@@ -0,0 +1,12 @@
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using System.Text;
|
||||
|
||||
namespace AndDietCokeWebApi;
|
||||
|
||||
public class AuthOptions
|
||||
{
|
||||
public const string ISSUER = "AndDietCoke_AuthServer"; // издатель токена
|
||||
public const string AUDIENCE = "AndDietCoke_AuthClient"; // потребитель токена
|
||||
const string KEY = "cokesecret_secretsecretsecretkey!123"; // ключ для шифрации
|
||||
public static SymmetricSecurityKey GetSymmetricSecurityKey() => new(Encoding.UTF8.GetBytes(KEY));
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
using AndDietCokeContracts.AdapterContracts;
|
||||
using AndDietCokeContracts.BindingModels;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace AndDietCokeWebApi.Controllers;
|
||||
|
||||
[Authorize]
|
||||
[Route("api/[controller]")]
|
||||
[ApiController]
|
||||
[Produces("application/json")]
|
||||
public class BuyersController(IBuyerAdapter adapter) : ControllerBase
|
||||
{
|
||||
private readonly IBuyerAdapter _adapter = adapter;
|
||||
|
||||
[HttpGet]
|
||||
public IActionResult GetAllRecords()
|
||||
{
|
||||
return _adapter.GetList().GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpGet("{data}")]
|
||||
public IActionResult GetRecord(string data)
|
||||
{
|
||||
return _adapter.GetElement(data).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
public IActionResult Register([FromBody] BuyerBindingModel model)
|
||||
{
|
||||
return _adapter.RegisterBuyer(model).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpPut]
|
||||
public IActionResult ChangeInfo([FromBody] BuyerBindingModel model)
|
||||
{
|
||||
return _adapter.ChangeBuyerInfo(model).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpDelete("{id}")]
|
||||
public IActionResult Delete(string id)
|
||||
{
|
||||
return _adapter.RemoveBuyer(id).GetResponse(Request, Response);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
using AndDietCokeContracts.AdapterContracts;
|
||||
using AndDietCokeContracts.BindingModels;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace AndDietCokeWebApi.Controllers;
|
||||
|
||||
|
||||
[Authorize]
|
||||
[Route("api/[controller]/[action]")]
|
||||
[ApiController]
|
||||
[Produces("application/json")]
|
||||
public class DishesController(IDishAdapter adapter) : ControllerBase
|
||||
{
|
||||
private readonly IDishAdapter _adapter = adapter;
|
||||
|
||||
[HttpGet]
|
||||
public IActionResult GetRecords(bool includeDeleted)
|
||||
{
|
||||
return _adapter.GetList(includeDeleted).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
public IActionResult GetHistory(string id)
|
||||
{
|
||||
return _adapter.GetHistory(id).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpGet("{data}")]
|
||||
public IActionResult GetRecord(string data)
|
||||
{
|
||||
return _adapter.GetElement(data).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
public IActionResult Register([FromBody] DishBindingModel model)
|
||||
{
|
||||
return _adapter.RegisterDish(model).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpPut]
|
||||
public IActionResult ChangeInfo([FromBody] DishBindingModel model)
|
||||
{
|
||||
return _adapter.ChangeDishInfo(model).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpDelete("{id}")]
|
||||
public IActionResult Delete(string id)
|
||||
{
|
||||
return _adapter.RemoveDish(id).GetResponse(Request, Response);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
using AndDietCokeContracts.AdapterContracts;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace AndDietCokeWebApi.Controllers;
|
||||
|
||||
[Authorize]
|
||||
[Route("api/[controller]")]
|
||||
[ApiController]
|
||||
[Produces("application/json")]
|
||||
public class PostHistoryController(IPostAdapter adapter) : ControllerBase
|
||||
{
|
||||
private readonly IPostAdapter _adapter = adapter;
|
||||
|
||||
[HttpGet("{id}")]
|
||||
public IActionResult GetHistory(string id)
|
||||
{
|
||||
return _adapter.GetHistory(id).GetResponse(Request, Response);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
using AndDietCokeContracts.AdapterContracts;
|
||||
using AndDietCokeContracts.BindingModels;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace AndDietCokeWebApi.Controllers;
|
||||
|
||||
[Authorize]
|
||||
[Route("api/[controller]")]
|
||||
[ApiController]
|
||||
[Produces("application/json")]
|
||||
public class PostsController(IPostAdapter adapter) : ControllerBase
|
||||
{
|
||||
private readonly IPostAdapter _adapter = adapter;
|
||||
|
||||
[HttpGet]
|
||||
public IActionResult GetRecords()
|
||||
{
|
||||
return _adapter.GetList().GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpGet("{data}")]
|
||||
public IActionResult GetRecord(string data)
|
||||
{
|
||||
return _adapter.GetElement(data).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
public IActionResult Register([FromBody] PostBindingModel model)
|
||||
{
|
||||
return _adapter.RegisterPost(model).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpPut]
|
||||
public IActionResult ChangeInfo([FromBody] PostBindingModel model)
|
||||
{
|
||||
return _adapter.ChangePostInfo(model).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpDelete("{id}")]
|
||||
public IActionResult Delete(string id)
|
||||
{
|
||||
return _adapter.RemovePost(id).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpPatch("{id}")]
|
||||
public IActionResult Restore(string id)
|
||||
{
|
||||
return _adapter.RestorePost(id).GetResponse(Request, Response);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
using AndDietCokeContracts.AdapterContracts;
|
||||
using AndDietCokeContracts.AdapterContracts.OperationResponses;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace AndDietCokeWebApi.Controllers;
|
||||
|
||||
[Authorize]
|
||||
[Route("api/[controller]/[action]")]
|
||||
[ApiController]
|
||||
[Produces("application/json")]
|
||||
public class SalaryController(ISalaryAdapter adapter) : ControllerBase
|
||||
{
|
||||
private readonly ISalaryAdapter _adapter = adapter;
|
||||
|
||||
[HttpGet]
|
||||
public IActionResult GetRecords(DateTime fromDate, DateTime toDate)
|
||||
{
|
||||
return _adapter.GetListByPeriod(fromDate, toDate).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
public IActionResult GetEmployeeRecords(string id, DateTime fromDate, DateTime toDate)
|
||||
{
|
||||
return _adapter.GetListByPeriodByEmployee(fromDate, toDate, id).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
public IActionResult Calculate(DateTime date)
|
||||
{
|
||||
return _adapter.CalculateSalary(date).GetResponse(Request, Response);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
using AndDietCokeContracts.AdapterContracts;
|
||||
using AndDietCokeContracts.BindingModels;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace AndDietCokeWebApi.Controllers;
|
||||
|
||||
[Authorize]
|
||||
[Route("api/[controller]/[action]")]
|
||||
[ApiController]
|
||||
[Produces("application/json")]
|
||||
public class SalesController(ISaleAdapter adapter) : ControllerBase
|
||||
{
|
||||
private readonly ISaleAdapter _adapter = adapter;
|
||||
|
||||
[HttpGet]
|
||||
public IActionResult GetRecords(DateTime fromDate, DateTime toDate)
|
||||
{
|
||||
return _adapter.GetList(fromDate, toDate).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
public IActionResult GetWorkerRecords(string id, DateTime fromDate, DateTime toDate)
|
||||
{
|
||||
return _adapter.GetWorkerList(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 GetDishRecords(string id, DateTime fromDate, DateTime toDate)
|
||||
{
|
||||
return _adapter.GetDishList(id, fromDate, toDate).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpGet("{data}")]
|
||||
public IActionResult GetRecord(string data)
|
||||
{
|
||||
return _adapter.GetElement(data).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
public IActionResult Sale([FromBody] SaleBindingModel model)
|
||||
{
|
||||
return _adapter.MakeSale(model).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpDelete("{id}")]
|
||||
public IActionResult Cancel(string id)
|
||||
{
|
||||
return _adapter.CancelSale(id).GetResponse(Request, Response);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using NUnit.Framework;
|
||||
|
||||
namespace AndDietCokeWebApi.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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
using AndDietCokeContracts.AdapterContracts;
|
||||
using AndDietCokeContracts.BindingModels;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace AndDietCokeWebApi.Controllers;
|
||||
|
||||
[Authorize]
|
||||
[Route("api/[controller]/[action]")]
|
||||
[ApiController]
|
||||
[Produces("application/json")]
|
||||
public class WorkersController(IWorkerAdapter adapter) : ControllerBase
|
||||
{
|
||||
private readonly IWorkerAdapter _adapter = adapter;
|
||||
|
||||
[HttpGet]
|
||||
public IActionResult GetRecords(bool includeDeleted = false)
|
||||
{
|
||||
return _adapter.GetList(includeDeleted).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
public IActionResult GetPostRecords(string id, bool includeDeleted = false)
|
||||
{
|
||||
return _adapter.GetPostList(id, includeDeleted).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
public IActionResult GetBirthDateRecords(DateTime fromDate, DateTime toDate, bool includeDeleted = false)
|
||||
{
|
||||
return _adapter.GetListByBirthDate(fromDate, toDate, includeDeleted).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
public IActionResult GetEmploymentRecords(DateTime fromDate, DateTime toDate, bool includeDeleted = false)
|
||||
{
|
||||
return _adapter.GetListByEmploymentDate(fromDate, toDate, includeDeleted).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpGet("{data}")]
|
||||
public IActionResult GetRecord(string data)
|
||||
{
|
||||
return _adapter.GetElement(data).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
public IActionResult Register([FromBody] WorkerBindingModel model)
|
||||
{
|
||||
return _adapter.RegisterWorker(model).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpPut]
|
||||
public IActionResult ChangeInfo([FromBody] WorkerBindingModel model)
|
||||
{
|
||||
return _adapter.ChangeWorkerInfo(model).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpDelete("{id}")]
|
||||
public IActionResult Delete(string id)
|
||||
{
|
||||
return _adapter.RemoveWorker(id).GetResponse(Request, Response);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
using AndDietCokeContracts.Infrastrusture;
|
||||
|
||||
namespace AndDietCokeWebApi.Infrastructure;
|
||||
|
||||
public class ConfigurationDatabase(IConfiguration configuration) : IConfigurationDatabase
|
||||
{
|
||||
private readonly Lazy<DataBaseSettings> _dataBaseSettings = new(() =>
|
||||
{
|
||||
return configuration.GetValue<DataBaseSettings>("DataBaseSettings") ?? throw new InvalidDataException(nameof(DataBaseSettings));
|
||||
});
|
||||
|
||||
public string ConnectionString => _dataBaseSettings.Value.ConnectionString;
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
namespace AndDietCokeWebApi.Infrastructure;
|
||||
|
||||
public class DataBaseSettings
|
||||
{
|
||||
public required string ConnectionString { get; set; }
|
||||
}
|
||||
114
AndDietCokeProject/AndDietCokeWebApi/Program.cs
Normal file
114
AndDietCokeProject/AndDietCokeWebApi/Program.cs
Normal file
@@ -0,0 +1,114 @@
|
||||
using AndDietCokeWebApi;
|
||||
using AndDietCokeDatabase;
|
||||
using AndDietCokeBuisnessLogic.Implementations;
|
||||
using AndDietCokeContracts.BisnessLogicsContracts;
|
||||
using AndDietCokeContracts.Infrastrusture;
|
||||
using AndDietCokeContracts.StoragesContracts;
|
||||
using AndDietCokeDatabase.Implementations;
|
||||
using AndDietCokeWebApi.Infrastructure;
|
||||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using Serilog;
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
using System.Security.Claims;
|
||||
using AndDietCokeContracts.AdapterContracts;
|
||||
using AndDietCokeWebApi.Adapters;
|
||||
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
|
||||
// Add services to the container.
|
||||
|
||||
builder.Services.AddControllers();
|
||||
|
||||
using var loggerFactory = new LoggerFactory();
|
||||
loggerFactory.AddSerilog(new LoggerConfiguration().ReadFrom.Configuration(builder.Configuration).CreateLogger());
|
||||
builder.Services.AddSingleton(loggerFactory.CreateLogger("Any"));
|
||||
|
||||
builder.Services.AddAuthorization();
|
||||
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
|
||||
.AddJwtBearer(options =>
|
||||
{
|
||||
options.TokenValidationParameters = new TokenValidationParameters
|
||||
{
|
||||
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>, <20><><EFBFBD><EFBFBD><EFBFBD> <20><> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
|
||||
ValidateIssuer = true,
|
||||
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>, <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
|
||||
ValidIssuer = AuthOptions.ISSUER,
|
||||
// <20><><EFBFBD><EFBFBD><EFBFBD> <20><> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
|
||||
ValidateAudience = true,
|
||||
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
|
||||
ValidAudience = AuthOptions.AUDIENCE,
|
||||
// <20><><EFBFBD><EFBFBD><EFBFBD> <20><> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
|
||||
ValidateLifetime = true,
|
||||
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
|
||||
IssuerSigningKey = AuthOptions.GetSymmetricSecurityKey(),
|
||||
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
|
||||
ValidateIssuerSigningKey = true,
|
||||
};
|
||||
});
|
||||
|
||||
builder.Services.AddSingleton<IConfigurationDatabase, ConfigurationDatabase>();
|
||||
|
||||
builder.Services.AddTransient<IBuyerBusinessLogicContract, BuyerBusinessLogicContract>();
|
||||
builder.Services.AddTransient<IPostBusinessLogicContract, PostBusinessLogicContract>();
|
||||
builder.Services.AddTransient<IDishBusinessLogicContract, DishBusinessLogicContract>();
|
||||
builder.Services.AddTransient<ISalaryBusinessLogicContract, SalaryBusinessLogicContract>();
|
||||
builder.Services.AddTransient<ISaleBusinessLogicContract, SaleBusinessLogicContract>();
|
||||
builder.Services.AddTransient<IWorkerBusinessLogicContract, WorkerBusinessLogicContract>();
|
||||
|
||||
builder.Services.AddTransient<AndDietCokeDbContext>();
|
||||
builder.Services.AddTransient<IBuyerStorageContract, BuyerStorageContract>();
|
||||
builder.Services.AddTransient<IPostStorageContract, PostStorageContract>();
|
||||
builder.Services.AddTransient<IDishStorageContract, DishStorageContract>();
|
||||
builder.Services.AddTransient<ISalaryStorageContract, SalaryStorageContract>();
|
||||
builder.Services.AddTransient<ISaleStorageContract, SaleStorageContract>();
|
||||
builder.Services.AddTransient<IWorkerStorageContract, WorkerStorageContract>();
|
||||
|
||||
builder.Services.AddTransient<IBuyerAdapter, BuyerAdapter>();
|
||||
builder.Services.AddTransient<IPostAdapter, PostAdapter>();
|
||||
builder.Services.AddTransient<IDishAdapter, DishAdapter>();
|
||||
builder.Services.AddTransient<ISalaryAdapter, SalaryAdapter>();
|
||||
builder.Services.AddTransient<ISaleAdapter, SaleAdapter>();
|
||||
builder.Services.AddTransient<IWorkerAdapter, WorkerAdapter>();
|
||||
|
||||
|
||||
|
||||
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
|
||||
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<AndDietCokeDbContext>();
|
||||
if (dbContext.Database.CanConnect())
|
||||
{
|
||||
dbContext.Database.EnsureCreated();
|
||||
dbContext.Database.Migrate();
|
||||
}
|
||||
}
|
||||
|
||||
app.UseHttpsRedirection();
|
||||
|
||||
app.UseAuthentication();
|
||||
app.UseAuthorization();
|
||||
|
||||
app.Map("/login/{username}", (string username) =>
|
||||
{
|
||||
return new JwtSecurityTokenHandler().WriteToken(new JwtSecurityToken(
|
||||
issuer: AuthOptions.ISSUER,
|
||||
audience: AuthOptions.AUDIENCE,
|
||||
claims: [new(ClaimTypes.Name, username)],
|
||||
expires: DateTime.UtcNow.Add(TimeSpan.FromMinutes(2)),
|
||||
signingCredentials: new SigningCredentials(AuthOptions.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256)));
|
||||
});
|
||||
|
||||
app.MapControllers();
|
||||
|
||||
app.Run();
|
||||
@@ -0,0 +1,41 @@
|
||||
{
|
||||
"$schema": "https://json.schemastore.org/launchsettings.json",
|
||||
"iisSettings": {
|
||||
"windowsAuthentication": false,
|
||||
"anonymousAuthentication": true,
|
||||
"iisExpress": {
|
||||
"applicationUrl": "http://localhost:48128",
|
||||
"sslPort": 44326
|
||||
}
|
||||
},
|
||||
"profiles": {
|
||||
"http": {
|
||||
"commandName": "Project",
|
||||
"dotnetRunMessages": true,
|
||||
"launchBrowser": true,
|
||||
"launchUrl": "swagger",
|
||||
"applicationUrl": "http://localhost:5006",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
},
|
||||
"https": {
|
||||
"commandName": "Project",
|
||||
"dotnetRunMessages": true,
|
||||
"launchBrowser": true,
|
||||
"launchUrl": "swagger",
|
||||
"applicationUrl": "https://localhost:7215;http://localhost:5006",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
},
|
||||
"IIS Express": {
|
||||
"commandName": "IISExpress",
|
||||
"launchBrowser": true,
|
||||
"launchUrl": "swagger",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
13
AndDietCokeProject/AndDietCokeWebApi/WeatherForecast.cs
Normal file
13
AndDietCokeProject/AndDietCokeWebApi/WeatherForecast.cs
Normal file
@@ -0,0 +1,13 @@
|
||||
namespace AndDietCokeWebApi
|
||||
{
|
||||
public class WeatherForecast
|
||||
{
|
||||
public DateOnly Date { get; set; }
|
||||
|
||||
public int TemperatureC { get; set; }
|
||||
|
||||
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
|
||||
|
||||
public string? Summary { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
}
|
||||
}
|
||||
}
|
||||
28
AndDietCokeProject/AndDietCokeWebApi/appsettings.json
Normal file
28
AndDietCokeProject/AndDietCokeWebApi/appsettings.json
Normal file
@@ -0,0 +1,28 @@
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
}
|
||||
},
|
||||
"Serilog": {
|
||||
"Using": [ "Serilog.Sinks.File" ],
|
||||
"MinimumLevel": {
|
||||
"Default": "Information"
|
||||
},
|
||||
"WriteTo": [
|
||||
{
|
||||
"Name": "File",
|
||||
"Args": {
|
||||
"path": "../logs/anddietcoke-.log",
|
||||
"rollingInterval": "Day",
|
||||
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} {CorrelationId} {Level:u3} {Username} {Message:lj}{Exception}{NewLine}"
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"AllowedHosts": "*",
|
||||
"DataBaseSettings": {
|
||||
"ConnectionString": "Host=127.0.0.1;Port=5432;Database=AndDietCoke;Username=postgres;Password=postgres;"
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user