11 Commits

Author SHA1 Message Date
IlyasValiulov
0bd6c0910c правка проверки и списания компонент 2025-03-21 14:04:08 +04:00
IlyasValiulov
b9f01be873 3 усложенная лаба 2025-03-11 23:05:33 +04:00
IlyasValiulov
12844dc03b Merge branch 'LabWork02_BusinessLogic_Hard' into LabWork03_Storage_Hard 2025-03-07 20:00:20 +04:00
IlyasValiulov
9bc7da62f9 правки по третьей лабе 2025-03-07 12:05:45 +04:00
IlyasValiulov
6d0e92cd35 Добавление проверки компонента 2025-03-06 20:39:51 +04:00
IlyasValiulov
2e1379fdc0 лаба 3 2025-03-06 18:31:13 +04:00
IlyasValiulov
e9d39370c8 предварительный коммит 2025-03-05 23:17:25 +04:00
IlyasValiulov
ecb621bbbc 2 усложненная 2025-03-03 12:20:37 +04:00
IlyasValiulov
814b878d67 Объединение с первой усложненный веткой 2025-02-21 17:38:18 +04:00
IlyasValiulov
1b10b08b94 Добавление листов для таблицы многих ко многим в классы SuppliesDataModel и WarehouseDataModel 2025-02-21 12:25:24 +04:00
IlyasValiulov
21e7134953 усложненная лаба 2025-02-08 13:02:26 +04:00
57 changed files with 4167 additions and 7 deletions

View File

@@ -9,6 +9,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FurnitureAssemblyTests", "F
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FurnitureAssemblyBusinessLogic", "FurnitureAssemblyBusinessLogic\FurnitureAssemblyBusinessLogic.csproj", "{698BF48B-C9AC-4684-8150-52E8148F15A0}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FurnitureAssemblyDatebase", "FurnitureAssemblyDatebase\FurnitureAssemblyDatebase.csproj", "{BDE6EBBB-E735-408D-B34B-490C2AE9201B}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@@ -27,6 +29,10 @@ Global
{698BF48B-C9AC-4684-8150-52E8148F15A0}.Debug|Any CPU.Build.0 = Debug|Any CPU
{698BF48B-C9AC-4684-8150-52E8148F15A0}.Release|Any CPU.ActiveCfg = Release|Any CPU
{698BF48B-C9AC-4684-8150-52E8148F15A0}.Release|Any CPU.Build.0 = Release|Any CPU
{BDE6EBBB-E735-408D-B34B-490C2AE9201B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{BDE6EBBB-E735-408D-B34B-490C2AE9201B}.Debug|Any CPU.Build.0 = Debug|Any CPU
{BDE6EBBB-E735-408D-B34B-490C2AE9201B}.Release|Any CPU.ActiveCfg = Release|Any CPU
{BDE6EBBB-E735-408D-B34B-490C2AE9201B}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE

View File

@@ -8,9 +8,10 @@ using System.Text.Json;
namespace FurnitureAssemblyBusinessLogic.Implementations;
internal class FurnitureBusinessLogicContract(IFurnitureStorageContract furnitureStorageContract, ILogger logger) : IFurnitureBusinessLogicContract
internal class FurnitureBusinessLogicContract(IFurnitureStorageContract furnitureStorageContract, IWarehouseStorageContract warehouseStorageContract, ILogger logger) : IFurnitureBusinessLogicContract
{
IFurnitureStorageContract _furnitureStorageContract = furnitureStorageContract;
IWarehouseStorageContract _warehouseStorageContract = warehouseStorageContract;
private readonly ILogger _logger = logger;
public List<FurnitureDataModel> GetAllFurnitures()
@@ -38,6 +39,10 @@ internal class FurnitureBusinessLogicContract(IFurnitureStorageContract furnitur
_logger.LogInformation("New data: {json}", JsonSerializer.Serialize(furnitureDataModel));
ArgumentNullException.ThrowIfNull(furnitureDataModel);
furnitureDataModel.Validate();
if (!_warehouseStorageContract.CheckComponents(furnitureDataModel))
{
throw new InsufficientException("Dont have component in warehouse");
}
_furnitureStorageContract.AddElement(furnitureDataModel);
}
@@ -46,6 +51,10 @@ internal class FurnitureBusinessLogicContract(IFurnitureStorageContract furnitur
_logger.LogInformation("Update data: {json}", JsonSerializer.Serialize(furnitureDataModel));
ArgumentNullException.ThrowIfNull(furnitureDataModel);
furnitureDataModel.Validate();
if (!_warehouseStorageContract.CheckComponents(furnitureDataModel))
{
throw new InsufficientException("Dont have component in warehouse");
}
_furnitureStorageContract.UpdElement(furnitureDataModel);
}

View File

@@ -0,0 +1,52 @@
using FurnitureAssemblyContracts.BusinessLogicsContracts;
using FurnitureAssemblyContracts.DataModels;
using FurnitureAssemblyContracts.Enums;
using FurnitureAssemblyContracts.Exceptions;
using FurnitureAssemblyContracts.Extentions;
using FurnitureAssemblyContracts.StoragesContracts;
using Microsoft.Extensions.Logging;
using System.Text.Json;
namespace FurnitureAssemblyBusinessLogic.Implementations;
public class SuppliesBusinessLogicContract(ISuppliesStorageContract suppliesStorageContract, ILogger logger) : ISuppliesBusinessLogicContract
{
private readonly ISuppliesStorageContract _suppliesStorageContract = suppliesStorageContract;
private readonly ILogger _logger = logger;
public List<SuppliesDataModel> GetAllComponents()
{
_logger.LogInformation("GetAllComponents");
return _suppliesStorageContract.GetList() ?? throw new NullListException();
}
public SuppliesDataModel GetComponentByData(string data)
{
_logger.LogInformation("Get element by data: {data}", data);
if (data.IsEmpty())
{
throw new ArgumentNullException(nameof(data));
}
if (!data.IsGuid())
{
throw new ElementNotFoundException(data);
}
return _suppliesStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data);
}
public void InsertComponent(SuppliesDataModel suppliesDataModel)
{
_logger.LogInformation("New data: {json}", JsonSerializer.Serialize(suppliesDataModel));
ArgumentNullException.ThrowIfNull(suppliesDataModel);
suppliesDataModel.Validate();
_suppliesStorageContract.AddElement(suppliesDataModel);
}
public void UpdateComponent(SuppliesDataModel suppliesDataModel)
{
_logger.LogInformation("Update data: {json}", JsonSerializer.Serialize(suppliesDataModel));
ArgumentNullException.ThrowIfNull(suppliesDataModel);
suppliesDataModel.Validate();
_suppliesStorageContract.UpdElement(suppliesDataModel);
}
}

View File

@@ -0,0 +1,65 @@
using FurnitureAssemblyContracts.BusinessLogicsContracts;
using FurnitureAssemblyContracts.DataModels;
using FurnitureAssemblyContracts.Enums;
using FurnitureAssemblyContracts.Exceptions;
using FurnitureAssemblyContracts.Extentions;
using FurnitureAssemblyContracts.StoragesContracts;
using Microsoft.Extensions.Logging;
using System.Text.Json;
namespace FurnitureAssemblyBusinessLogic.Implementations;
public class WarehouseBusinessLogicContract(IWarehouseStorageContract warehouseStorageContract, ILogger logger) : IWarehouseBusinessLogicContract
{
private readonly IWarehouseStorageContract _warehouseStorageContract = warehouseStorageContract;
private readonly ILogger _logger = logger;
public List<WarehouseDataModel> GetAllComponents()
{
_logger.LogInformation("GetAllComponents");
return _warehouseStorageContract.GetList() ?? throw new NullListException();
}
public WarehouseDataModel GetComponentByData(string data)
{
_logger.LogInformation("Get element by data: {data}", data);
if (data.IsEmpty())
{
throw new ArgumentNullException(nameof(data));
}
if (!data.IsGuid())
{
throw new ElementNotFoundException(data);
}
return _warehouseStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data);
}
public void InsertComponent(WarehouseDataModel warehouseDataModel)
{
_logger.LogInformation("New data: {json}", JsonSerializer.Serialize(warehouseDataModel));
ArgumentNullException.ThrowIfNull(warehouseDataModel);
warehouseDataModel.Validate();
_warehouseStorageContract.AddElement(warehouseDataModel);
}
public void UpdateComponent(WarehouseDataModel warehouseDataModel)
{
_logger.LogInformation("Update data: {json}", JsonSerializer.Serialize(warehouseDataModel));
ArgumentNullException.ThrowIfNull(warehouseDataModel);
warehouseDataModel.Validate();
_warehouseStorageContract.UpdElement(warehouseDataModel);
}
public void DeleteComponent(string id)
{
logger.LogInformation("Delete by id: {id}", id);
if (id.IsEmpty())
{
throw new ArgumentNullException(nameof(id));
}
if (!id.IsGuid())
{
throw new ValidationException("Id is not a unique identifier");
}
_warehouseStorageContract.DelElement(id);
}
}

View File

@@ -0,0 +1,11 @@
using FurnitureAssemblyContracts.DataModels;
namespace FurnitureAssemblyContracts.BusinessLogicsContracts;
public interface ISuppliesBusinessLogicContract
{
List<SuppliesDataModel> GetAllComponents();
SuppliesDataModel GetComponentByData(string data);
void InsertComponent(SuppliesDataModel componentDataModel);
void UpdateComponent(SuppliesDataModel componentDataModel);
}

View File

@@ -0,0 +1,12 @@
using FurnitureAssemblyContracts.DataModels;
namespace FurnitureAssemblyContracts.BusinessLogicsContracts;
public interface IWarehouseBusinessLogicContract
{
List<WarehouseDataModel> GetAllComponents();
WarehouseDataModel GetComponentByData(string data);
void InsertComponent(WarehouseDataModel warehouseDataModel);
void UpdateComponent(WarehouseDataModel warehouseDataModel);
void DeleteComponent(string id);
}

View File

@@ -5,13 +5,13 @@ using FurnitureAssemblyContracts.Infrastructure;
namespace FurnitureAssemblyContracts.DataModels;
public class ComponentDataModel(string id, string name, ComponentType componentType, string? prevName = null, string? prevPrevName = null) : IValidation
public class ComponentDataModel(string id, string name, ComponentType type, string? prevName = null, string? prevPrevName = null) : IValidation
{
public string Id { get; private set; } = id;
public string Name { get; private set; } = name;
public string? PrevName { get; private set; } = prevName;
public string? PrevPrevName { get; private set; } = prevPrevName;
public ComponentType Type { get; private set; } = componentType;
public ComponentType Type { get; private set; } = type;
public void Validate()
{

View File

@@ -0,0 +1,26 @@
using FurnitureAssemblyContracts.Exceptions;
using FurnitureAssemblyContracts.Extentions;
using FurnitureAssemblyContracts.Infrastructure;
namespace FurnitureAssemblyContracts.DataModels;
public class ComponentSuppliesDataModel(string suppliesId, string componentId, int count) : IValidation
{
public string SuppliesId { get; private set; } = suppliesId;
public string ComponentId { get; private set; } = componentId;
public int Count { get; private set; } = count;
public void Validate()
{
if (SuppliesId.IsEmpty())
throw new ValidationException("Field FurnitureId is empty");
if (!SuppliesId.IsGuid())
throw new ValidationException("The value in the field FurnitureId is not a unique identifier");
if (ComponentId.IsEmpty())
throw new ValidationException("Field ComponentId is empty");
if (!ComponentId.IsGuid())
throw new ValidationException("The value in the field BlandId is not a unique identifier");
if (Count <= 0)
throw new ValidationException("Field Count is less than or equal to 0");
}
}

View File

@@ -0,0 +1,26 @@
using FurnitureAssemblyContracts.Exceptions;
using FurnitureAssemblyContracts.Extentions;
using FurnitureAssemblyContracts.Infrastructure;
namespace FurnitureAssemblyContracts.DataModels;
public class ComponentWarehouseDataModel(string warehouseId, string componentId, int count) : IValidation
{
public string WarehouseId { get; private set; } = warehouseId;
public string ComponentId { get; private set; } = componentId;
public int Count { get; private set; } = count;
public void Validate()
{
if (WarehouseId.IsEmpty())
throw new ValidationException("Field WarehouseId is empty");
if (!WarehouseId.IsGuid())
throw new ValidationException("The value in the field WarehouseId is not a unique identifier");
if (ComponentId.IsEmpty())
throw new ValidationException("Field ComponentId is empty");
if (!ComponentId.IsGuid())
throw new ValidationException("The value in the field ComponentId is not a unique identifier");
if (Count <= 0)
throw new ValidationException("Field Count is less than or equal to 0");
}
}

View File

@@ -5,9 +5,9 @@ using FurnitureAssemblyContracts.Infrastructure;
namespace FurnitureAssemblyContracts.DataModels;
public class PostDataModel(string id, string postName, PostType postType, double salary, bool isActual, DateTime changeDate) : IValidation
public class PostDataModel(string postid, string postName, PostType postType, double salary, bool isActual, DateTime changeDate) : IValidation
{
public string Id { get; private set; } = id;
public string Id { get; private set; } = postid;
public string PostName { get; private set; } = postName;
public PostType PostType { get; private set; } = postType;
public double Salary { get; private set; } = salary;

View File

@@ -0,0 +1,29 @@
using FurnitureAssemblyContracts.Enums;
using FurnitureAssemblyContracts.Exceptions;
using FurnitureAssemblyContracts.Extentions;
using FurnitureAssemblyContracts.Infrastructure;
namespace FurnitureAssemblyContracts.DataModels;
public class SuppliesDataModel(string id, ComponentType type, DateTime productuionDate, int count, List<ComponentSuppliesDataModel> components) : IValidation
{
public string Id { get; private set; } = id;
public ComponentType Type { get; private set; } = type;
public DateTime ProductuionDate { get; private set; } = productuionDate;
public int Count { get; private set; } = count;
public List<ComponentSuppliesDataModel> Components { get; private set; } = components;
public void Validate()
{
if (Id.IsEmpty())
throw new ValidationException("Field Id is empty");
if (!Id.IsGuid())
throw new ValidationException("The value in the field Id is not a unique identifier");
if (Type == ComponentType.None)
throw new ValidationException("Field Type is empty");
if (Count <= 0)
throw new ValidationException("Field Count is less than or equal to 0");
if ((Components?.Count ?? 0) == 0)
throw new ValidationException("The component must include supplies");
}
}

View File

@@ -0,0 +1,28 @@
using FurnitureAssemblyContracts.Enums;
using FurnitureAssemblyContracts.Exceptions;
using FurnitureAssemblyContracts.Extentions;
using FurnitureAssemblyContracts.Infrastructure;
namespace FurnitureAssemblyContracts.DataModels;
public class WarehouseDataModel(string id, ComponentType type, int count, List<ComponentWarehouseDataModel> components) : IValidation
{
public string Id { get; private set; } = id;
public ComponentType Type { get; private set; } = type;
public int Count { get; private set; } = count;
public List<ComponentWarehouseDataModel> Components { get; private set; } = components;
public void Validate()
{
if (Id.IsEmpty())
throw new ValidationException("Field Id is empty");
if (!Id.IsGuid())
throw new ValidationException("The value in the field Id is not a unique identifier");
if (Type == ComponentType.None)
throw new ValidationException("Field Type is empty");
if (Count <= 0)
throw new ValidationException("Field Count is less than or equal to 0");
if ((Components?.Count ?? 0) == 0)
throw new ValidationException("The component must include supplies");
}
}

View File

@@ -0,0 +1,6 @@
namespace FurnitureAssemblyContracts.Exceptions;
public class ElementDeletedException : Exception
{
public ElementDeletedException(string id) : base($"Cannot modify a deleted item(id: { id})") { }
}

View File

@@ -0,0 +1,5 @@
namespace FurnitureAssemblyContracts.Exceptions;
public class InsufficientException(string message) : Exception(message)
{
}

View File

@@ -0,0 +1,7 @@
namespace FurnitureAssemblyContracts.Infrastructure;
public interface IConfigurationDatabase
{
string ConnectionString { get; }
}

View File

@@ -0,0 +1,11 @@
using FurnitureAssemblyContracts.DataModels;
namespace FurnitureAssemblyContracts.StoragesContracts;
public interface ISuppliesStorageContract
{
List<SuppliesDataModel> GetList(DateTime? startDate = null);
SuppliesDataModel GetElementById(string id);
void AddElement(SuppliesDataModel suppliesDataModel);
void UpdElement(SuppliesDataModel suppliesDataModel);
}

View File

@@ -0,0 +1,13 @@
using FurnitureAssemblyContracts.DataModels;
namespace FurnitureAssemblyContracts.StoragesContracts;
public interface IWarehouseStorageContract
{
List<WarehouseDataModel> GetList();
WarehouseDataModel GetElementById(string id);
void AddElement(WarehouseDataModel warehouseDataModel);
void UpdElement(WarehouseDataModel warehouseDataModel);
void DelElement(string id);
bool CheckComponents(FurnitureDataModel furnitureDataModel);
}

View File

@@ -0,0 +1,19 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="AutoMapper" Version="14.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="9.0.2" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="9.0.4" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\FurnitureAssemblyContracts\FurnitureAssemblyContracts.csproj" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,60 @@
using FurnitureAssemblyContracts.Infrastructure;
using FurnitureAssemblyDatebase.Models;
using Microsoft.EntityFrameworkCore;
namespace FurnitureAssemblyDatebase;
public class FurnitureAssemblyDbContext(IConfigurationDatabase configurationDatabase) : DbContext
{
private readonly IConfigurationDatabase? _configurationDatabase = configurationDatabase;
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseNpgsql(_configurationDatabase?.ConnectionString, o
=> o.SetPostgresVersion(12, 2));
base.OnConfiguring(optionsBuilder);
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Component>().HasIndex(x => x.Name).IsUnique();
modelBuilder.Entity<Furniture>().HasIndex(x => x.Name).IsUnique();
modelBuilder.Entity<Post>()
.HasIndex(e => new { e.PostName, e.IsActual })
.IsUnique()
.HasFilter($"\"{nameof(Post.IsActual)}\" = TRUE");
modelBuilder.Entity<Post>()
.HasIndex(e => new { e.PostId, e.IsActual })
.IsUnique()
.HasFilter($"\"{nameof(Post.IsActual)}\" = TRUE");
modelBuilder.Entity<ComponentSupplies>().HasKey(x => new { x.SuppliesId, x.ComponentId });
modelBuilder.Entity<ComponentWarehouse>().HasKey(x => new { x.WarehouseId, x.ComponentId });
modelBuilder.Entity<FurnitureComponent>().HasKey(x => new { x.FurnitureId, x.ComponentId });
modelBuilder.Entity<FurnitureComponent>()
.HasOne(fc => fc.Furniture)
.WithMany(f => f.Components)
.HasForeignKey(fc => fc.FurnitureId)
.OnDelete(DeleteBehavior.Restrict);
}
public DbSet<ManifacturingFurniture> Manufacturing { get; set; }
public DbSet<Post> Posts { get; set; }
public DbSet<Component> Components { get; set; }
public DbSet<Salary> Salaries { get; set; }
public DbSet<Furniture> Furnitures { get; set; }
public DbSet<FurnitureComponent> FurnitureComponents { get; set; }
public DbSet<Worker> Workers { get; set; }
public DbSet<Supplies> Supplieses { get; set; }
public DbSet<Warehouse> Warehouses { get; set; }
public DbSet<ComponentSupplies> ComponentSupplieses { get; set; }
public DbSet<ComponentWarehouse> ComponentWarehouses { get; set; }
}

View File

@@ -0,0 +1,159 @@
using AutoMapper;
using FurnitureAssemblyContracts.DataModels;
using FurnitureAssemblyContracts.Exceptions;
using FurnitureAssemblyContracts.StoragesContracts;
using FurnitureAssemblyDatebase.Models;
using Microsoft.EntityFrameworkCore;
using Npgsql;
namespace FurnitureAssemblyDatebase.Implementations;
public class ComponentStorageContract : IComponentStorageContract
{
private readonly FurnitureAssemblyDbContext _dbContext;
private readonly Mapper _mapper;
public ComponentStorageContract(FurnitureAssemblyDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.AddMaps(typeof(Component));
});
_mapper = new Mapper(config);
}
public List<ComponentDataModel> GetList()
{
try
{
return [.. _dbContext.Components.Select(x => _mapper.Map<ComponentDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public ComponentDataModel? GetElementById(string id)
{
try
{
return _mapper.Map<ComponentDataModel>(GetComponentById(id));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public ComponentDataModel? GetElementByName(string name)
{
try
{
return _mapper.Map<ComponentDataModel>(_dbContext.Components.FirstOrDefault(x => x.Name == name));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public ComponentDataModel? GetElementByOldName(string name)
{
try
{
return _mapper.Map<ComponentDataModel>(_dbContext.Components.FirstOrDefault(x =>
x.PrevName == name || x.PrevPrevName == name));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void AddElement(ComponentDataModel manufacturerDataModel)
{
try
{
_dbContext.Components.Add(_mapper.Map<Component>(manufacturerDataModel));
_dbContext.SaveChanges();
}
catch (InvalidOperationException ex) when (ex.TargetSite?.Name == "ThrowIdentityConflict")
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("Id", manufacturerDataModel.Id);
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Components_Name" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("Name", manufacturerDataModel.Name);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void UpdElement(ComponentDataModel manufacturerDataModel)
{
try
{
var element = GetComponentById(manufacturerDataModel.Id) ?? throw new ElementNotFoundException(manufacturerDataModel.Id);
if (element.Name != manufacturerDataModel.Name)
{
element.PrevPrevName = element.PrevName;
element.PrevName = element.Name;
element.Name = manufacturerDataModel.Name;
}
if (element.Type != manufacturerDataModel.Type)
{
element.Type = manufacturerDataModel.Type;
}
_dbContext.Components.Update(element);
_dbContext.SaveChanges();
}
catch (ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Components_Name" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("Name", manufacturerDataModel.Name);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void DelElement(string id)
{
try
{
var element = GetComponentById(id) ?? throw new ElementNotFoundException(id);
_dbContext.Components.Remove(element);
_dbContext.SaveChanges();
}
catch (ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
private Component? GetComponentById(string id) => _dbContext.Components.FirstOrDefault(x => x.Id == id);
}

View File

@@ -0,0 +1,136 @@
using AutoMapper;
using FurnitureAssemblyContracts.DataModels;
using FurnitureAssemblyContracts.Exceptions;
using FurnitureAssemblyContracts.StoragesContracts;
using FurnitureAssemblyDatebase.Models;
using Microsoft.EntityFrameworkCore;
using Npgsql;
namespace FurnitureAssemblyDatebase;
public class FurnitureStorageContract : IFurnitureStorageContract
{
private readonly FurnitureAssemblyDbContext _dbContext;
private readonly Mapper _mapper;
public FurnitureStorageContract(FurnitureAssemblyDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Furniture, FurnitureDataModel>();
cfg.CreateMap<FurnitureDataModel, Furniture>();
});
_mapper = new Mapper(config);
}
public List<FurnitureDataModel> GetList()
{
try
{
return [.. _dbContext.Furnitures.Select(x => _mapper.Map<FurnitureDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public FurnitureDataModel GetElementById(string id)
{
try
{
return _mapper.Map<FurnitureDataModel>(GetFurnitureById(id));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public FurnitureDataModel GetElementByName(string name)
{
try
{
return _mapper.Map<FurnitureDataModel>(_dbContext.Furnitures.FirstOrDefault(x => x.Name == name));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void AddElement(FurnitureDataModel furnitureDataModel)
{
try
{
_dbContext.Furnitures.Add(_mapper.Map<Furniture>(furnitureDataModel));
_dbContext.SaveChanges();
}
catch (InvalidOperationException ex) when (ex.TargetSite?.Name == "ThrowIdentityConflict")
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("Id", furnitureDataModel.Id);
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Furnitures_Name" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("Name", furnitureDataModel.Name);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void UpdElement(FurnitureDataModel furnitureDataModel)
{
try
{
var element = GetFurnitureById(furnitureDataModel.Id) ?? throw new ElementNotFoundException(furnitureDataModel.Id);
_dbContext.Furnitures.Update(_mapper.Map(furnitureDataModel, element));
_dbContext.SaveChanges();
}
catch (ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Furnitures_Name" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("Name", furnitureDataModel.Name);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void DelElement(string id)
{
try
{
var element = GetFurnitureById(id) ?? throw new ElementNotFoundException(id);
_dbContext.Furnitures.Remove(element);
_dbContext.SaveChanges();
}
catch (ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
private Furniture? GetFurnitureById(string id) => _dbContext.Furnitures.FirstOrDefault(x => x.Id == id);
}

View File

@@ -0,0 +1,106 @@
using AutoMapper;
using FurnitureAssemblyContracts.DataModels;
using FurnitureAssemblyContracts.Exceptions;
using FurnitureAssemblyContracts.StoragesContracts;
using FurnitureAssemblyDatebase.Models;
using Microsoft.EntityFrameworkCore;
using Npgsql;
namespace FurnitureAssemblyDatebase.Implementations;
public class ManifacturingStorageContract : IManifacturingStorageContract
{
private readonly FurnitureAssemblyDbContext _dbContext;
private readonly Mapper _mapper;
public ManifacturingStorageContract(FurnitureAssemblyDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<ManifacturingFurniture, ManifacturingFurnitureDataModel>();
cfg.CreateMap<ManifacturingFurnitureDataModel, ManifacturingFurniture>();
});
_mapper = new Mapper(config);
}
public List<ManifacturingFurnitureDataModel> GetList(DateTime? startDate = null, DateTime? endDate = null, string? workerId = null, string? furnitureId = null)
{
try
{
var query = _dbContext.Manufacturing.AsQueryable();
if (startDate is not null && endDate is not null)
{
query = query.Where(x => x.ProductuionDate >= startDate && x.ProductuionDate < endDate);
}
if (workerId is not null)
{
query = query.Where(x => x.WorkerId == workerId);
}
if (furnitureId is not null)
{
query = query.Where(x => x.FurnitureId == furnitureId);
}
return [.. query.Select(x => _mapper.Map<ManifacturingFurnitureDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public ManifacturingFurnitureDataModel? GetElementById(string id)
{
try
{
return _mapper.Map<ManifacturingFurnitureDataModel>(GetManifacturingById(id));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void AddElement(ManifacturingFurnitureDataModel manifacturingFurnitureDataModel)
{
try
{
_dbContext.Manufacturing.Add(_mapper.Map<ManifacturingFurniture>(manifacturingFurnitureDataModel));
_dbContext.SaveChanges();
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void UpdElement(ManifacturingFurnitureDataModel manifacturingFurnitureDataModel)
{
try
{
var element = GetManifacturingById(manifacturingFurnitureDataModel.Id) ?? throw new ElementNotFoundException(manifacturingFurnitureDataModel.Id);
_dbContext.Manufacturing.Update(_mapper.Map(manifacturingFurnitureDataModel, element));
_dbContext.SaveChanges();
}
catch (ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Manifacturing_Id" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("PostId", manifacturingFurnitureDataModel.Id);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
private ManifacturingFurniture? GetManifacturingById(string id) => _dbContext.Manufacturing.FirstOrDefault(x => x.Id == id);
}

View File

@@ -0,0 +1,192 @@
using AutoMapper;
using FurnitureAssemblyContracts.DataModels;
using FurnitureAssemblyContracts.Exceptions;
using FurnitureAssemblyContracts.StoragesContracts;
using FurnitureAssemblyDatebase.Models;
using Microsoft.EntityFrameworkCore;
using Npgsql;
using System.Xml.Linq;
namespace FurnitureAssemblyDatebase.Implementations;
public class PostStorageContract : IPostStorageContract
{
private readonly FurnitureAssemblyDbContext _dbContext;
private readonly Mapper _mapper;
public PostStorageContract(FurnitureAssemblyDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Post, PostDataModel>()
.ForMember(x => x.Id, x => x.MapFrom(src => src.PostId));
cfg.CreateMap<PostDataModel, Post>()
.ForMember(x => x.Id, x => x.Ignore())
.ForMember(x => x.PostId, x => x.MapFrom(src => src.Id))
.ForMember(x => x.IsActual, x => x.MapFrom(src => true))
.ForMember(x => x.ChangeDate, x => x.MapFrom(src => DateTime.UtcNow));
});
_mapper = new Mapper(config);
}
public List<PostDataModel> GetList(bool onlyActual = true)
{
try
{
var query = _dbContext.Posts.AsQueryable();
if (onlyActual)
{
query = query.Where(x => x.IsActual);
}
return [.. query.Select(x => _mapper.Map<PostDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public PostDataModel? GetElementById(string id)
{
try
{
return _mapper.Map<PostDataModel>(_dbContext.Posts.FirstOrDefault(x => x.PostId == id && x.IsActual));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public PostDataModel? GetElementByName(string name)
{
try
{
return _mapper.Map<PostDataModel>(_dbContext.Posts.FirstOrDefault(x => x.PostName == name && x.IsActual));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public List<PostDataModel> GetPostWithHistory(string postId)
{
try
{
return [.. _dbContext.Posts.Where(x => x.PostId == postId).Select(x => _mapper.Map<PostDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void AddElement(PostDataModel postDataModel)
{
try
{
_dbContext.Posts.Add(_mapper.Map<Post>(postDataModel));
_dbContext.SaveChanges();
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Posts_PostName_IsActual" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("PostName", postDataModel.PostName);
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Posts_PostId_IsActual" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("PostId", postDataModel.Id);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void UpdElement(PostDataModel postDataModel)
{
try
{
var transaction = _dbContext.Database.BeginTransaction();
try
{
var element = GetPostById(postDataModel.Id) ?? throw new ElementNotFoundException(postDataModel.Id);
if (!element.IsActual)
{
throw new ElementDeletedException(postDataModel.Id);
}
element.IsActual = false;
_dbContext.SaveChanges();
var newElement = _mapper.Map<Post>(postDataModel);
_dbContext.Posts.Add(newElement);
_dbContext.SaveChanges();
transaction.Commit();
}
catch
{
transaction.Rollback();
throw;
}
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Posts_PostName_IsActual" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("PostName", postDataModel.PostName);
}
catch (Exception ex) when (ex is ElementDeletedException || ex is ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void DelElement(string id)
{
try
{
var element = GetPostById(id) ?? throw new ElementNotFoundException(id);
if (!element.IsActual)
{
throw new ElementDeletedException(id);
}
element.IsActual = false;
_dbContext.SaveChanges();
}
catch
{
_dbContext.ChangeTracker.Clear();
throw;
}
}
public void ResElement(string id)
{
try
{
var element = GetPostById(id) ?? throw new ElementNotFoundException(id);
element.IsActual = true;
_dbContext.SaveChanges();
}
catch
{
_dbContext.ChangeTracker.Clear();
throw;
}
}
private Post? GetPostById(string id) => _dbContext.Posts.Where(x => x.PostId == id).OrderByDescending(x => x.ChangeDate).FirstOrDefault();
}

View File

@@ -0,0 +1,56 @@
using AutoMapper;
using FurnitureAssemblyContracts.DataModels;
using FurnitureAssemblyContracts.Exceptions;
using FurnitureAssemblyContracts.StoragesContracts;
using FurnitureAssemblyDatebase.Models;
namespace FurnitureAssemblyDatebase.Implementations;
public class SalaryStorageContract : ISalaryStorageContract
{
private readonly FurnitureAssemblyDbContext _dbContext;
private readonly Mapper _mapper;
public SalaryStorageContract(FurnitureAssemblyDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Salary, SalaryDataModel>();
cfg.CreateMap<SalaryDataModel, Salary>()
.ForMember(dest => dest.WorkerSalary, opt => opt.MapFrom(src => src.Salary));
});
_mapper = new Mapper(config);
}
public List<SalaryDataModel> GetList(DateTime startDate, DateTime endDate, string? workerId = null)
{
try
{
var query = _dbContext.Salaries.Where(x => x.SalaryDate >= startDate && x.SalaryDate <= endDate);
if (workerId is not null)
{
query = query.Where(x => x.WorkerId == workerId);
}
return [.. query.Select(x => _mapper.Map<SalaryDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void AddElement(SalaryDataModel salaryDataModel)
{
try
{
_dbContext.Salaries.Add(_mapper.Map<Salary>(salaryDataModel));
_dbContext.SaveChanges();
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
}

View File

@@ -0,0 +1,84 @@
using AutoMapper;
using FurnitureAssemblyContracts.DataModels;
using FurnitureAssemblyContracts.Exceptions;
using FurnitureAssemblyContracts.StoragesContracts;
using FurnitureAssemblyDatebase.Models;
namespace FurnitureAssemblyDatebase.Implementations;
public class SuppliesStorageContract : ISuppliesStorageContract
{
private readonly FurnitureAssemblyDbContext _dbContext;
private readonly Mapper _mapper;
public SuppliesStorageContract(FurnitureAssemblyDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.AddMaps(typeof(Supplies));
});
_mapper = new Mapper(config);
}
public List<SuppliesDataModel> GetList(DateTime? startDate = null)
{
try
{
return [.. _dbContext.Supplieses.Select(x => _mapper.Map<SuppliesDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public SuppliesDataModel GetElementById(string id)
{
try
{
return _mapper.Map<SuppliesDataModel>(GetSuppliesById(id));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void AddElement(SuppliesDataModel suppliesDataModel)
{
try
{
_dbContext.Supplieses.Add(_mapper.Map<Supplies>(suppliesDataModel));
_dbContext.SaveChanges();
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void UpdElement(SuppliesDataModel suppliesDataModel)
{
try
{
var element = GetSuppliesById(suppliesDataModel.Id) ?? throw new ElementNotFoundException(suppliesDataModel.Id);
_dbContext.Supplieses.Update(_mapper.Map(suppliesDataModel, element));
_dbContext.SaveChanges();
}
catch (ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
private Supplies? GetSuppliesById(string id) => _dbContext.Supplieses.FirstOrDefault(x => x.Id == id);
}

View File

@@ -0,0 +1,134 @@
using AutoMapper;
using FurnitureAssemblyContracts.DataModels;
using FurnitureAssemblyContracts.Exceptions;
using FurnitureAssemblyContracts.StoragesContracts;
using FurnitureAssemblyDatebase.Models;
namespace FurnitureAssemblyDatebase.Implementations;
public class WarehouseStorageContract : IWarehouseStorageContract
{
private readonly FurnitureAssemblyDbContext _dbContext;
private readonly Mapper _mapper;
public WarehouseStorageContract(FurnitureAssemblyDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.AddMaps(typeof(Warehouse));
});
_mapper = new Mapper(config);
}
public List<WarehouseDataModel> GetList()
{
try
{
return [.. _dbContext.Warehouses.Select(x => _mapper.Map<WarehouseDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public WarehouseDataModel GetElementById(string id)
{
try
{
return _mapper.Map<WarehouseDataModel>(GetWarehouseById(id));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void AddElement(WarehouseDataModel warehouseDataModel)
{
try
{
_dbContext.Warehouses.Add(_mapper.Map<Warehouse>(warehouseDataModel));
_dbContext.SaveChanges();
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void UpdElement(WarehouseDataModel warehouseDataModel)
{
try
{
var element = GetWarehouseById(warehouseDataModel.Id) ?? throw new ElementNotFoundException(warehouseDataModel.Id);
_dbContext.Warehouses.Update(_mapper.Map(warehouseDataModel, element));
_dbContext.SaveChanges();
}
catch (ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void DelElement(string id)
{
try
{
var element = GetWarehouseById(id) ?? throw new ElementNotFoundException(id);
_dbContext.Warehouses.Remove(element);
_dbContext.SaveChanges();
}
catch (ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public bool CheckComponents(FurnitureDataModel furnitureDataModel)
{
using (var transaction = _dbContext.Database.BeginTransaction())
{
foreach (FurnitureComponentDataModel furniture_component in furnitureDataModel.Components)
{
var component = _dbContext.Components.FirstOrDefault(x => x.Id == furniture_component.ComponentId);
var warehouse = _dbContext.Warehouses.FirstOrDefault(x => x.Type == component.Type && x.Count >= furniture_component.Count);
if (warehouse == null)
{
transaction.Rollback();
return false;
}
if (warehouse.Count - furniture_component.Count == 0)
{
DelElement(warehouse.Id);
}
else
{
warehouse.Count -= furniture_component.Count;
}
}
transaction.Commit();
_dbContext.SaveChanges();
return true;
}
}
private Warehouse? GetWarehouseById(string id) => _dbContext.Warehouses.FirstOrDefault(x => x.Id == id);
}

View File

@@ -0,0 +1,143 @@
using AutoMapper;
using FurnitureAssemblyContracts.DataModels;
using FurnitureAssemblyContracts.Exceptions;
using FurnitureAssemblyContracts.StoragesContracts;
using FurnitureAssemblyDatebase.Models;
namespace FurnitureAssemblyDatebase.Implementations;
public class WorkerStorageContract : IWorkerStorageContract
{
private readonly FurnitureAssemblyDbContext _dbContext;
private readonly Mapper _mapper;
public WorkerStorageContract(FurnitureAssemblyDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Worker, WorkerDataModel>();
cfg.CreateMap<WorkerDataModel, Worker>();
});
_mapper = new Mapper(config);
}
public List<WorkerDataModel> GetList(bool onlyActive = true, string? postId = null, DateTime? fromBirthDate = null, DateTime? toBirthDate = null, DateTime? fromEmploymentDate = null, DateTime? toEmploymentDate = null)
{
try
{
var query = _dbContext.Workers.AsQueryable();
if (onlyActive)
{
query = query.Where(x => !x.IsDeleted);
}
if (postId is not null)
{
query = query.Where(x => x.PostId == postId);
}
if (fromBirthDate is not null && toBirthDate is not null)
{
query = query.Where(x => x.BirthDate >= fromBirthDate && x.BirthDate <= toBirthDate);
}
if (fromEmploymentDate is not null && toEmploymentDate is not null)
{
query = query.Where(x => x.EmploymentDate >= fromEmploymentDate && x.EmploymentDate <= toEmploymentDate);
}
return [.. query.Select(x => _mapper.Map<WorkerDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public WorkerDataModel? GetElementById(string id)
{
try
{
return _mapper.Map<WorkerDataModel>(GetWorkerById(id));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public WorkerDataModel? GetElementByFIO(string fio)
{
try
{
return
_mapper.Map<WorkerDataModel>(_dbContext.Workers.FirstOrDefault(x => x.FIO == fio));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void AddElement(WorkerDataModel workerDataModel)
{
try
{
_dbContext.Workers.Add(_mapper.Map<Worker>(workerDataModel));
_dbContext.SaveChanges();
}
catch (InvalidOperationException ex) when (ex.TargetSite?.Name == "ThrowIdentityConflict")
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("Id", workerDataModel.Id);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void UpdElement(WorkerDataModel workerDataModel)
{
try
{
var element = GetWorkerById(workerDataModel.Id) ?? throw new ElementNotFoundException(workerDataModel.Id);
_dbContext.Workers.Update(_mapper.Map(workerDataModel, element));
_dbContext.SaveChanges();
}
catch (ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void DelElement(string id)
{
try
{
var element = GetWorkerById(id) ?? throw new
ElementNotFoundException(id);
element.IsDeleted = true;
_dbContext.SaveChanges();
}
catch (ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
private Worker? GetWorkerById(string id) => _dbContext.Workers.FirstOrDefault(x => x.Id == id && !x.IsDeleted);
}

View File

@@ -0,0 +1,22 @@
using AutoMapper;
using FurnitureAssemblyContracts.DataModels;
using FurnitureAssemblyContracts.Enums;
using System.ComponentModel.DataAnnotations.Schema;
namespace FurnitureAssemblyDatebase.Models;
[AutoMap(typeof(ComponentDataModel), ReverseMap = true)]
public class Component
{
public required string Id { get; set; }
public required string Name { get; set; }
public string? PrevName { get; set; }
public string? PrevPrevName { get; set; }
public required ComponentType Type { get; set; }
[ForeignKey("ComponentId")]
public List<FurnitureComponent>? FurnitureComponents { get; set; }
[ForeignKey("SuppliesesId")]
public List<ComponentSupplies>? ComponentSupplies { get; set; }
[ForeignKey("WarehousesId")]
public List<ComponentWarehouse>? ComponentWarehouse { get; set; }
}

View File

@@ -0,0 +1,14 @@
using AutoMapper;
using FurnitureAssemblyContracts.DataModels;
namespace FurnitureAssemblyDatebase.Models;
[AutoMap(typeof(ComponentSuppliesDataModel), ReverseMap = true)]
public class ComponentSupplies
{
public required string SuppliesId { get; set; }
public required string ComponentId { get; set; }
public int Count { get; set; }
public Supplies? Supplies { get; set; }
public Component? Components { get; set; }
}

View File

@@ -0,0 +1,14 @@
using AutoMapper;
using FurnitureAssemblyContracts.DataModels;
namespace FurnitureAssemblyDatebase.Models;
[AutoMap(typeof(ComponentWarehouseDataModel), ReverseMap = true)]
public class ComponentWarehouse
{
public required string WarehouseId { get; set; }
public required string ComponentId { get; set; }
public int Count { get; set; }
public Warehouse? Warehouses { get; set; }
public Component? Components { get; set; }
}

View File

@@ -0,0 +1,13 @@
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace FurnitureAssemblyDatebase.Models;
public class Furniture
{
public required string Id { get; set; }
public required string Name { get; set; }
public int Weight { get; set; }
[ForeignKey("FurnitureId")]
public List<FurnitureComponent>? Components { get; set; }
}

View File

@@ -0,0 +1,10 @@
namespace FurnitureAssemblyDatebase.Models;
public class FurnitureComponent
{
public required string FurnitureId { get; set; }
public required string ComponentId { get; set; }
public int Count { get; set; }
public Furniture? Furniture { get; set; }
public Component? Component { get; set; }
}

View File

@@ -0,0 +1,12 @@
namespace FurnitureAssemblyDatebase.Models;
public class ManifacturingFurniture
{
public required string Id { get; set; }
public required string FurnitureId { get; set; }
public int Count { get; set; }
public DateTime ProductuionDate { get; set; }
public required string WorkerId { get; set ; }
public Furniture? Furniture { get; set; }
public Worker? Worker { get; set; }
}

View File

@@ -0,0 +1,14 @@
using FurnitureAssemblyContracts.Enums;
namespace FurnitureAssemblyDatebase.Models;
public class Post
{
public string Id { get; set; } = Guid.NewGuid().ToString();
public required string PostId { get; set; }
public required string PostName { get; set; }
public PostType PostType { get; set; }
public double Salary { get; set; }
public bool IsActual { get; set; }
public DateTime ChangeDate { get; set; }
}

View File

@@ -0,0 +1,10 @@
namespace FurnitureAssemblyDatebase.Models;
public class Salary
{
public string Id { get; set; } = Guid.NewGuid().ToString();
public required string WorkerId { get; set; }
public double WorkerSalary { get; set; }
public DateTime SalaryDate { get; set; }
public Worker? Worker { get; set; }
}

View File

@@ -0,0 +1,18 @@
using AutoMapper;
using FurnitureAssemblyContracts.DataModels;
using FurnitureAssemblyContracts.Enums;
using System.ComponentModel.DataAnnotations.Schema;
namespace FurnitureAssemblyDatebase.Models;
[AutoMap(typeof(SuppliesDataModel), ReverseMap = true)]
public class Supplies
{
public required string Id { get; set; }
public required ComponentType Type { get; set; }
public DateTime ProductuionDate { get; set; }
public required int Count { get; set; }
[ForeignKey("SuppliesId")]
public List<ComponentSupplies>? Components { get; set; }
}

View File

@@ -0,0 +1,17 @@
using AutoMapper;
using FurnitureAssemblyContracts.DataModels;
using FurnitureAssemblyContracts.Enums;
using System.ComponentModel.DataAnnotations.Schema;
namespace FurnitureAssemblyDatebase.Models;
[AutoMap(typeof(WarehouseDataModel), ReverseMap = true)]
public class Warehouse
{
public required string Id { get; set; }
public required ComponentType Type { get; set; }
public required int Count { get; set; }
[ForeignKey("WarehouseId")]
public List<ComponentWarehouse>? Components { get; set; }
}

View File

@@ -0,0 +1,19 @@
using FurnitureAssemblyContracts.Enums;
using System.ComponentModel.DataAnnotations.Schema;
namespace FurnitureAssemblyDatebase.Models;
public class Worker
{
public required string Id { get; set; }
public required string FIO { get; set; }
public required string PostId { get; set; }
public DateTime BirthDate { get; set; }
public DateTime EmploymentDate { get; set; }
public bool IsDeleted { get; set; }
public DateTime ChangeDate { get; set; }
[ForeignKey("WorkerId")]
public List<Salary>? Salaries { get; set; }
[ForeignKey("WorkerId")]
public List<ManifacturingFurniture>? ManifacturingFurniture { get; set; }
}

View File

@@ -11,18 +11,21 @@ namespace FurnitureAssemblyTests.BusinessLogicContractsTests;
public class FurnitureBusinessLogicContractTests
{
private IFurnitureBusinessLogicContract _furnitureBusinessLogicContract;
private Mock<IWarehouseStorageContract> _warehouseStorageContract;
private Mock<IFurnitureStorageContract> _furnitureStorageContract;
[OneTimeSetUp]
public void OneTimeSetUp()
{
_furnitureStorageContract = new Mock<IFurnitureStorageContract>();
_furnitureBusinessLogicContract = new FurnitureBusinessLogicContract(_furnitureStorageContract.Object, new Mock<ILogger>().Object);
_warehouseStorageContract = new Mock<IWarehouseStorageContract>();
_furnitureBusinessLogicContract = new FurnitureBusinessLogicContract(_furnitureStorageContract.Object, _warehouseStorageContract.Object, new Mock<ILogger>().Object);
}
[TearDown]
public void TearDown()
{
_warehouseStorageContract.Reset();
_furnitureStorageContract.Reset();
}
@@ -154,6 +157,7 @@ public class FurnitureBusinessLogicContractTests
//Arrange
var flag = false;
var record = new FurnitureDataModel(Guid.NewGuid().ToString(), "name", 10, [new FurnitureComponentDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]);
_warehouseStorageContract.Setup(x => x.CheckComponents(It.IsAny<FurnitureDataModel>())).Returns(true);
_furnitureStorageContract.Setup(x => x.AddElement(It.IsAny<FurnitureDataModel>())).Callback((FurnitureDataModel x) =>
{
flag = x.Id == record.Id && x.Name == record.Name;
@@ -161,6 +165,7 @@ public class FurnitureBusinessLogicContractTests
//Act
_furnitureBusinessLogicContract.InsertFurniture(record);
//Assert
_warehouseStorageContract.Verify(x => x.CheckComponents(It.IsAny<FurnitureDataModel>()), Times.Once);
_furnitureStorageContract.Verify(x => x.AddElement(It.IsAny<FurnitureDataModel>()), Times.Once);
Assert.That(flag);
}
@@ -169,10 +174,12 @@ public class FurnitureBusinessLogicContractTests
public void InsertFurnitures_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_warehouseStorageContract.Setup(x => x.CheckComponents(It.IsAny<FurnitureDataModel>())).Returns(true);
_furnitureStorageContract.Setup(x => x.AddElement(It.IsAny<FurnitureDataModel>())).Throws(new ElementExistsException("Data", "Data"));
//Act&Assert
Assert.That(() => _furnitureBusinessLogicContract.InsertFurniture(new(Guid.NewGuid().ToString(), "name", 10,
[new FurnitureComponentDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<ElementExistsException>());
_warehouseStorageContract.Verify(x => x.CheckComponents(It.IsAny<FurnitureDataModel>()), Times.Once);
_furnitureStorageContract.Verify(x => x.AddElement(It.IsAny<FurnitureDataModel>()), Times.Once);
}
@@ -197,19 +204,34 @@ public class FurnitureBusinessLogicContractTests
public void InsertFurnitures_StorageThrowError_ThrowException_Test()
{
//Arrange
_warehouseStorageContract.Setup(x => x.CheckComponents(It.IsAny<FurnitureDataModel>())).Returns(true);
_furnitureStorageContract.Setup(x => x.AddElement(It.IsAny<FurnitureDataModel>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _furnitureBusinessLogicContract.InsertFurniture(new(Guid.NewGuid().ToString(), "name", 10,
[new FurnitureComponentDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<StorageException>());
_warehouseStorageContract.Verify(x => x.CheckComponents(It.IsAny<FurnitureDataModel>()), Times.Once);
_furnitureStorageContract.Verify(x => x.AddElement(It.IsAny<FurnitureDataModel>()), Times.Once);
}
[Test]
public void InsertFurniture_InsufficientError_ThrowException_Test()
{
//Arrange
_warehouseStorageContract.Setup(x => x.CheckComponents(It.IsAny<FurnitureDataModel>())).Returns(false);
Assert.That(() => _furnitureBusinessLogicContract.InsertFurniture(new FurnitureDataModel(Guid.NewGuid().ToString(), "name", 10,
[new FurnitureComponentDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<InsufficientException>());
//Act&Assert
_warehouseStorageContract.Verify(x => x.CheckComponents(It.IsAny<FurnitureDataModel>()), Times.Once);
_furnitureStorageContract.Verify(x => x.UpdElement(It.IsAny<FurnitureDataModel>()), Times.Never);
}
[Test]
public void UpdateFurnitures_CorrectRecord_Test()
{
//Arrange
var flag = false;
var record = new FurnitureDataModel(Guid.NewGuid().ToString(), "name", 10, [new FurnitureComponentDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]);
_warehouseStorageContract.Setup(x => x.CheckComponents(It.IsAny<FurnitureDataModel>())).Returns(true);
_furnitureStorageContract.Setup(x => x.UpdElement(It.IsAny<FurnitureDataModel>())).Callback((FurnitureDataModel x) =>
{
flag = x.Id == record.Id && x.Name == record.Name;
@@ -217,6 +239,7 @@ public class FurnitureBusinessLogicContractTests
//Act
_furnitureBusinessLogicContract.UpdateFurniture(record);
//Assert
_warehouseStorageContract.Verify(x => x.CheckComponents(It.IsAny<FurnitureDataModel>()), Times.Once);
_furnitureStorageContract.Verify(x => x.UpdElement(It.IsAny<FurnitureDataModel>()), Times.Once);
Assert.That(flag);
}
@@ -225,10 +248,12 @@ public class FurnitureBusinessLogicContractTests
public void UpdateFurnitures_RecordWithIncorrectData_ThrowException_Test()
{
//Arrange
_warehouseStorageContract.Setup(x => x.CheckComponents(It.IsAny<FurnitureDataModel>())).Returns(true);
_furnitureStorageContract.Setup(x => x.UpdElement(It.IsAny<FurnitureDataModel>())).Throws(new ElementNotFoundException(""));
//Act&Assert
Assert.That(() => _furnitureBusinessLogicContract.UpdateFurniture(new(Guid.NewGuid().ToString(), "name", 10,
[new FurnitureComponentDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<ElementNotFoundException>());
_warehouseStorageContract.Verify(x => x.CheckComponents(It.IsAny<FurnitureDataModel>()), Times.Once);
_furnitureStorageContract.Verify(x => x.UpdElement(It.IsAny<FurnitureDataModel>()), Times.Once);
}
@@ -236,10 +261,12 @@ public class FurnitureBusinessLogicContractTests
public void UpdateFurnitures_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_warehouseStorageContract.Setup(x => x.CheckComponents(It.IsAny<FurnitureDataModel>())).Returns(true);
_furnitureStorageContract.Setup(x => x.UpdElement(It.IsAny<FurnitureDataModel>())).Throws(new ElementExistsException("Data", "Data"));
//Act&Assert
Assert.That(() => _furnitureBusinessLogicContract.UpdateFurniture(new(Guid.NewGuid().ToString(), "name", 10,
[new FurnitureComponentDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<ElementExistsException>());
_warehouseStorageContract.Verify(x => x.CheckComponents(It.IsAny<FurnitureDataModel>()), Times.Once);
_furnitureStorageContract.Verify(x => x.UpdElement(It.IsAny<FurnitureDataModel>()), Times.Once);
}
@@ -264,13 +291,27 @@ public class FurnitureBusinessLogicContractTests
public void UpdateFurnitures_StorageThrowError_ThrowException_Test()
{
//Arrange
_warehouseStorageContract.Setup(x => x.CheckComponents(It.IsAny<FurnitureDataModel>())).Returns(true);
_furnitureStorageContract.Setup(x => x.UpdElement(It.IsAny<FurnitureDataModel>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _furnitureBusinessLogicContract.UpdateFurniture(new(Guid.NewGuid().ToString(), "name", 10,
[new FurnitureComponentDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(),5)])), Throws.TypeOf<StorageException>());
_warehouseStorageContract.Verify(x => x.CheckComponents(It.IsAny<FurnitureDataModel>()), Times.Once);
_furnitureStorageContract.Verify(x => x.UpdElement(It.IsAny<FurnitureDataModel>()), Times.Once);
}
[Test]
public void UpdateFurniture_InsufficientError_ThrowException_Test()
{
//Arrange
_warehouseStorageContract.Setup(x => x.CheckComponents(It.IsAny<FurnitureDataModel>())).Returns(false);
//Act&Assert
Assert.That(() => _furnitureBusinessLogicContract.UpdateFurniture(new(Guid.NewGuid().ToString(), "name", 10,
[new FurnitureComponentDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<InsufficientException>());
_warehouseStorageContract.Verify(x => x.CheckComponents(It.IsAny<FurnitureDataModel>()), Times.Once);
_furnitureStorageContract.Verify(x => x.UpdElement(It.IsAny<FurnitureDataModel>()), Times.Never);
}
[Test]
public void DeleteFurnitures_CorrectRecord_Test()
{

View File

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

View File

@@ -0,0 +1,291 @@
using FurnitureAssemblyBusinessLogic.Implementations;
using FurnitureAssemblyContracts.BusinessLogicsContracts;
using FurnitureAssemblyContracts.DataModels;
using FurnitureAssemblyContracts.Enums;
using FurnitureAssemblyContracts.Exceptions;
using FurnitureAssemblyContracts.StoragesContracts;
using Microsoft.Extensions.Logging;
using Moq;
namespace FurnitureAssemblyTests.BusinessLogicContractsTests;
[TestFixture]
internal class WarehouseBusinessLogicContractTests
{
private IWarehouseBusinessLogicContract _warehouseBusinessLogicContract;
private Mock<IWarehouseStorageContract> _warehouseStorageContract;
[OneTimeSetUp]
public void OneTimeSetUp()
{
_warehouseStorageContract = new Mock<IWarehouseStorageContract>();
_warehouseBusinessLogicContract = new WarehouseBusinessLogicContract(_warehouseStorageContract.Object, new Mock<ILogger>().Object);
}
[TearDown]
public void TearDown()
{
_warehouseStorageContract.Reset();
}
public void GetAllSupplies_ReturnListOfRecords_Test()
{
// Arrange
var listOriginal = new List<WarehouseDataModel>()
{
new(Guid.NewGuid().ToString(), ComponentType.Panel, 1, []),
new(Guid.NewGuid().ToString(), ComponentType.Panel, 1, []),
new(Guid.NewGuid().ToString(), ComponentType.Panel, 1, []),
};
_warehouseStorageContract.Setup(x => x.GetList()).Returns(listOriginal);
// Act
var list = _warehouseBusinessLogicContract.GetAllComponents();
// Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.EquivalentTo(listOriginal));
}
[Test]
public void GetAllSupplies_ReturnEmptyList_Test()
{
// Arrange
_warehouseStorageContract.Setup(x => x.GetList()).Returns([]);
// Act
var list = _warehouseBusinessLogicContract.GetAllComponents();
// Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
_warehouseStorageContract.Verify(x => x.GetList(), Times.Once);
}
[Test]
public void GetAllSupplies_ReturnNull_ThrowException_Test()
{
// Arrange
_warehouseStorageContract.Setup(x => x.GetList()).Returns((List<WarehouseDataModel>)null);
// Act & Assert
Assert.That(() => _warehouseBusinessLogicContract.GetAllComponents(), Throws.TypeOf<NullListException>());
_warehouseStorageContract.Verify(x => x.GetList(), Times.Once);
}
[Test]
public void GetAllSupplies_StorageThrowError_ThrowException_Test()
{
// Arrange
_warehouseStorageContract.Setup(x => x.GetList()).Throws(new StorageException(new InvalidOperationException()));
// Act & Assert
Assert.That(() => _warehouseBusinessLogicContract.GetAllComponents(), Throws.TypeOf<StorageException>());
_warehouseStorageContract.Verify(x => x.GetList(), Times.Once);
}
[Test]
public void GetSuppliesByData_GetById_ReturnRecord_Test()
{
// Arrange
var id = Guid.NewGuid().ToString();
var record = new WarehouseDataModel(id, ComponentType.Panel, 1, []);
_warehouseStorageContract.Setup(x => x.GetElementById(id)).Returns(record);
// Act
var element = _warehouseBusinessLogicContract.GetComponentByData(id);
// Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.Id, Is.EqualTo(id));
_warehouseStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetComponentsByData_EmptyData_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _warehouseBusinessLogicContract.GetComponentByData(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _warehouseBusinessLogicContract.GetComponentByData(string.Empty), Throws.TypeOf<ArgumentNullException>());
_warehouseStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetSuppliesByData_GetById_NotFoundRecord_ThrowException_Test()
{
// Arrange
_warehouseStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new ElementNotFoundException(""));
// Act & Assert
Assert.That(() => _warehouseBusinessLogicContract.GetComponentByData(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_warehouseStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetSuppliesByData_StorageThrowError_ThrowException_Test()
{
// Arrange
_warehouseStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
// Act & Assert
Assert.That(() => _warehouseBusinessLogicContract.GetComponentByData(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_warehouseStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void InsertSupplies_CorrectRecord_Test()
{
// Arrange
var record = new WarehouseDataModel(Guid.NewGuid().ToString(), ComponentType.Panel, 1,
[new ComponentWarehouseDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]);
_warehouseStorageContract.Setup(x => x.AddElement(It.IsAny<WarehouseDataModel>()));
// Act
_warehouseBusinessLogicContract.InsertComponent(record);
// Assert
_warehouseStorageContract.Verify(x => x.AddElement(It.IsAny<WarehouseDataModel>()), Times.Once);
}
[Test]
public void InsertSupplies_RecordWithExistsData_ThrowException_Test()
{
// Arrange
_warehouseStorageContract.Setup(x => x.AddElement(It.IsAny<WarehouseDataModel>())).Throws(new ElementExistsException("Data", "Data"));
// Act & Assert
Assert.That(() => _warehouseBusinessLogicContract.InsertComponent(new(Guid.NewGuid().ToString(), ComponentType.Panel, 1,
[new ComponentWarehouseDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<ElementExistsException>());
_warehouseStorageContract.Verify(x => x.AddElement(It.IsAny<WarehouseDataModel>()), Times.Once);
}
[Test]
public void InsertSupplies_NullRecord_ThrowException_Test()
{
// Act & Assert
Assert.That(() => _warehouseBusinessLogicContract.InsertComponent(null), Throws.TypeOf<ArgumentNullException>());
_warehouseStorageContract.Verify(x => x.AddElement(It.IsAny<WarehouseDataModel>()), Times.Never);
}
[Test]
public void InsertComponents_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _warehouseBusinessLogicContract.InsertComponent(new WarehouseDataModel("id", ComponentType.Panel, 1, [])), Throws.TypeOf<ValidationException>());
_warehouseStorageContract.Verify(x => x.AddElement(It.IsAny<WarehouseDataModel>()), Times.Never);
}
[Test]
public void InsertSupplies_StorageThrowError_ThrowException_Test()
{
// Arrange
_warehouseStorageContract.Setup(x => x.AddElement(It.IsAny<WarehouseDataModel>())).Throws(new StorageException(new InvalidOperationException()));
// Act & Assert
Assert.That(() => _warehouseBusinessLogicContract.InsertComponent(new(Guid.NewGuid().ToString(), ComponentType.Panel, 1,
[new ComponentWarehouseDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<StorageException>());
_warehouseStorageContract.Verify(x => x.AddElement(It.IsAny<WarehouseDataModel>()), Times.Once);
}
[Test]
public void UpdateSupplies_CorrectRecord_Test()
{
// Arrange
var record = new WarehouseDataModel(Guid.NewGuid().ToString(), ComponentType.Panel, 1,
[new ComponentWarehouseDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]);
_warehouseStorageContract.Setup(x => x.UpdElement(It.IsAny<WarehouseDataModel>()));
// Act
_warehouseBusinessLogicContract.UpdateComponent(record);
// Assert
_warehouseStorageContract.Verify(x => x.UpdElement(It.IsAny<WarehouseDataModel>()), Times.Once);
}
[Test]
public void UpdateSupplies_RecordWithIncorrectData_ThrowException_Test()
{
// Arrange
_warehouseStorageContract.Setup(x => x.UpdElement(It.IsAny<WarehouseDataModel>())).Throws(new ElementNotFoundException(""));
// Act & Assert
Assert.That(() => _warehouseBusinessLogicContract.UpdateComponent(new(Guid.NewGuid().ToString(), ComponentType.Panel, 1,
[new ComponentWarehouseDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<ElementNotFoundException>());
_warehouseStorageContract.Verify(x => x.UpdElement(It.IsAny<WarehouseDataModel>()), Times.Once);
}
[Test]
public void UpdateSupplies_RecordWithExistsData_ThrowException_Test()
{
// Arrange
_warehouseStorageContract.Setup(x => x.UpdElement(It.IsAny<WarehouseDataModel>())).Throws(new ElementExistsException("Data", "Data"));
// Act & Assert
Assert.That(() => _warehouseBusinessLogicContract.UpdateComponent(new(Guid.NewGuid().ToString(), ComponentType.Panel, 1,
[new ComponentWarehouseDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<ElementExistsException>());
_warehouseStorageContract.Verify(x => x.UpdElement(It.IsAny<WarehouseDataModel>()), Times.Once);
}
[Test]
public void UpdateSupplies_NullRecord_ThrowException_Test()
{
// Act & Assert
Assert.That(() => _warehouseBusinessLogicContract.UpdateComponent(null), Throws.TypeOf<ArgumentNullException>());
_warehouseStorageContract.Verify(x => x.UpdElement(It.IsAny<WarehouseDataModel>()), Times.Never);
}
[Test]
public void UpdateComponents_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _warehouseBusinessLogicContract.UpdateComponent(new WarehouseDataModel(Guid.NewGuid().ToString(), ComponentType.Panel, 1, [])), Throws.TypeOf<ValidationException>());
_warehouseStorageContract.Verify(x => x.UpdElement(It.IsAny<WarehouseDataModel>()), Times.Never);
}
[Test]
public void UpdateSupplies_StorageThrowError_ThrowException_Test()
{
// Arrange
_warehouseStorageContract.Setup(x => x.UpdElement(It.IsAny<WarehouseDataModel>())).Throws(new StorageException(new InvalidOperationException()));
// Act & Assert
Assert.That(() => _warehouseBusinessLogicContract.UpdateComponent(new(Guid.NewGuid().ToString(), ComponentType.Panel, 1,
[new ComponentWarehouseDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<StorageException>());
_warehouseStorageContract.Verify(x => x.UpdElement(It.IsAny<WarehouseDataModel>()), Times.Once);
}
[Test]
public void DeleteComponents_CorrectRecord_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
var flag = false;
_warehouseStorageContract.Setup(x => x.DelElement(It.Is((string x) => x == id))).Callback(() => { flag = true; });
//Act
_warehouseBusinessLogicContract.DeleteComponent(id);
//Assert
_warehouseStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once); Assert.That(flag);
}
[Test]
public void DeleteComponents_RecordWithIncorrectId_ThrowException_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
_warehouseStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new ElementNotFoundException(id));
//Act&Assert
Assert.That(() => _warehouseBusinessLogicContract.DeleteComponent(Guid.NewGuid().ToString()),
Throws.TypeOf<ElementNotFoundException>());
_warehouseStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
}
[Test]
public void DeleteComponents_IdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _warehouseBusinessLogicContract.DeleteComponent(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _warehouseBusinessLogicContract.DeleteComponent(string.Empty), Throws.TypeOf<ArgumentNullException>());
_warehouseStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Never);
}
[Test]
public void DeleteComponents_IdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _warehouseBusinessLogicContract.DeleteComponent("id"),
Throws.TypeOf<ValidationException>());
_warehouseStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Never);
}
[Test]
public void DeleteComponents_StorageThrowError_ThrowException_Test()
{
//Arrange
_warehouseStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _warehouseBusinessLogicContract.DeleteComponent(Guid.NewGuid().ToString()),
Throws.TypeOf<StorageException>());
_warehouseStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
}
}

View File

@@ -29,7 +29,7 @@ internal class ComponentDataModelTests
{
var component = CreateDataModel(Guid.NewGuid().ToString(), null, ComponentType.Box);
Assert.That(() => component.Validate(), Throws.TypeOf<ValidationException>());
component = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, ComponentType.Box);
component = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, ComponentType.Box);
Assert.That(() => component.Validate(), Throws.TypeOf<ValidationException>());
}
@@ -40,6 +40,7 @@ internal class ComponentDataModelTests
Assert.That(() => component.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void AllFieldsIsCorrectTest()
{

View File

@@ -0,0 +1,70 @@
using FurnitureAssemblyContracts.DataModels;
using FurnitureAssemblyContracts.Exceptions;
namespace FurnitureAssemblyTests.DataModelsTests;
[TestFixture]
internal class ComponentSuppliesDataModelTests
{
[Test]
public void SuppliesIdIsNullOrEmptyTest()
{
var model = CreateDataModel(null, Guid.NewGuid().ToString(), 1);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
model = CreateDataModel(string.Empty, Guid.NewGuid().ToString(), 1);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void SuppliesIdIsNotGuidTest()
{
var model = CreateDataModel("id", Guid.NewGuid().ToString(), 1);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void ComponentIdIsNullOrEmptyTest()
{
var model = CreateDataModel(Guid.NewGuid().ToString(), null, 1);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
model = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, 1);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void ComponentIdIsNotGuidTest()
{
var model = CreateDataModel(Guid.NewGuid().ToString(), "id", 1);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void CountIsLessOrZeroTest()
{
var model = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 0);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
model = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), -1);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void AllFieldsIsCorrectTest()
{
var suppliesId = Guid.NewGuid().ToString();
var componentId = Guid.NewGuid().ToString();
var count = 1;
var model = CreateDataModel(suppliesId, componentId, count);
Assert.That(() => model.Validate(), Throws.Nothing);
Assert.Multiple(() =>
{
Assert.That(model.SuppliesId, Is.EqualTo(suppliesId));
Assert.That(model.ComponentId, Is.EqualTo(componentId));
Assert.That(model.Count, Is.EqualTo(count));
});
}
private static ComponentSuppliesDataModel CreateDataModel(string? suppliesId, string? componentId, int count)
=> new(suppliesId, componentId, count);
}

View File

@@ -0,0 +1,70 @@
using FurnitureAssemblyContracts.DataModels;
using FurnitureAssemblyContracts.Exceptions;
namespace FurnitureAssemblyTests.DataModelsTests;
[TestFixture]
internal class ComponentWarehouseDataModelTests
{
[Test]
public void WarehouseIdIsNullOrEmptyTest()
{
var model = CreateDataModel(null, Guid.NewGuid().ToString(), 1);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
model = CreateDataModel(string.Empty, Guid.NewGuid().ToString(), 1);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void WarehouseIdIsNotGuidTest()
{
var model = CreateDataModel("id", Guid.NewGuid().ToString(), 1);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void ComponentIdIsNullOrEmptyTest()
{
var model = CreateDataModel(Guid.NewGuid().ToString(), null, 1);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
model = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, 1);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void ComponentIdIsNotGuidTest()
{
var model = CreateDataModel(Guid.NewGuid().ToString(), "id", 1);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void CountIsLessOrZeroTest()
{
var model = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 0);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
model = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), -1);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void AllFieldsIsCorrectTest()
{
var warehouseId = Guid.NewGuid().ToString();
var componentId = Guid.NewGuid().ToString();
var count = 1;
var model = CreateDataModel(componentId, componentId, count);
Assert.That(() => model.Validate(), Throws.Nothing);
Assert.Multiple(() =>
{
Assert.That(model.WarehouseId, Is.EqualTo(componentId));
Assert.That(model.ComponentId, Is.EqualTo(componentId));
Assert.That(model.Count, Is.EqualTo(count));
});
}
private static ComponentWarehouseDataModel CreateDataModel(string? warehouseId, string? componentId, int count)
=> new(warehouseId, componentId, count);
}

View File

@@ -0,0 +1,77 @@
using FurnitureAssemblyContracts.DataModels;
using FurnitureAssemblyContracts.Enums;
using FurnitureAssemblyContracts.Exceptions;
namespace FurnitureAssemblyTests.DataModelsTests;
[TestFixture]
public class SuppliesDataModelTest
{
[Test]
public void IdIsNullOrEmptyTest()
{
var model = CreateDataModel(null, ComponentType.Handle, DateTime.Now, 1, CreateSuppliesDataModel());
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
model = CreateDataModel(string.Empty, ComponentType.Handle, DateTime.Now, 1, CreateSuppliesDataModel());
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void IdIsNotGuidTest()
{
var model = CreateDataModel("id", ComponentType.Handle, DateTime.Now, 1, CreateSuppliesDataModel());
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void TypeIsNoneTest()
{
var model = CreateDataModel(Guid.NewGuid().ToString(), ComponentType.None, DateTime.Now, 1, CreateSuppliesDataModel());
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void CountIsLessOrZeroTest()
{
var model = CreateDataModel(Guid.NewGuid().ToString(), ComponentType.None, DateTime.Now, 0, CreateSuppliesDataModel());
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
model = CreateDataModel(Guid.NewGuid().ToString(), ComponentType.None, DateTime.Now, -1, CreateSuppliesDataModel());
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void SuppliesIsEmptyOrNullTest()
{
var model = CreateDataModel(Guid.NewGuid().ToString(), ComponentType.None, DateTime.Now, 0, []);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
model = CreateDataModel(Guid.NewGuid().ToString(), ComponentType.None, DateTime.Now, 0, null);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void AllFieldsIsCorrectTest()
{
var id = Guid.NewGuid().ToString();
var type = ComponentType.Handle;
var date = DateTime.Now;
var count = 1;
var supplies = CreateSuppliesDataModel();
var model = CreateDataModel(id, type, date, count, supplies);
Assert.DoesNotThrow(() => model.Validate());
Assert.Multiple(() =>
{
Assert.That(model.Id, Is.EqualTo(id));
Assert.That(model.Type, Is.EqualTo(type));
Assert.That(model.ProductuionDate, Is.EqualTo(date));
Assert.That(model.Count, Is.EqualTo(count));
Assert.That(model.Components, Is.EqualTo(supplies));
});
}
private static SuppliesDataModel CreateDataModel(string? id, ComponentType type, DateTime date, int count, List<ComponentSuppliesDataModel> supplies)
=> new(id, type, date, count, supplies);
private static List<ComponentSuppliesDataModel> CreateSuppliesDataModel()
=> [new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 1)];
}

View File

@@ -0,0 +1,75 @@
using FurnitureAssemblyContracts.DataModels;
using FurnitureAssemblyContracts.Enums;
using FurnitureAssemblyContracts.Exceptions;
namespace FurnitureAssemblyTests.DataModelsTests;
[TestFixture]
internal class WorkhouseDataModelTests
{
[Test]
public void IdIsNullOrEmptyTest()
{
var model = CreateDataModel(null, ComponentType.Handle, 1, CreateWarehouseDataModel());
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
model = CreateDataModel(string.Empty, ComponentType.Handle, 1, CreateWarehouseDataModel());
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void IdIsNotGuidTest()
{
var model = CreateDataModel("id", ComponentType.Handle, 1, CreateWarehouseDataModel());
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void TypeIsNoneTest()
{
var model = CreateDataModel(Guid.NewGuid().ToString(), ComponentType.None, 1, CreateWarehouseDataModel());
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void CountIsLessOrZeroTest()
{
var model = CreateDataModel(Guid.NewGuid().ToString(), ComponentType.None, 0, CreateWarehouseDataModel());
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
model = CreateDataModel(Guid.NewGuid().ToString(), ComponentType.None, -1, CreateWarehouseDataModel());
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void WorkhouseIsEmptyOrNullTest()
{
var model = CreateDataModel(Guid.NewGuid().ToString(), ComponentType.None, 0, []);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
model = CreateDataModel(Guid.NewGuid().ToString(), ComponentType.None, 0, null);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void AllFieldsIsCorrectTest()
{
var id = Guid.NewGuid().ToString();
var type = ComponentType.Handle;
var count = 1;
var warehouse = CreateWarehouseDataModel();
var model = CreateDataModel(id, type, count, warehouse);
Assert.DoesNotThrow(() => model.Validate());
Assert.Multiple(() =>
{
Assert.That(model.Id, Is.EqualTo(id));
Assert.That(model.Type, Is.EqualTo(type));
Assert.That(model.Count, Is.EqualTo(count));
Assert.That(model.Components, Is.EqualTo(warehouse));
});
}
private static WarehouseDataModel CreateDataModel(string? id, ComponentType type, int count, List<ComponentWarehouseDataModel> warehouse)
=> new WarehouseDataModel(id, type, count, warehouse);
private static List<ComponentWarehouseDataModel> CreateWarehouseDataModel()
=> [new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 1)];
}

View File

@@ -20,6 +20,7 @@
<ItemGroup>
<ProjectReference Include="..\FurnitureAssemblyBusinessLogic\FurnitureAssemblyBusinessLogic.csproj" />
<ProjectReference Include="..\FurnitureAssemblyContracts\FurnitureAssemblyContracts.csproj" />
<ProjectReference Include="..\FurnitureAssemblyDatebase\FurnitureAssemblyDatebase.csproj" />
</ItemGroup>
<ItemGroup>

View File

@@ -0,0 +1,8 @@
using FurnitureAssemblyContracts.Infrastructure;
namespace FurnitureAssemblyTests.Infrastructure;
public class ConfigurationDateBaseTest : IConfigurationDatabase
{
public string ConnectionString => "Host=127.0.0.1;Port=5432;Database=furnitureassemblytest;";
}

View File

@@ -0,0 +1,24 @@
using FurnitureAssemblyDatebase;
using FurnitureAssemblyTests.Infrastructure;
namespace FurnitureAssemblyTests.StorageContractTests;
internal abstract class BaseStorageContractTest
{
protected FurnitureAssemblyDbContext FurnitureAssemblyDbContext { get; private set; }
[OneTimeSetUp]
public void OneTimeSetUp()
{
FurnitureAssemblyDbContext = new FurnitureAssemblyDbContext(new ConfigurationDateBaseTest());
FurnitureAssemblyDbContext.Database.EnsureDeleted();
FurnitureAssemblyDbContext.Database.EnsureCreated();
}
[OneTimeTearDown]
public void OneTimeTearDown()
{
FurnitureAssemblyDbContext.Database.EnsureDeleted();
FurnitureAssemblyDbContext.Dispose();
}
}

View File

@@ -0,0 +1,202 @@
using Castle.Components.DictionaryAdapter.Xml;
using FurnitureAssemblyContracts.DataModels;
using FurnitureAssemblyContracts.Enums;
using FurnitureAssemblyContracts.Exceptions;
using FurnitureAssemblyDatebase.Implementations;
using FurnitureAssemblyDatebase.Models;
using Microsoft.EntityFrameworkCore;
namespace FurnitureAssemblyTests.StorageContractTests;
[TestFixture]
internal class ComponentStorageContractTests : BaseStorageContractTest
{
private ComponentStorageContract _componentStorageContract;
[SetUp]
public void SetUp()
{
_componentStorageContract = new ComponentStorageContract(FurnitureAssemblyDbContext);
}
[TearDown]
public void TearDown()
{
FurnitureAssemblyDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Components\" CASCADE; ");
}
[Test]
public void Try_GetList_WhenHaveRecords_Test()
{
var component = InsertComponentToDatabaseAndReturn(Guid.NewGuid().ToString(), "Component 1");
InsertComponentToDatabaseAndReturn(Guid.NewGuid().ToString(), "Component 2");
InsertComponentToDatabaseAndReturn(Guid.NewGuid().ToString(), "Component 3");
var list = _componentStorageContract.GetList();
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(3));
AssertElement(list.First(), component);
}
[Test]
public void Try_GetList_WhenNoRecords_Test()
{
var list = _componentStorageContract.GetList();
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.Empty);
}
[Test]
public void Try_GetElementById_WhenHaveRecord_Test()
{
var component = InsertComponentToDatabaseAndReturn(Guid.NewGuid().ToString());
AssertElement(_componentStorageContract.GetElementById(component.Id), component);
}
[Test]
public void Try_GetElementById_WhenNoRecord_Test()
{
InsertComponentToDatabaseAndReturn(Guid.NewGuid().ToString());
Assert.That(() => _componentStorageContract.GetElementById(Guid.NewGuid().ToString()), Is.Null);
}
[Test]
public void Try_GetElementByName_WhenHaveRecord_Test()
{
var component = InsertComponentToDatabaseAndReturn(Guid.NewGuid().ToString(), "Unique Name");
AssertElement(_componentStorageContract.GetElementByName(component.Name), component);
}
[Test]
public void Try_GetElementByName_WhenNoRecord_Test()
{
InsertComponentToDatabaseAndReturn(Guid.NewGuid().ToString());
Assert.That(() => _componentStorageContract.GetElementByName("Non-existent Name"), Is.Null);
}
[Test]
public void Try_GetElementByOldName_WhenHaveRecord_Test()
{
var component = InsertComponentToDatabaseAndReturn(Guid.NewGuid().ToString(), "Current Name", ComponentType.Panel, "Previous Name", "Old Name");
AssertElement(_componentStorageContract.GetElementByOldName(component.PrevName!), component);
AssertElement(_componentStorageContract.GetElementByOldName(component.PrevPrevName!), component);
}
[Test]
public void Try_GetElementByOldName_WhenNoRecord_Test()
{
InsertComponentToDatabaseAndReturn(Guid.NewGuid().ToString());
Assert.That(() => _componentStorageContract.GetElementByOldName("Non-existent Old Name"), Is.Null);
}
[Test]
public void Try_AddElement_Test()
{
var component = CreateModel(Guid.NewGuid().ToString(), "New Component");
_componentStorageContract.AddElement(component);
AssertElement(GetComponentFromDatabase(component.Id), component);
}
[Test]
public void Try_AddElement_WhenHaveRecordWithSameId_Test()
{
var component = CreateModel(Guid.NewGuid().ToString(), "Unique Name");
InsertComponentToDatabaseAndReturn(component.Id);
Assert.That(() => _componentStorageContract.AddElement(component), Throws.TypeOf<ElementExistsException>());
}
[Test]
public void Try_AddElement_WhenHaveRecordWithSameName_Test()
{
var component = CreateModel(Guid.NewGuid().ToString(), "Duplicate Name");
InsertComponentToDatabaseAndReturn(Guid.NewGuid().ToString(), component.Name);
Assert.That(() => _componentStorageContract.AddElement(component), Throws.TypeOf<ElementExistsException>());
}
[Test]
public void Try_UpdElement_Test()
{
var component = CreateModel(Guid.NewGuid().ToString(), "Old Name", ComponentType.Panel, "Previous Name", "Old Name");
InsertComponentToDatabaseAndReturn(component.Id, name: component.Name!, type: component.Type!, prevName: component.PrevName!, prevPrevName: component.PrevPrevName!);
_componentStorageContract.UpdElement(component);
AssertElement(GetComponentFromDatabase(component.Id), component);
}
[Test]
public void Try_UpdElement_WhenNoChangeName_Test()
{
var component = CreateModel(Guid.NewGuid().ToString(), "Same Name", ComponentType.Panel, "Previous Name", "Old Name");
InsertComponentToDatabaseAndReturn(component.Id, component.Name, component.Type, component.PrevName, component.PrevPrevName);
_componentStorageContract.UpdElement(component);
AssertElement(GetComponentFromDatabase(component.Id), component);
}
[Test]
public void Try_UpdElement_WhenNoRecordWithThisId_Test()
{
Assert.That(() => _componentStorageContract.UpdElement(CreateModel(Guid.NewGuid().ToString())), Throws.TypeOf<ElementNotFoundException>());
}
[Test]
public void Try_UpdElement_WhenHaveRecordWithSameName_Test()
{
var component = CreateModel(Guid.NewGuid().ToString(), "Duplicate Name");
InsertComponentToDatabaseAndReturn(component.Id, "Old Name");
InsertComponentToDatabaseAndReturn(Guid.NewGuid().ToString(), component.Name);
Assert.That(() => _componentStorageContract.UpdElement(component), Throws.TypeOf<ElementExistsException>());
}
[Test]
public void Try_DelElement_Test()
{
var component = InsertComponentToDatabaseAndReturn(Guid.NewGuid().ToString());
_componentStorageContract.DelElement(component.Id);
var element = GetComponentFromDatabase(component.Id);
Assert.That(element, Is.Null);
}
[Test]
public void Try_DelElement_WhenNoRecordWithThisId_Test()
{
Assert.That(() => _componentStorageContract.DelElement(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
}
private Component InsertComponentToDatabaseAndReturn(string id, string name = "test", ComponentType type = ComponentType.Panel, string prevName = "prevname", string prevPrevName = "prevprevname")
{
var component = new Component { Id = id, Name = name, Type = type, PrevName = prevName, PrevPrevName = prevPrevName };
FurnitureAssemblyDbContext.Components.Add(component);
FurnitureAssemblyDbContext.SaveChanges();
return component;
}
private static void AssertElement(ComponentDataModel? actual, Component expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.Id, Is.EqualTo(expected.Id));
Assert.That(actual.Name, Is.EqualTo(expected.Name));
Assert.That(actual.PrevName, Is.EqualTo(expected.PrevName));
Assert.That(actual.PrevPrevName, Is.EqualTo(expected.PrevPrevName));
Assert.That(actual.Type, Is.EqualTo(expected.Type));
});
}
private static ComponentDataModel CreateModel(string id, string name = "test", ComponentType type = ComponentType.Panel, string prevName = "prevname", string prevPrevName = "prevprevname")
=> new(id, name, type, prevName, prevPrevName);
private Component? GetComponentFromDatabase(string id) => FurnitureAssemblyDbContext.Components.FirstOrDefault(x => x.Id == id);
private static void AssertElement(Component? actual, ComponentDataModel expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.Id, Is.EqualTo(expected.Id));
Assert.That(actual.Name, Is.EqualTo(expected.Name));
Assert.That(actual.PrevName, Is.EqualTo(expected.PrevName));
Assert.That(actual.PrevPrevName, Is.EqualTo(expected.PrevPrevName));
Assert.That(actual.Type, Is.EqualTo(expected.Type));
});
}
}

View File

@@ -0,0 +1,178 @@
using FurnitureAssemblyContracts.DataModels;
using FurnitureAssemblyContracts.Exceptions;
using FurnitureAssemblyDatebase;
using FurnitureAssemblyDatebase.Models;
using Microsoft.EntityFrameworkCore;
namespace FurnitureAssemblyTests.StorageContractTests;
[TestFixture]
internal class FurnitureStorageContractTests : BaseStorageContractTest
{
private FurnitureStorageContract _furnitureStorageContract;
[SetUp]
public void SetUp()
{
_furnitureStorageContract = new FurnitureStorageContract(FurnitureAssemblyDbContext);
}
[TearDown]
public void TearDown()
{
FurnitureAssemblyDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Furnitures\" CASCADE;");
}
[Test]
public void Try_GetList_WhenHaveRecords_Test()
{
var furniture = InsertFurnitureToDatabaseAndReturn(Guid.NewGuid().ToString(), "Furniture 1");
InsertFurnitureToDatabaseAndReturn(Guid.NewGuid().ToString(), "Furniture 2");
InsertFurnitureToDatabaseAndReturn(Guid.NewGuid().ToString(), "Furniture 3");
var list = _furnitureStorageContract.GetList();
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(3));
AssertElement(list.First(), furniture);
}
[Test]
public void Try_GetList_WhenNoRecords_Test()
{
var list = _furnitureStorageContract.GetList();
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.Empty);
}
[Test]
public void Try_GetElementById_WhenHaveRecord_Test()
{
var furniture = InsertFurnitureToDatabaseAndReturn(Guid.NewGuid().ToString());
AssertElement(_furnitureStorageContract.GetElementById(furniture.Id), furniture);
}
[Test]
public void Try_GetElementById_WhenNoRecord_Test()
{
InsertFurnitureToDatabaseAndReturn(Guid.NewGuid().ToString());
Assert.That(() => _furnitureStorageContract.GetElementById(Guid.NewGuid().ToString()), Is.Null);
}
[Test]
public void Try_GetElementByName_WhenHaveRecord_Test()
{
var furniture = InsertFurnitureToDatabaseAndReturn(Guid.NewGuid().ToString(), "Unique Name");
AssertElement(_furnitureStorageContract.GetElementByName(furniture.Name), furniture);
}
[Test]
public void Try_GetElementByName_WhenNoRecord_Test()
{
InsertFurnitureToDatabaseAndReturn(Guid.NewGuid().ToString());
Assert.That(() => _furnitureStorageContract.GetElementByName("Non-existent Name"), Is.Null);
}
[Test]
public void Try_AddElement_Test()
{
var furniture = CreateModel(Guid.NewGuid().ToString(), "New Furniture");
_furnitureStorageContract.AddElement(furniture);
AssertElement(GetFurnitureFromDatabase(furniture.Id), furniture);
}
[Test]
public void Try_AddElement_WhenHaveRecordWithSameId_Test()
{
var furniture = CreateModel(Guid.NewGuid().ToString(), "Unique Name");
InsertFurnitureToDatabaseAndReturn(furniture.Id);
Assert.That(() => _furnitureStorageContract.AddElement(furniture), Throws.TypeOf<ElementExistsException>());
}
[Test]
public void Try_AddElement_WhenHaveRecordWithSameName_Test()
{
var furniture = CreateModel(Guid.NewGuid().ToString(), "Duplicate Name");
InsertFurnitureToDatabaseAndReturn(Guid.NewGuid().ToString(), furniture.Name);
Assert.That(() => _furnitureStorageContract.AddElement(furniture), Throws.TypeOf<ElementExistsException>());
}
[Test]
public void Try_UpdElement_Test()
{
var furniture = CreateModel(Guid.NewGuid().ToString(), "Old Name");
InsertFurnitureToDatabaseAndReturn(furniture.Id, name: furniture.Name!);
_furnitureStorageContract.UpdElement(furniture);
AssertElement(GetFurnitureFromDatabase(furniture.Id), furniture);
}
[Test]
public void Try_UpdElement_WhenNoChangeName_Test()
{
var furniture = CreateModel(Guid.NewGuid().ToString(), "Same Name");
InsertFurnitureToDatabaseAndReturn(furniture.Id, furniture.Name);
_furnitureStorageContract.UpdElement(furniture);
AssertElement(GetFurnitureFromDatabase(furniture.Id), furniture);
}
[Test]
public void Try_UpdElement_WhenNoRecordWithThisId_Test()
{
Assert.That(() => _furnitureStorageContract.UpdElement(CreateModel(Guid.NewGuid().ToString())), Throws.TypeOf<ElementNotFoundException>());
}
[Test]
public void Try_UpdElement_WhenHaveRecordWithSameName_Test()
{
var furniture = CreateModel(Guid.NewGuid().ToString(), "Duplicate Name");
InsertFurnitureToDatabaseAndReturn(furniture.Id, "Old Name");
InsertFurnitureToDatabaseAndReturn(Guid.NewGuid().ToString(), furniture.Name);
Assert.That(() => _furnitureStorageContract.UpdElement(furniture), Throws.TypeOf<ElementExistsException>());
}
[Test]
public void Try_DelElement_Test()
{
var furniture = InsertFurnitureToDatabaseAndReturn(Guid.NewGuid().ToString());
_furnitureStorageContract.DelElement(furniture.Id);
var element = GetFurnitureFromDatabase(furniture.Id);
Assert.That(element, Is.Null);
}
[Test]
public void Try_DelElement_WhenNoRecordWithThisId_Test()
{
Assert.That(() => _furnitureStorageContract.DelElement(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
}
private Furniture InsertFurnitureToDatabaseAndReturn(string id, string name = "test")
{
var furniture = new Furniture { Id = id, Name = name };
FurnitureAssemblyDbContext.Furnitures.Add(furniture);
FurnitureAssemblyDbContext.SaveChanges();
return furniture;
}
private static void AssertElement(FurnitureDataModel? actual, Furniture expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.Id, Is.EqualTo(expected.Id));
Assert.That(actual.Name, Is.EqualTo(expected.Name));
});
}
private static FurnitureDataModel CreateModel(string id, string name = "test", int weight = 0)
=> new(id, name, weight, []);
private Furniture? GetFurnitureFromDatabase(string id) => FurnitureAssemblyDbContext.Furnitures.FirstOrDefault(x => x.Id == id);
private static void AssertElement(Furniture? actual, FurnitureDataModel expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.Id, Is.EqualTo(expected.Id));
Assert.That(actual.Name, Is.EqualTo(expected.Name));
});
}
}

View File

@@ -0,0 +1,178 @@
using FurnitureAssemblyContracts.DataModels;
using FurnitureAssemblyContracts.Exceptions;
using FurnitureAssemblyDatebase.Implementations;
using FurnitureAssemblyDatebase.Models;
using Microsoft.EntityFrameworkCore;
namespace FurnitureAssemblyTests.StorageContractTests;
[TestFixture]
internal class ManifacturingStorageContractTests : BaseStorageContractTest
{
private ManifacturingStorageContract _manifacturingStorageContract;
private Worker _worker;
private Furniture _furniture;
[SetUp]
public void SetUp()
{
_manifacturingStorageContract = new ManifacturingStorageContract(FurnitureAssemblyDbContext);
_worker = InsertWorkerToDatabaseAndReturn();
_furniture = InsertFurnitureToDatabaseAndReturn();
}
[TearDown]
public void TearDown()
{
FurnitureAssemblyDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Furnitures\" CASCADE;");
FurnitureAssemblyDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Manufacturing\" CASCADE;");
FurnitureAssemblyDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Workers\" CASCADE;");
}
[Test]
public void Try_GetList_WhenHaveRecords_Test()
{
var manufacturing = InsertManufacturingToDatabaseAndReturn(Guid.NewGuid().ToString(), _furniture.Id, 5, _worker.Id);
InsertManufacturingToDatabaseAndReturn(Guid.NewGuid().ToString(), _furniture.Id, 5, _worker.Id);
InsertManufacturingToDatabaseAndReturn(Guid.NewGuid().ToString(), _furniture.Id, 5, _worker.Id);
var list = _manifacturingStorageContract.GetList();
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(3));
AssertElement(list.First(), manufacturing);
}
[Test]
public void Try_GetList_WhenNoRecords_Test()
{
var list = _manifacturingStorageContract.GetList();
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.Empty);
}
[Test]
public void Try_GetList_ByWorker_Test()
{
var worker = InsertWorkerToDatabaseAndReturn("Other worker");
InsertManufacturingToDatabaseAndReturn(Guid.NewGuid().ToString(), _furniture.Id, 5, _worker.Id);
InsertManufacturingToDatabaseAndReturn(Guid.NewGuid().ToString(), _furniture.Id, 5, _worker.Id);
InsertManufacturingToDatabaseAndReturn(Guid.NewGuid().ToString(), _furniture.Id, 5, worker.Id);
var list = _manifacturingStorageContract.GetList(workerId: _worker.Id);
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(2));
Assert.That(list.All(x => x.WorkerId == _worker.Id));
}
[Test]
public void Try_GetList_ByFurniture_Test()
{
var furniture = InsertFurnitureToDatabaseAndReturn("Other furniture");
InsertManufacturingToDatabaseAndReturn(Guid.NewGuid().ToString(), _furniture.Id, 5, _worker.Id);
InsertManufacturingToDatabaseAndReturn(Guid.NewGuid().ToString(), _furniture.Id, 5, _worker.Id);
InsertManufacturingToDatabaseAndReturn(Guid.NewGuid().ToString(), furniture.Id, 5, _worker.Id);
var list = _manifacturingStorageContract.GetList(furnitureId: _furniture.Id);
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(2));
Assert.That(list.All(x => x.FurnitureId == _furniture.Id));
}
[Test]
public void Try_GetElementById_WhenHaveRecord_Test()
{
var manufacturing = InsertManufacturingToDatabaseAndReturn(Guid.NewGuid().ToString(), _furniture.Id, 5, _worker.Id);
AssertElement(_manifacturingStorageContract.GetElementById(manufacturing.Id), manufacturing);
}
[Test]
public void Try_GetElementById_WhenNoRecord_Test()
{
InsertManufacturingToDatabaseAndReturn(Guid.NewGuid().ToString(), _furniture.Id, 5, _worker.Id);
Assert.That(() => _manifacturingStorageContract.GetElementById(Guid.NewGuid().ToString()), Is.Null);
}
[Test]
public void Try_AddElement_Test()
{
var manufacturing = CreateModel(Guid.NewGuid().ToString(), _furniture.Id, 5, _worker.Id);
_manifacturingStorageContract.AddElement(manufacturing);
AssertElement(GetManufacturingFromDatabaseById(manufacturing.Id), manufacturing);
}
[Test]
public void Try_AddElement_WhenHaveRecordWithSameId_Test()
{
var manufacturing = CreateModel(Guid.NewGuid().ToString(), _furniture.Id, 5, _worker.Id);
InsertManufacturingToDatabaseAndReturn(manufacturing.Id, _furniture.Id, 5, _worker.Id);
Assert.That(() => _manifacturingStorageContract.AddElement(manufacturing), Throws.TypeOf<StorageException>());
}
[Test]
public void Try_UpdElement_Test()
{
var manufacturing = CreateModel(Guid.NewGuid().ToString(), _furniture.Id, 5, _worker.Id);
InsertManufacturingToDatabaseAndReturn(manufacturing.Id, _furniture.Id, 5, _worker.Id);
_manifacturingStorageContract.UpdElement(manufacturing);
AssertElement(GetManufacturingFromDatabaseById(manufacturing.Id), manufacturing);
}
[Test]
public void Try_UpdElement_WhenNoRecordWithThisId_Test()
{
Assert.That(() => _manifacturingStorageContract.UpdElement(CreateModel(Guid.NewGuid().ToString(), _furniture.Id, 5, _worker.Id)), Throws.TypeOf<ElementNotFoundException>());
}
private Worker InsertWorkerToDatabaseAndReturn(string workerFIO = "fio")
{
var worker = new Worker() { Id = Guid.NewGuid().ToString(), PostId = Guid.NewGuid().ToString(), FIO = workerFIO, IsDeleted = false };
FurnitureAssemblyDbContext.Workers.Add(worker);
FurnitureAssemblyDbContext.SaveChanges();
return worker;
}
private Furniture InsertFurnitureToDatabaseAndReturn(string furnitureName = "furniture", int weight = 5)
{
var furniture = new Furniture() { Id = Guid.NewGuid().ToString(), Name = furnitureName, Weight = weight };
FurnitureAssemblyDbContext.Furnitures.Add(furniture);
FurnitureAssemblyDbContext.SaveChanges();
return furniture;
}
private ManifacturingFurniture InsertManufacturingToDatabaseAndReturn(string id, string furnitureId, int count, string workerId)
{
var manufacturing = new ManifacturingFurniture() { Id = id, FurnitureId = furnitureId, Count = count, WorkerId = workerId };
FurnitureAssemblyDbContext.Manufacturing.Add(manufacturing);
FurnitureAssemblyDbContext.SaveChanges();
return manufacturing;
}
private static void AssertElement(ManifacturingFurnitureDataModel? actual, ManifacturingFurniture expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.Id, Is.EqualTo(expected.Id));
Assert.That(actual.WorkerId, Is.EqualTo(expected.WorkerId));
Assert.That(actual.Count, Is.EqualTo(expected.Count));
Assert.That(actual.FurnitureId, Is.EqualTo(expected.FurnitureId));
});
}
private static ManifacturingFurnitureDataModel CreateModel(string id, string furnitureId, int count, string workerId)
{
return new(id, furnitureId, count, workerId);
}
private ManifacturingFurniture? GetManufacturingFromDatabaseById(string id) =>
FurnitureAssemblyDbContext.Manufacturing.FirstOrDefault(x => x.Id == id);
private static void AssertElement(ManifacturingFurniture? actual, ManifacturingFurnitureDataModel expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.Id, Is.EqualTo(expected.Id));
Assert.That(actual.WorkerId, Is.EqualTo(expected.WorkerId));
Assert.That(actual.Count, Is.EqualTo(expected.Count));
Assert.That(actual.FurnitureId, Is.EqualTo(expected.FurnitureId));
});
}
}

View File

@@ -0,0 +1,337 @@
using FurnitureAssemblyContracts.DataModels;
using FurnitureAssemblyContracts.Enums;
using FurnitureAssemblyContracts.Exceptions;
using FurnitureAssemblyDatebase.Implementations;
using FurnitureAssemblyDatebase.Models;
using Microsoft.EntityFrameworkCore;
namespace FurnitureAssemblyTests.StorageContractTests;
[TestFixture]
internal class PostStorageContractTests : BaseStorageContractTest
{
private PostStorageContract _postStorageContract;
[SetUp]
public void SetUp()
{
_postStorageContract = new PostStorageContract(FurnitureAssemblyDbContext);
}
[TearDown]
public void TearDown()
{
FurnitureAssemblyDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Posts\"CASCADE; ");
}
[Test]
public void Try_GetList_WhenHaveRecords_Test()
{
var post = InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(),
"name 1");
InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 2");
InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 3");
var list = _postStorageContract.GetList();
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(3));
AssertElement(list.First(x => x.Id == post.PostId), post);
}
[Test]
public void Try_GetList_WhenNoRecords_Test()
{
var list = _postStorageContract.GetList();
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.Empty);
}
[Test]
public void Try_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);
var list = _postStorageContract.GetPostWithHistory(postId);
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(2));
}
[Test]
public void Try_GetPostWithHistory_WhenNoRecords_Test()
{
var postId = Guid.NewGuid().ToString();
InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 1", isActual: true);
InsertPostToDatabaseAndReturn(postId, "name 2", isActual: true);
InsertPostToDatabaseAndReturn(postId, "name 2", isActual: false);
var list = _postStorageContract.GetPostWithHistory(Guid.NewGuid().ToString());
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
}
[Test]
public void Try_GetElementById_WhenHaveRecord_Test()
{
var post = InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString());
AssertElement(_postStorageContract.GetElementById(post.PostId), post);
}
[Test]
public void Try_GetElementById_WhenNoRecord_Test()
{
InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString());
Assert.That(() => _postStorageContract.GetElementById(Guid.NewGuid().ToString()), Is.Null);
}
[Test]
public void Try_GetElementById_WhenRecordHasDeleted_Test()
{
var post = InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), isActual: false);
Assert.That(() => _postStorageContract.GetElementById(post.PostId), Is.Null);
}
[Test]
public void Try_GetElementById_WhenTrySearchById_Test()
{
var post = InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString());
Assert.That(() => _postStorageContract.GetElementById(post.Id), Is.Null);
}
[Test]
public void Try_GetElementByName_WhenHaveRecord_Test()
{
var post = InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString());
AssertElement(_postStorageContract.GetElementByName(post.PostName),
post);
}
[Test]
public void Try_GetElementByName_WhenNoRecord_Test()
{
InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString());
Assert.That(() => _postStorageContract.GetElementByName("name"), Is.Null);
}
[Test]
public void Try_GetElementByName_WhenRecordHasDeleted_Test()
{
var post = InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), isActual: false);
Assert.That(() => _postStorageContract.GetElementById(post.PostName), Is.Null);
}
[Test]
public void Try_AddElement_Test()
{
var post = CreateModel(Guid.NewGuid().ToString(), isActual: true);
_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));
}
[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);
Assert.That(() => _postStorageContract.AddElement(post),
Throws.TypeOf<ElementExistsException>());
}
[Test]
public void
Try_AddElement_WhenHaveRecordWithSamePostIdAndActualIsTrue_Test()
{
var post = CreateModel(Guid.NewGuid().ToString(), isActual: true);
InsertPostToDatabaseAndReturn(post.Id, isActual: true);
Assert.That(() => _postStorageContract.AddElement(post),
Throws.TypeOf<ElementExistsException>());
}
[Test]
public void Try_UpdElement_Test()
{
var post = CreateModel(Guid.NewGuid().ToString());
InsertPostToDatabaseAndReturn(post.Id, isActual: true);
_postStorageContract.UpdElement(post);
var posts = FurnitureAssemblyDbContext.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));
}
[Test]
public void Try_UpdElement_WhenNoRecordWithThisId_Test()
{
Assert.That(() => _postStorageContract.UpdElement(CreateModel(Guid.NewGuid().ToString())),
Throws.TypeOf<ElementNotFoundException>());
}
[Test]
public void Try_UpdElement_WhenHaveRecordWithSameName_Test()
{
var post = CreateModel(Guid.NewGuid().ToString(), "New Name");
InsertPostToDatabaseAndReturn(post.Id, postName: "name");
InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), postName: post.PostName);
Assert.That(() => _postStorageContract.UpdElement(post),
Throws.TypeOf<ElementExistsException>());
}
[Test]
public void Try_UpdElement_WhenRecordWasDeleted_Test()
{
var post = CreateModel(Guid.NewGuid().ToString());
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);
_postStorageContract.DelElement(post.PostId);
var element = GetPostFromDatabaseByPostId(post.PostId);
Assert.Multiple(() =>
{
Assert.That(element, Is.Not.Null);
Assert.That(!element!.IsActual);
});
}
[Test]
public void Try_DelElement_WhenNoRecordWithThisId_Test()
{
Assert.That(() => _postStorageContract.DelElement(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
}
[Test]
public void Try_DelElement_WhenRecordWasDeleted_Test()
{
var post = InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), 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);
_postStorageContract.ResElement(post.PostId);
var element = GetPostFromDatabaseByPostId(post.PostId);
Assert.Multiple(() =>
{
Assert.That(element, Is.Not.Null);
Assert.That(element!.IsActual);
});
}
[Test]
public void Try_ResElement_WhenNoRecordWithThisId_Test()
{
Assert.That(() => _postStorageContract.ResElement(Guid.NewGuid().ToString()),
Throws.TypeOf<ElementNotFoundException>());
}
[Test]
public void Try_ResElement_WhenRecordNotWasDeleted_Test()
{
var post = InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), isActual: true);
Assert.That(() => _postStorageContract.ResElement(post.PostId), Throws.Nothing);
}
private Post InsertPostToDatabaseAndReturn(string id, string postName = "test", PostType postType = PostType.Builder, 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
};
FurnitureAssemblyDbContext.Posts.Add(post);
FurnitureAssemblyDbContext.SaveChanges();
return post;
}
private static void AssertElement(PostDataModel? actual, Post expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.Id, Is.EqualTo(expected.PostId));
Assert.That(actual.PostName, Is.EqualTo(expected.PostName)); Assert.That(actual.PostType, Is.EqualTo(expected.PostType));
Assert.That(actual.Salary, Is.EqualTo(expected.Salary));
Assert.That(actual.IsActual, Is.EqualTo(expected.IsActual));
});
}
private static PostDataModel CreateModel(string postId, string postName = "test", PostType postType = PostType.Builder, double salary = 10, bool isActual = false, DateTime? changeDate = null)
=> new(postId, postName, postType, salary, isActual, changeDate ?? DateTime.UtcNow);
private Post? GetPostFromDatabaseByPostId(string id) => FurnitureAssemblyDbContext.Posts
.Where(x => x.PostId == id).OrderByDescending(x => x.ChangeDate).FirstOrDefault();
private static void AssertElement(Post? actual, PostDataModel expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.PostId, Is.EqualTo(expected.Id));
Assert.That(actual.PostName, Is.EqualTo(expected.PostName));
Assert.That(actual.PostType, Is.EqualTo(expected.PostType));
Assert.That(actual.Salary, Is.EqualTo(expected.Salary));
Assert.That(actual.IsActual, Is.EqualTo(expected.IsActual));
});
}
}

View File

@@ -0,0 +1,168 @@
using FurnitureAssemblyContracts.DataModels;
using FurnitureAssemblyDatebase;
using FurnitureAssemblyDatebase.Implementations;
using FurnitureAssemblyDatebase.Models;
using Microsoft.EntityFrameworkCore;
namespace FurnitureAssemblyTests.StorageContractTests;
[TestFixture]
internal class SalaryStorageContractTests : BaseStorageContractTest
{
private SalaryStorageContract _salaryStorageContract;
private Worker _worker;
[SetUp]
public void SetUp()
{
_salaryStorageContract = new SalaryStorageContract(FurnitureAssemblyDbContext);
_worker = InsertWorkerToDatabaseAndReturn();
}
[TearDown]
public void TearDown()
{
FurnitureAssemblyDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Salaries\"CASCADE; ");
FurnitureAssemblyDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Workers\"CASCADE; ");
}
[Test]
public void Try_GetList_WhenHaveRecords_Test()
{
var salary = InsertSalaryToDatabaseAndReturn(_worker.Id, workerSalary: 100);
InsertSalaryToDatabaseAndReturn(_worker.Id);
InsertSalaryToDatabaseAndReturn(_worker.Id);
var list = _salaryStorageContract.GetList(DateTime.UtcNow.AddDays(-10), DateTime.UtcNow.AddDays(10));
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(3));
AssertElement(list.First(), salary);
}
[Test]
public void Try_GetList_WhenNoRecords_Test()
{
var list = _salaryStorageContract.GetList(DateTime.UtcNow.AddDays(-10), DateTime.UtcNow.AddDays(10));
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.Empty);
}
[Test]
public void Try_GetList_OnlyInDatePeriod_Test()
{
InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate: DateTime.UtcNow.AddDays(-2));
InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate: DateTime.UtcNow.AddDays(-1).AddMinutes(-5));
InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate: DateTime.UtcNow.AddDays(-1).AddMinutes(5));
InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate: DateTime.UtcNow.AddDays(1).AddMinutes(-5));
InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate: DateTime.UtcNow.AddDays(1).AddMinutes(5));
InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate: DateTime.UtcNow.AddDays(-2));
var list = _salaryStorageContract.GetList(DateTime.UtcNow.AddDays(-1), DateTime.UtcNow.AddDays(1));
Assert.That(list, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(list, Has.Count.EqualTo(2));
});
}
[Test]
public void Try_GetList_ByWorker_Test()
{
var worker = InsertWorkerToDatabaseAndReturn("name 2");
InsertSalaryToDatabaseAndReturn(_worker.Id);
InsertSalaryToDatabaseAndReturn(_worker.Id);
InsertSalaryToDatabaseAndReturn(worker.Id);
var list = _salaryStorageContract.GetList(DateTime.UtcNow.AddDays(-
1), DateTime.UtcNow.AddDays(1), _worker.Id);
Assert.That(list, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(list, Has.Count.EqualTo(2));
Assert.That(list.All(x => x.WorkerId == _worker.Id));
});
}
[Test]
public void Try_GetList_ByWorkerOnlyInDatePeriod_Test()
{
var worker = InsertWorkerToDatabaseAndReturn("name 2");
InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate:
DateTime.UtcNow.AddDays(-2));
InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate:
DateTime.UtcNow.AddDays(-1).AddMinutes(5));
InsertSalaryToDatabaseAndReturn(worker.Id, salaryDate:
DateTime.UtcNow.AddDays(-1).AddMinutes(5));
InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate:
DateTime.UtcNow.AddDays(1).AddMinutes(-5));
InsertSalaryToDatabaseAndReturn(worker.Id, salaryDate:
DateTime.UtcNow.AddDays(1).AddMinutes(-5));
InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate:
DateTime.UtcNow.AddDays(-2));
var list = _salaryStorageContract.GetList(DateTime.UtcNow.AddDays(-
1), DateTime.UtcNow.AddDays(1), _worker.Id);
Assert.That(list, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(list, Has.Count.EqualTo(2));
Assert.That(list.All(x => x.WorkerId == _worker.Id));
});
}
[Test]
public void Try_AddElement_Test()
{
var salary = CreateModel(_worker.Id);
_salaryStorageContract.AddElement(salary);
AssertElement(GetSalaryFromDatabaseByWorkerId(_worker.Id), salary);
}
private Worker InsertWorkerToDatabaseAndReturn(string workerFIO = "fio")
{
var worker = new Worker()
{
Id = Guid.NewGuid().ToString(),
PostId = Guid.NewGuid().ToString(),
FIO = workerFIO,
IsDeleted = false
};
FurnitureAssemblyDbContext.Workers.Add(worker);
FurnitureAssemblyDbContext.SaveChanges();
return worker;
}
private Salary InsertSalaryToDatabaseAndReturn(string workerId, double
workerSalary = 1, DateTime? salaryDate = null)
{
var salary = new Salary()
{
WorkerId = workerId,
WorkerSalary = workerSalary,
SalaryDate = salaryDate ?? DateTime.UtcNow
};
FurnitureAssemblyDbContext.Salaries.Add(salary);
FurnitureAssemblyDbContext.SaveChanges();
return salary;
}
private static void AssertElement(SalaryDataModel? actual, Salary expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.WorkerId, Is.EqualTo(expected.WorkerId));
Assert.That(actual.Salary, Is.EqualTo(expected.WorkerSalary));
});
}
private static SalaryDataModel CreateModel(string workerId, double workerSalary = 1, DateTime? salaryDate = null)
=> new(workerId, salaryDate ?? DateTime.UtcNow, workerSalary);
private Salary? GetSalaryFromDatabaseByWorkerId(string id) => FurnitureAssemblyDbContext.Salaries.FirstOrDefault(x => x.WorkerId == id);
private static void AssertElement(Salary? actual, SalaryDataModel expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.WorkerId, Is.EqualTo(expected.WorkerId));
Assert.That(actual.WorkerSalary, Is.EqualTo(expected.Salary));
});
}
}

View File

@@ -0,0 +1,187 @@
using FurnitureAssemblyContracts.DataModels;
using FurnitureAssemblyContracts.Exceptions;
using FurnitureAssemblyDatebase.Implementations;
using FurnitureAssemblyDatebase.Models;
using FurnitureAssemblyDatebase;
using Microsoft.EntityFrameworkCore;
using FurnitureAssemblyContracts.Enums;
namespace FurnitureAssemblyTests.StorageContractTests;
[TestFixture]
internal class SuppliesStorageContractTests : BaseStorageContractTest
{
private SuppliesStorageContract _suppliesStorageContract;
private Component _component;
[SetUp]
public void SetUp()
{
_suppliesStorageContract = new SuppliesStorageContract(FurnitureAssemblyDbContext);
_component = InsertComponentToDatabaseAndReturn();
}
[TearDown]
public void TearDown()
{
FurnitureAssemblyDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Supplieses\" CASCADE;");
FurnitureAssemblyDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Components\" CASCADE;");
}
[Test]
public void Try_GetList_WhenHaveRecords_Test()
{
var supply = InsertSupplyToDatabaseAndReturn(Guid.NewGuid().ToString(), ComponentType.Handle, 5);
InsertSupplyToDatabaseAndReturn(Guid.NewGuid().ToString(), ComponentType.Handle, 5);
InsertSupplyToDatabaseAndReturn(Guid.NewGuid().ToString(), ComponentType.Handle, 5);
var list = _suppliesStorageContract.GetList();
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(3));
AssertElement(list.First(), supply);
}
[Test]
public void Try_GetList_WhenNoRecords_Test()
{
var list = _suppliesStorageContract.GetList();
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.Empty);
}
[Test]
public void Try_GetElementById_WhenHaveRecord_Test()
{
var supply = InsertSupplyToDatabaseAndReturn(Guid.NewGuid().ToString(), ComponentType.Handle, 5);
AssertElement(_suppliesStorageContract.GetElementById(supply.Id), supply);
}
[Test]
public void Try_GetElementById_WhenNoRecord_Test()
{
Assert.That(() => _suppliesStorageContract.GetElementById(Guid.NewGuid().ToString()), Is.Null);
}
[Test]
public void Try_AddElement_Test()
{
var supply = CreateModel(Guid.NewGuid().ToString(), ComponentType.Handle, 5, [_component.Id]);
_suppliesStorageContract.AddElement(supply);
AssertElement(GetSupplyFromDatabaseById(supply.Id), supply);
}
[Test]
public void Try_AddElement_WhenHaveRecordWithSameId_Test()
{
var supply = CreateModel(Guid.NewGuid().ToString(), ComponentType.Handle, 5, [_component.Id]);
InsertSupplyToDatabaseAndReturn(supply.Id, ComponentType.Handle, 5, [(_component.Id, 3)]);
Assert.That(() => _suppliesStorageContract.AddElement(supply), Throws.TypeOf<StorageException>());
}
[Test]
public void Try_UpdElement_Test()
{
var supply = CreateModel(Guid.NewGuid().ToString(), ComponentType.Handle, 5, [_component.Id]);
InsertSupplyToDatabaseAndReturn(supply.Id, ComponentType.Legs, 5, null);
_suppliesStorageContract.UpdElement(supply);
AssertElement(GetSupplyFromDatabaseById(supply.Id), supply);
}
[Test]
public void Try_UpdElement_WhenNoRecordWithThisId_Test()
{
Assert.That(() => _suppliesStorageContract.UpdElement(CreateModel(Guid.NewGuid().ToString(), ComponentType.Handle, 5, [_component.Id])), Throws.TypeOf<ElementNotFoundException>());
}
private Component InsertComponentToDatabaseAndReturn()
{
var component = new Component { Id = Guid.NewGuid().ToString(), Name = "Test Component", Type = ComponentType.Panel };
FurnitureAssemblyDbContext.Components.Add(component);
FurnitureAssemblyDbContext.SaveChanges();
return component;
}
private Supplies InsertSupplyToDatabaseAndReturn(string id, ComponentType type, int count, List<(string, int)>? components = null)
{
var supply = new Supplies { Id = id, Type = type, ProductuionDate = DateTime.UtcNow, Count = count, Components = [] };
if (components is not null)
{
foreach (var elem in components)
{
supply.Components.Add(new ComponentSupplies { SuppliesId = supply.Id, ComponentId = elem.Item1, Count = elem.Item2 });
}
}
FurnitureAssemblyDbContext.Supplieses.Add(supply);
FurnitureAssemblyDbContext.SaveChanges();
return supply;
}
private static void AssertElement(SuppliesDataModel? actual, Supplies expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.Id, Is.EqualTo(expected.Id));
Assert.That(actual.Type, Is.EqualTo(expected.Type));
Assert.That(actual.ProductuionDate, Is.EqualTo(expected.ProductuionDate));
Assert.That(actual.Count, Is.EqualTo(expected.Count));
});
if (expected.Components is not null)
{
Assert.That(actual.Components, Is.Not.Null);
Assert.That(actual.Components, Has.Count.EqualTo(expected.Components.Count));
for (int i = 0; i < actual.Components.Count; ++i)
{
Assert.Multiple(() =>
{
Assert.That(actual.Components[i].ComponentId, Is.EqualTo(expected.Components[i].ComponentId));
Assert.That(actual.Components[i].Count, Is.EqualTo(expected.Components[i].Count));
});
}
}
else
{
Assert.That(actual.Components, Is.Null);
}
}
private static void AssertElement(Supplies? actual, SuppliesDataModel expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.Id, Is.EqualTo(expected.Id));
Assert.That(actual.Type, Is.EqualTo(expected.Type));
Assert.That(actual.ProductuionDate, Is.EqualTo(expected.ProductuionDate));
Assert.That(actual.Count, Is.EqualTo(expected.Count));
});
if (expected.Components is not null)
{
Assert.That(actual.Components, Is.Not.Null);
Assert.That(actual.Components, Has.Count.EqualTo(expected.Components.Count));
for (int i = 0; i < actual.Components.Count; ++i)
{
Assert.Multiple(() =>
{
Assert.That(actual.Components[i].ComponentId, Is.EqualTo(expected.Components[i].ComponentId));
Assert.That(actual.Components[i].Count, Is.EqualTo(expected.Components[i].Count));
});
}
}
else
{
Assert.That(actual.Components, Is.Null);
}
}
private static SuppliesDataModel CreateModel(string id, ComponentType type, int count, List<string> componentsIds)
{
var components = componentsIds.Select(x => new ComponentSuppliesDataModel(id, x, 1)).ToList();
return new(id, type, DateTime.UtcNow, count, components);
}
private Supplies? GetSupplyFromDatabaseById(string id)
{
return FurnitureAssemblyDbContext.Supplieses.FirstOrDefault(x => x.Id == id);
}
}

View File

@@ -0,0 +1,209 @@
using FurnitureAssemblyContracts.DataModels;
using FurnitureAssemblyContracts.Enums;
using FurnitureAssemblyContracts.Exceptions;
using FurnitureAssemblyDatebase.Implementations;
using FurnitureAssemblyDatebase.Models;
using Microsoft.EntityFrameworkCore;
namespace FurnitureAssemblyTests.StorageContractTests;
internal class WarehouseStorageContractTests : BaseStorageContractTest
{
private WarehouseStorageContract _warehouseStorageContract;
private Component _component;
[SetUp]
public void SetUp()
{
_warehouseStorageContract = new WarehouseStorageContract(FurnitureAssemblyDbContext);
_component = InsertComponentToDatabaseAndReturn(Guid.NewGuid().ToString(), "name", ComponentType.Panel);
}
[TearDown]
public void TearDown()
{
FurnitureAssemblyDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Warehouses\" CASCADE;");
FurnitureAssemblyDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Components\" CASCADE;");
}
[Test]
public void Try_GetList_WhenHaveRecords_Test()
{
var warehouse = InsertWarehouseToDatabaseAndReturn(Guid.NewGuid().ToString(), ComponentType.Handle, 5);
InsertWarehouseToDatabaseAndReturn(Guid.NewGuid().ToString(), ComponentType.Handle, 5);
InsertWarehouseToDatabaseAndReturn(Guid.NewGuid().ToString(), ComponentType.Handle, 5);
var list = _warehouseStorageContract.GetList();
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(3));
AssertElement(list.First(), warehouse);
}
[Test]
public void Try_GetList_WhenNoRecords_Test()
{
var list = _warehouseStorageContract.GetList();
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.Empty);
}
[Test]
public void Try_GetElementById_WhenHaveRecord_Test()
{
var warehouse = InsertWarehouseToDatabaseAndReturn(Guid.NewGuid().ToString(), ComponentType.Handle, 5);
var result = _warehouseStorageContract.GetElementById(warehouse.Id);
AssertElement(result, warehouse);
}
[Test]
public void Try_GetElementById_WhenNoRecord_Test()
{
Assert.That(() => _warehouseStorageContract.GetElementById(Guid.NewGuid().ToString()), Is.Null);
}
[Test]
public void Try_AddElement_WhenValidData_Test()
{
var warehouse = CreateModel(Guid.NewGuid().ToString(), ComponentType.Handle, 5, [_component.Id]);
_warehouseStorageContract.AddElement(warehouse);
var result = GetWarehouseFromDatabaseById(warehouse.Id);
AssertElement(result, warehouse);
}
[Test]
public void Try_AddElement_WhenHaveRecordWithSameId_Test()
{
var warehouse = CreateModel(Guid.NewGuid().ToString(), ComponentType.Handle, 5, [_component.Id]);
InsertWarehouseToDatabaseAndReturn(warehouse.Id, ComponentType.Handle, 5, [(_component.Id, 3)]);
Assert.That(() => _warehouseStorageContract.AddElement(warehouse), Throws.TypeOf<StorageException>());
}
[Test]
public void Try_AddElement_WhenNoHaveComponent_Test()
{
var warehouse = CreateModel(Guid.NewGuid().ToString(), ComponentType.Handle, 0, [_component.Id]);
InsertWarehouseToDatabaseAndReturn(warehouse.Id, ComponentType.Handle, 5, [(_component.Id, 3)]);
Assert.That(() => _warehouseStorageContract.AddElement(warehouse), Throws.TypeOf<StorageException>());
}
[Test]
public void Try_UpdElement_WhenValidData_Test()
{
var warehouse = CreateModel(Guid.NewGuid().ToString(), ComponentType.Handle, 5, [_component.Id]);
InsertWarehouseToDatabaseAndReturn(warehouse.Id, ComponentType.Legs, 10, null);
_warehouseStorageContract.UpdElement(warehouse);
var result = GetWarehouseFromDatabaseById(warehouse.Id);
AssertElement(result, warehouse);
}
[Test]
public void Try_UpdElement_WhenNoRecordWithThisId_Test()
{
var warehouse = CreateModel(Guid.NewGuid().ToString(), ComponentType.Handle, 5, [_component.Id]);
Assert.That(() => _warehouseStorageContract.UpdElement(warehouse), Throws.TypeOf<ElementNotFoundException>());
}
[Test]
public void Try_DelElement_WhenRecordExists_Test()
{
var warehouse = InsertWarehouseToDatabaseAndReturn(Guid.NewGuid().ToString(), ComponentType.Handle, 5);
_warehouseStorageContract.DelElement(warehouse.Id);
var result = GetWarehouseFromDatabaseById(warehouse.Id);
Assert.That(result, Is.Null);
}
[Test]
public void Try_DelElement_WhenRecordDoesNotExist_ThrowsElementNotFoundException()
{
Assert.That(() => _warehouseStorageContract.DelElement(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
}
private Component InsertComponentToDatabaseAndReturn(string id, string name, ComponentType type)
{
var component = new Component { Id = id, Name = name, Type = type };
FurnitureAssemblyDbContext.Components.Add(component);
FurnitureAssemblyDbContext.SaveChanges();
return component;
}
private Warehouse InsertWarehouseToDatabaseAndReturn(string id, ComponentType type, int count, List<(string, int)>? components = null)
{
var warehouse = new Warehouse { Id = id, Type = type, Count = count, Components = [] };
if (components is not null)
{
foreach (var elem in components)
{
warehouse.Components.Add(new ComponentWarehouse { WarehouseId = warehouse.Id, ComponentId = elem.Item1, Count = elem.Item2 });
}
}
FurnitureAssemblyDbContext.Warehouses.Add(warehouse);
FurnitureAssemblyDbContext.SaveChanges();
return warehouse;
}
private static void AssertElement(WarehouseDataModel? actual, Warehouse expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.Id, Is.EqualTo(expected.Id));
Assert.That(actual.Type, Is.EqualTo(expected.Type));
Assert.That(actual.Count, Is.EqualTo(expected.Count));
});
if (expected.Components is not null)
{
Assert.That(actual.Components, Is.Not.Null);
Assert.That(actual.Components, Has.Count.EqualTo(expected.Components.Count));
for (int i = 0; i < actual.Components.Count; ++i)
{
Assert.Multiple(() =>
{
Assert.That(actual.Components[i].ComponentId, Is.EqualTo(expected.Components[i].ComponentId));
Assert.That(actual.Components[i].Count, Is.EqualTo(expected.Components[i].Count));
});
}
}
else
{
Assert.That(actual.Components, Is.Null);
}
}
private static void AssertElement(Warehouse? actual, WarehouseDataModel expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.Id, Is.EqualTo(expected.Id));
Assert.That(actual.Type, Is.EqualTo(expected.Type));
Assert.That(actual.Count, Is.EqualTo(expected.Count));
});
if (expected.Components is not null)
{
Assert.That(actual.Components, Is.Not.Null);
Assert.That(actual.Components, Has.Count.EqualTo(expected.Components.Count));
for (int i = 0; i < actual.Components.Count; ++i)
{
Assert.Multiple(() =>
{
Assert.That(actual.Components[i].ComponentId, Is.EqualTo(expected.Components[i].ComponentId));
Assert.That(actual.Components[i].Count, Is.EqualTo(expected.Components[i].Count));
});
}
}
else
{
Assert.That(actual.Components, Is.Null);
}
}
private static WarehouseDataModel CreateModel(string id, ComponentType type, int count, List<string> componentsIds)
{
var components = componentsIds.Select(x => new ComponentWarehouseDataModel(id, x, 1)).ToList();
return new(id, type, count, components);
}
private Warehouse? GetWarehouseFromDatabaseById(string id)
{
return FurnitureAssemblyDbContext.Warehouses.FirstOrDefault(x => x.Id == id);
}
}

View File

@@ -0,0 +1,247 @@
using FurnitureAssemblyContracts.DataModels;
using FurnitureAssemblyContracts.Exceptions;
using FurnitureAssemblyDatebase.Implementations;
using FurnitureAssemblyDatebase.Models;
using Microsoft.EntityFrameworkCore;
namespace FurnitureAssemblyTests.StorageContractTests;
[TestFixture]
internal class WorkerStorageContractTests : BaseStorageContractTest
{
private WorkerStorageContract _workerStorageContract;
[SetUp]
public void SetUp()
{
_workerStorageContract = new WorkerStorageContract(FurnitureAssemblyDbContext);
}
[TearDown]
public void TearDown()
{
FurnitureAssemblyDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Workers\"CASCADE; ");
}
[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 list = _workerStorageContract.GetList();
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(3));
AssertElement(list.First(), worker);
}
[Test]
public void Try_GetList_WhenNoRecords_Test()
{
var list = _workerStorageContract.GetList();
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.Empty);
}
[Test]
public void Try_GetList_ByPostId_Test()
{
var postId = Guid.NewGuid().ToString();
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 1",
postId);
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 2",
postId);
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 3");
var list = _workerStorageContract.GetList(postId: postId);
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(2));
Assert.That(list.All(x => x.PostId == postId));
}
[Test]
public void Try_GetList_ByBirthDate_Test()
{
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));
var list = _workerStorageContract.GetList(fromBirthDate: DateTime.UtcNow.AddYears(-21).AddMinutes(-1), toBirthDate: DateTime.UtcNow.AddYears(-20).AddMinutes(1));
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(2));
}
[Test]
public void Try_GetList_ByEmploymentDate_Test()
{
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));
var list = _workerStorageContract.GetList(fromEmploymentDate: DateTime.UtcNow.AddDays(-1).AddMinutes(-1), toEmploymentDate: DateTime.UtcNow.AddDays(1).AddMinutes(1));
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(2));
}
[Test]
public void Try_GetList_ByAllParameters_Test()
{
var postId = Guid.NewGuid().ToString();
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));
var list = _workerStorageContract.GetList(postId: postId, fromBirthDate: DateTime.UtcNow.AddYears(-21).AddMinutes(-1),
toBirthDate: DateTime.UtcNow.AddYears(-20).AddMinutes(1), fromEmploymentDate: DateTime.UtcNow.AddDays(-1).AddMinutes(-1),
toEmploymentDate: DateTime.UtcNow.AddDays(1).AddMinutes(1));
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(1));
}
[Test]
public void Try_GetElementById_WhenHaveRecord_Test()
{
var worker = InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString());
AssertElement(_workerStorageContract.GetElementById(worker.Id), worker);
}
[Test]
public void Try_GetElementById_WhenNoRecord_Test()
{
Assert.That(() => _workerStorageContract.GetElementById(Guid.NewGuid().ToString()), Is.Null);
}
[Test]
public void Try_GetElementByFIO_WhenHaveRecord_Test()
{
var worker = InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString());
AssertElement(_workerStorageContract.GetElementByFIO(worker.FIO), worker);
}
[Test]
public void Try_GetElementByFIO_WhenNoRecord_Test()
{
Assert.That(() => _workerStorageContract.GetElementByFIO("New Fio"), Is.Null);
}
[Test]
public void Try_AddElement_Test()
{
var worker = CreateModel(Guid.NewGuid().ToString());
_workerStorageContract.AddElement(worker);
AssertElement(GetWorkerFromDatabase(worker.Id), worker);
}
[Test]
public void Try_AddElement_WhenHaveRecordWithSameId_Test()
{
var worker = CreateModel(Guid.NewGuid().ToString());
InsertWorkerToDatabaseAndReturn(worker.Id);
Assert.That(() => _workerStorageContract.AddElement(worker), Throws.TypeOf<ElementExistsException>());
}
[Test]
public void Try_UpdElement_Test()
{
var worker = CreateModel(Guid.NewGuid().ToString(), "New Fio");
InsertWorkerToDatabaseAndReturn(worker.Id);
_workerStorageContract.UpdElement(worker);
AssertElement(GetWorkerFromDatabase(worker.Id), worker);
}
[Test]
public void Try_UpdElement_WhenNoRecordWithThisId_Test()
{
Assert.That(() => _workerStorageContract.UpdElement(CreateModel(Guid.NewGuid().ToString())),
Throws.TypeOf<ElementNotFoundException>());
}
[Test]
public void Try_UpdElement_WhenNoRecordWasDeleted_Test()
{
var worker = CreateModel(Guid.NewGuid().ToString());
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());
_workerStorageContract.DelElement(worker.Id);
var element = GetWorkerFromDatabase(worker.Id);
Assert.That(element, Is.Not.Null);
Assert.That(element.IsDeleted);
}
[Test]
public void Try_DelElement_WhenNoRecordWithThisId_Test()
{
Assert.That(() => _workerStorageContract.DelElement(Guid.NewGuid().ToString()),
Throws.TypeOf<ElementNotFoundException>());
}
[Test]
public void Try_DelElement_WhenNoRecordWasDeleted_Test()
{
var worker = CreateModel(Guid.NewGuid().ToString());
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
};
FurnitureAssemblyDbContext.Workers.Add(worker);
FurnitureAssemblyDbContext.SaveChanges();
return worker;
}
private static void AssertElement(WorkerDataModel? actual, Worker expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.Id, Is.EqualTo(expected.Id));
Assert.That(actual.PostId, Is.EqualTo(expected.PostId));
Assert.That(actual.FIO, Is.EqualTo(expected.FIO));
Assert.That(actual.BirthDate, Is.EqualTo(expected.BirthDate));
Assert.That(actual.EmploymentDate,
Is.EqualTo(expected.EmploymentDate));
Assert.That(actual.IsDeleted, Is.EqualTo(expected.IsDeleted));
});
}
private static WorkerDataModel CreateModel(string id, string fio = "fio", string? postId = null, DateTime? birthDate = null, DateTime? employmentDate = null, bool isDeleted = false) =>
new(id, fio, postId ?? Guid.NewGuid().ToString(), birthDate ?? DateTime.UtcNow.AddYears(-20), employmentDate ?? DateTime.UtcNow, isDeleted);
private Worker? GetWorkerFromDatabase(string id) => FurnitureAssemblyDbContext.Workers.FirstOrDefault(x => x.Id == id);
private static void AssertElement(Worker? actual, WorkerDataModel expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.Id, Is.EqualTo(expected.Id));
Assert.That(actual.PostId, Is.EqualTo(expected.PostId));
Assert.That(actual.FIO, Is.EqualTo(expected.FIO));
Assert.That(actual.BirthDate, Is.EqualTo(expected.BirthDate));
Assert.That(actual.EmploymentDate,Is.EqualTo(expected.EmploymentDate));
Assert.That(actual.IsDeleted, Is.EqualTo(expected.IsDeleted));
});
}
}