80% Готово

This commit is contained in:
2025-03-27 06:55:34 +04:00
parent d3bf4eec43
commit e1e8d23bd0
25 changed files with 2080 additions and 229 deletions

View File

@@ -0,0 +1,22 @@
using SmallSoftwareContracts.AdapterContracts.OperationResponses;
using SmallSoftwareContracts.BindingModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SmallSoftwareContracts.AdapterContracts;
public interface IRequestAdapter
{
RequestOperationResponse GetList(DateTime fromDate, DateTime toDate);
RequestOperationResponse GetWorkerList(string id, DateTime fromDate, DateTime
toDate);
RequestOperationResponse GetSoftwareList(string id, DateTime fromDate, DateTime
toDate);
RequestOperationResponse GetElement(string id);
RequestOperationResponse MakeRequest(RequestBindingModel saleModel);
RequestOperationResponse CancelRequest(string id);
}

View File

@@ -0,0 +1,18 @@
using SmallSoftwareContracts.AdapterContracts.OperationResponses;
using SmallSoftwareContracts.BindingModels;
namespace SmallSoftwareContracts.AdapterContracts;
public interface ISoftwareAdapter
{
SoftwareOperationResponse GetList(bool includeDeleted);
SoftwareOperationResponse GetManufacturerList(string id, bool
includeDeleted);
SoftwareOperationResponse GetHistory(string id);
SoftwareOperationResponse GetElement(string data);
SoftwareOperationResponse RegisterSoftware(SoftwareBindingModel productModel);
SoftwareOperationResponse ChangeSoftwareInfo(SoftwareBindingModel
productModel);
SoftwareOperationResponse RemoveSoftware(string id);
}

View File

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

View File

@@ -0,0 +1,22 @@
using SmallSoftwareContracts.Infrastructure;
using SmallSoftwareContracts.ViewModels;
namespace SmallSoftwareContracts.AdapterContracts.OperationResponses;
public class SoftwareOperationResponse : OperationResponse
{
public static SoftwareOperationResponse OK(List<SoftwareViewModel> data) =>
OK<SoftwareOperationResponse, List<SoftwareViewModel>>(data);
public static SoftwareOperationResponse OK(List<SoftwareHistoryViewModel>
data) => OK<SoftwareOperationResponse, List<SoftwareHistoryViewModel>>(data);
public static SoftwareOperationResponse OK(SoftwareViewModel data) =>
OK<SoftwareOperationResponse, SoftwareViewModel>(data);
public static SoftwareOperationResponse NoContent() =>
NoContent<SoftwareOperationResponse>();
public static SoftwareOperationResponse NotFound(string message) =>
NotFound<SoftwareOperationResponse>(message);
public static SoftwareOperationResponse BadRequest(string message) =>
BadRequest<SoftwareOperationResponse>(message);
public static SoftwareOperationResponse InternalServerError(string message)
=> InternalServerError<SoftwareOperationResponse>(message);
}

View File

@@ -0,0 +1,12 @@
namespace SmallSoftwareContracts.BindingModels;
public class InstallationRequestBindingModel
{
public string? SoftwareId { get; set; }
public string? RequestId { get; set; }
public int Count { get; set; }
public double Price { get; set; }
}

View File

@@ -0,0 +1,11 @@
using SmallSoftwareContracts.DataModels;
namespace SmallSoftwareContracts.BindingModels;
public class RequestBindingModel
{
public string? Id { get; set; }
public string? WorkerId { get; set; }
public string? Email { get; set; }
public List<InstallationRequestBindingModel>? Softwares { get; set; }
}

View File

@@ -0,0 +1,12 @@
using SmallSoftwareContracts.Enums;
namespace SmallSoftwareContracts.BindingModels;
public class SoftwareBindingModel
{
public string? Id { get; set; }
public string? SoftwareName { get; set; }
public string? SoftwareType { get; set; }
public string? ManufacturerId { get; set; }
public double Price { get; set; }
}

View File

@@ -6,10 +6,20 @@ namespace SmallSoftwareContracts.DataModels;
public class InstallationRequestDataModel(string softwareId, string requestId, int count, double price) : IValidation
{
private readonly SoftwareDataModel? _software;
public string SoftwareId { get; private set; } = softwareId;
public string RequestId { get; private set; } = requestId;
public int Count { get; private set; } = count;
public double Price { get; private set; } = price;
public string SoftwareName => _software?.SoftwareName ?? string.Empty;
public InstallationRequestDataModel(string saleId, string softwareId, int count, double price, SoftwareDataModel software) : this(saleId, softwareId, count, price)
{
_software = software;
}
public void Validate()
{
if (SoftwareId.IsEmpty())

View File

@@ -9,12 +9,23 @@ namespace SmallSoftwareContracts.DataModels;
public class RequestDataModel(string id, string workerId, string email, double sum, bool isCancel, List<InstallationRequestDataModel> installationRequests) : IValidation
{
private readonly WorkerDataModel? _worker;
public string Id { get; private set; } = id;
public string WorkerId { get; private set; } = workerId;
public string Email { get; private set; } = email;
public double Sum { get; private set; } = sum;
public bool IsCancel { get; private set; } = isCancel;
public List<InstallationRequestDataModel> Softwares { get; private set; } = installationRequests;
public string WorkerFIO => _worker?.FIO ?? string.Empty;
public RequestDataModel(string id, string workerId, string email, double sum, bool isCancel, List<InstallationRequestDataModel> installationRequests, WorkerDataModel worker)
: this(id, workerId,email,sum,isCancel, installationRequests)
{
Sum = sum;
_worker = worker;
}
public void Validate()
{
if (Id.IsEmpty())

View File

@@ -13,12 +13,28 @@ namespace SmallSoftwareContracts.DataModels;
public class SoftwareDataModel(string id, string softwareName, SoftwareType softwareType, string manufacturerId, double price, bool isDeleted) : IValidation
{
private readonly ManufacturerDataModel? _manufacturer;
public string Id { get; private set; } = id;
public string SoftwareName { get; private set; } = softwareName;
public SoftwareType SoftwareType { get; private set; } = softwareType;
public string ManufacturerId { get; private set; } = manufacturerId;
public double Price { get; private set; } = price;
public bool IsDeleted { get; private set; } = isDeleted;
public string ManufacturerName => _manufacturer?.ManufacturerName ?? string.Empty;
public SoftwareDataModel(string id, string softwareName, SoftwareType
softwareType, string manufacturerId, double price, bool isDeleted,
ManufacturerDataModel manufacturer) : this(id, softwareName, softwareType,
manufacturerId, price, isDeleted)
{
_manufacturer = manufacturer;
}
public SoftwareDataModel(string id, string softwareName, SoftwareType
softwareType, string manufacturerId, double price) : this(id, softwareName,
softwareType, manufacturerId, price, false)
{ }
public void Validate()
{
if (Id.IsEmpty())

View File

@@ -11,9 +11,19 @@ namespace SmallSoftwareContracts.DataModels;
public class SoftwareHistoryDataModel(string softwareId, double oldPrice) : IValidation
{
private readonly SoftwareDataModel? _software;
public string SoftwareId { get; private set; } = softwareId;
public double OldPrice { get; private set; } = oldPrice;
public DateTime ChangeDate { get; private set; } = DateTime.UtcNow;
public string SoftwareName => _software?.SoftwareName ?? string.Empty;
public SoftwareHistoryDataModel(string softwareId, double oldPrice, DateTime
changeDate, SoftwareDataModel software) : this(softwareId, oldPrice)
{
ChangeDate = changeDate;
_software = software;
}
public void Validate()
{
if (SoftwareId.IsEmpty())

View File

@@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SmallSoftwareContracts.ViewModels;
public class InstallationRequestViewModel
{
public required string SoftwareId { get; set; }
public required string SoftwareName { get; set; }
public int Count { get; set; }
public double Price { get; set; }
}

View File

@@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SmallSoftwareContracts.ViewModels;
public class RequestViewModel
{
public required string Id { get; set; }
public required string WorkerId { get; set; }
public required string WorkerFIO { get; set; }
public double Sum { get; set; }
public bool IsCancel { get; set; }
public required List<InstallationRequestViewModel> Softwares { get; set; }
}

View File

@@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SmallSoftwareContracts.ViewModels;
public class SoftwareHistoryViewModel
{
public required string SoftwareName { get; set; }
public double OldPrice { get; set; }
public DateTime ChangeDate { get; set; }
}

View File

@@ -0,0 +1,13 @@
namespace SmallSoftwareContracts.ViewModels;
public class SoftwareViewModel
{
public required string Id { get; set; }
public required string SoftwareName { get; set; }
public required string ManufacturerId { get; set; }
public required string ManufacturerName { get; set; }
public required string SoftwareType { get; set; }
public double Price { get; set; }
public bool IsDeleted { get; set; }
}

View File

@@ -17,12 +17,21 @@ internal class RequestStorageContract : IRequestStorageContract
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Manufacturer, ManufacturerDataModel>();
cfg.CreateMap<Software, SoftwareDataModel>();
cfg.CreateMap<Worker, WorkerDataModel>();
cfg.CreateMap<InstallationRequest, InstallationRequestDataModel>();
cfg.CreateMap<InstallationRequestDataModel, InstallationRequest>();
cfg.CreateMap<InstallationRequestDataModel, InstallationRequest>()
.ForMember(x => x.SoftwareId, x => x.MapFrom(src => src.SoftwareId))
.ForMember(x => x.Software, x => x.Ignore());
cfg.CreateMap<Request, RequestDataModel>();
cfg.CreateMap<RequestDataModel, Request>()
.ForMember(x => x.IsCancel, x => x.MapFrom(src => false))
.ForMember(x => x.InstallationRequests, x => x.MapFrom(src => src.Softwares));
.ForMember(x => x.InstallationRequests, x => x.MapFrom(src => src.Softwares))
.ForMember(x => x.Worker, x => x.Ignore())
;
});
_mapper = new Mapper(config);
}

View File

@@ -17,6 +17,7 @@ internal class SoftwareStorageContract : ISoftwareStorageContract
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Manufacturer, ManufacturerDataModel>();
cfg.CreateMap<Software, SoftwareDataModel>();
cfg.CreateMap<SoftwareDataModel, Software>()
.ForMember(x => x.IsDeleted, x => x.MapFrom(src => false));
@@ -29,7 +30,7 @@ internal class SoftwareStorageContract : ISoftwareStorageContract
{
try
{
var query = _dbContext.Softwares.AsQueryable();
var query = _dbContext.Softwares.Include(x => x.Manufacturer).AsQueryable();
if (onlyActive)
{
query = query.Where(x => !x.IsDeleted);
@@ -52,7 +53,7 @@ internal class SoftwareStorageContract : ISoftwareStorageContract
{
try
{
return [.. _dbContext.SoftwareHistories.Where(x => x.SoftwareId == softwareId)
return [.. _dbContext.SoftwareHistories.Include(x => x.Software).Where(x => x.SoftwareId == softwareId)
.OrderByDescending(x => x.ChangeDate)
.Select(x => _mapper.Map<SoftwareHistoryDataModel>(x))];
}
@@ -79,7 +80,7 @@ internal class SoftwareStorageContract : ISoftwareStorageContract
try
{
return
_mapper.Map<SoftwareDataModel>(_dbContext.Softwares.FirstOrDefault(x =>
_mapper.Map<SoftwareDataModel>(_dbContext.Softwares.Include(x => x.Manufacturer).FirstOrDefault(x =>
x.SoftwareName == name && !x.IsDeleted));
}
catch (Exception ex)
@@ -181,6 +182,6 @@ internal class SoftwareStorageContract : ISoftwareStorageContract
}
}
private Software? GetSoftwareById(string id) =>
_dbContext.Softwares.FirstOrDefault(x => x.Id == id && !x.IsDeleted);
_dbContext.Softwares.Include(x => x.Manufacturer).FirstOrDefault(x => x.Id == id && !x.IsDeleted);
}

View File

@@ -5,6 +5,7 @@ using SmallSoftwareContracts.Exceptions;
using SmallSoftwareDatabase.Implementations;
using SmallSoftwareDatabase.Models;
using SmallSoftwareTests.Infrastructure;
using static NUnit.Framework.Internal.OSPlatform;
namespace SmallSoftwareTests.StoragesContracts;
[TestFixture]
@@ -12,33 +13,33 @@ internal class SoftwareStorageContractTests : BaseStorageContractTest
{
private SoftwareStorageContract _softwareStorageContract;
private Manufacturer _manufacturer;
[SetUp]
public void SetUp()
public void SetUp()
{
_softwareStorageContract = new SoftwareStorageContract(SmallSoftwareDbContext);
_manufacturer = InsertManufacturerToDatabaseAndReturn();
_softwareStorageContract = new SoftwareStorageContract(SmallSoftwareDbContext);
_manufacturer = SmallSoftwareDbContext.InsertManufacturerToDatabaseAndReturn();
}
[TearDown]
public void TearDown()
{
SmallSoftwareDbContext.RemoveSoftwaresFromDatabase();
SmallSoftwareDbContext.RemoveManufacturersFromDatabase();
}
[Test]
public void Try_GetList_WhenHaveRecords_Test()
{
var software =
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(_manufacturer.Id,Guid.NewGuid().ToString(),
"name 1");
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(_manufacturer.Id,Guid.NewGuid().ToString(),
"name 2");
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(_manufacturer.Id,Guid.NewGuid().ToString(),
"name 3");
var software = SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(_manufacturer.Id, softwareName: "name 1");
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(_manufacturer.Id, softwareName: "name 2");
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(_manufacturer.Id, softwareName: "name 3");
var list = _softwareStorageContract.GetList();
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(3));
AssertElement(list.First(x => x.Id == software.Id), software);
}
[Test]
public void Try_GetList_WhenNoRecords_Test()
{
@@ -46,15 +47,13 @@ public void SetUp()
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.Empty);
}
[Test]
public void Try_GetList_OnlyActual_Test()
{
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(Guid.NewGuid().ToString(),
_manufacturer.Id, "name 1", isDeleted: true);
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(Guid.NewGuid().ToString(),
_manufacturer.Id, "name 2", isDeleted: false);
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(Guid.NewGuid().ToString(),
_manufacturer.Id, "name 3", isDeleted: false);
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(_manufacturer.Id, softwareName: "name 1", isDeleted: true);
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(_manufacturer.Id, softwareName: "name 2", isDeleted: false);
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(_manufacturer.Id, softwareName: "name 3", isDeleted: false);
var list = _softwareStorageContract.GetList(onlyActive: true);
Assert.That(list, Is.Not.Null);
Assert.Multiple(() =>
@@ -63,15 +62,13 @@ public void SetUp()
Assert.That(!list.Any(x => x.IsDeleted));
});
}
[Test]
public void Try_GetList_IncludeNoActual_Test()
{
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(Guid.NewGuid().ToString(),
_manufacturer.Id, "name 1", isDeleted: true);
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(Guid.NewGuid().ToString(),
_manufacturer.Id, "name 2", isDeleted: true);
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(Guid.NewGuid().ToString(),
_manufacturer.Id, "name 3", isDeleted: false);
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(_manufacturer.Id, softwareName: "name 1", isDeleted: true);
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(_manufacturer.Id, softwareName: "name 2", isDeleted: true);
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(_manufacturer.Id, softwareName: "name 3", isDeleted: false);
var list = _softwareStorageContract.GetList(onlyActive: false);
Assert.That(list, Is.Not.Null);
Assert.Multiple(() =>
@@ -81,339 +78,250 @@ public void SetUp()
Assert.That(list.Count(x => !x.IsDeleted), Is.EqualTo(1));
});
}
[Test]
public void Try_GetList_ByManufacturer_Test()
{
var manufacruer = InsertManufacturerToDatabaseAndReturn("name 2");
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(Guid.NewGuid().ToString(),
_manufacturer.Id, "name 1", isDeleted: true);
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(Guid.NewGuid().ToString(),
_manufacturer.Id, "name 2", isDeleted: false);
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(Guid.NewGuid().ToString(),
manufacruer.Id, "name 3", isDeleted: false);
var list = _softwareStorageContract.GetList(manufacturerId:
_manufacturer.Id, onlyActive: false);
var manufacruer = SmallSoftwareDbContext.InsertManufacturerToDatabaseAndReturn(manufacturerName: "name 2");
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(_manufacturer.Id, softwareName: "name 1", isDeleted: true);
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(_manufacturer.Id, softwareName: "name 2", isDeleted: false);
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(manufacruer.Id, softwareName: "name 3", isDeleted: false);
var list = _softwareStorageContract.GetList(manufacturerId: _manufacturer.Id, onlyActive: false);
Assert.That(list, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(list, Has.Count.EqualTo(2));
Assert.That(list.All(x => x.ManufacturerId ==
_manufacturer.Id));
Assert.That(list.All(x => x.ManufacturerId == _manufacturer.Id));
});
}
[Test]
public void Try_GetList_ByManufacturerOnlyActual_Test()
{
var manufacruer = InsertManufacturerToDatabaseAndReturn("name 2");
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(Guid.NewGuid().ToString(),
_manufacturer.Id, "name 1", isDeleted: true);
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(Guid.NewGuid().ToString(),
_manufacturer.Id, "name 2", isDeleted: false);
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(Guid.NewGuid().ToString(),
manufacruer.Id, "name 3", isDeleted: false);
var list = _softwareStorageContract.GetList(manufacturerId:
_manufacturer.Id, onlyActive: true);
var manufacruer = SmallSoftwareDbContext.InsertManufacturerToDatabaseAndReturn(manufacturerName: "name 2");
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(_manufacturer.Id, softwareName: "name 1", isDeleted: true);
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(_manufacturer.Id, softwareName: "name 2", isDeleted: false);
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(manufacruer.Id, softwareName: "name 3", isDeleted: false);
var list = _softwareStorageContract.GetList(manufacturerId: _manufacturer.Id, onlyActive: true);
Assert.That(list, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(list, Has.Count.EqualTo(1));
Assert.That(list.All(x => x.ManufacturerId == _manufacturer.Id
&& !x.IsDeleted));
Assert.That(list.All(x => x.ManufacturerId == _manufacturer.Id && !x.IsDeleted));
});
}
[Test]
public void Try_GetHistoryBySoftwareId_WhenHaveRecords_Test()
{
var software =
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(Guid.NewGuid().ToString(), _manufacturer.Id,
"name 1");
InsertSoftwareHistoryToDatabaseAndReturn(software.Id, 20,
DateTime.UtcNow.AddDays(-1));
InsertSoftwareHistoryToDatabaseAndReturn(software.Id, 30,
DateTime.UtcNow.AddMinutes(-10));
InsertSoftwareHistoryToDatabaseAndReturn(software.Id, 40,
DateTime.UtcNow.AddDays(1));
var software = SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(_manufacturer.Id);
SmallSoftwareDbContext.InsertSoftwareHistoryToDatabaseAndReturn(software.Id, 20, DateTime.UtcNow.AddDays(-1));
SmallSoftwareDbContext.InsertSoftwareHistoryToDatabaseAndReturn(software.Id, 30, DateTime.UtcNow.AddMinutes(-10));
SmallSoftwareDbContext.InsertSoftwareHistoryToDatabaseAndReturn(software.Id, 40, DateTime.UtcNow.AddDays(1));
var list = _softwareStorageContract.GetHistoryBySoftwareId(software.Id);
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(3));
}
[Test]
public void Try_GetHistoryBySoftwareId_WhenNoRecords_Test()
{
var software =
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(Guid.NewGuid().ToString(), _manufacturer.Id,
"name 1");
InsertSoftwareHistoryToDatabaseAndReturn(software.Id, 20,
DateTime.UtcNow.AddDays(-1));
InsertSoftwareHistoryToDatabaseAndReturn(software.Id, 30,
DateTime.UtcNow.AddMinutes(-10));
InsertSoftwareHistoryToDatabaseAndReturn(software.Id, 40,
DateTime.UtcNow.AddDays(1));
var list =
_softwareStorageContract.GetHistoryBySoftwareId(Guid.NewGuid().ToString());
var software = SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(_manufacturer.Id);
SmallSoftwareDbContext.InsertSoftwareHistoryToDatabaseAndReturn(software.Id, 20, DateTime.UtcNow.AddDays(-1));
SmallSoftwareDbContext.InsertSoftwareHistoryToDatabaseAndReturn(software.Id, 30, DateTime.UtcNow.AddMinutes(-10));
SmallSoftwareDbContext.InsertSoftwareHistoryToDatabaseAndReturn(software.Id, 40, DateTime.UtcNow.AddDays(1));
var list = _softwareStorageContract.GetHistoryBySoftwareId(Guid.NewGuid().ToString());
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
}
[Test]
public void Try_GetElementById_WhenHaveRecord_Test()
{
var software =
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(Guid.NewGuid().ToString(), _manufacturer.Id);
AssertElement(_softwareStorageContract.GetElementById(software.Id),
software);
var software = SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(_manufacturer.Id);
AssertElement(_softwareStorageContract.GetElementById(software.Id), software);
}
[Test]
public void Try_GetElementById_WhenNoRecord_Test()
{
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(Guid.NewGuid().ToString(),
_manufacturer.Id);
Assert.That(() =>
_softwareStorageContract.GetElementById(Guid.NewGuid().ToString()), Is.Null);
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(_manufacturer.Id);
Assert.That(() => _softwareStorageContract.GetElementById(Guid.NewGuid().ToString()), Is.Null);
}
[Test]
public void Try_GetElementById_WhenRecordHasDeleted_Test()
public void Try_GetElementById_WhenRecordWasDeleted_Test()
{
var software =
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(Guid.NewGuid().ToString(), _manufacturer.Id,
isDeleted: true);
Assert.That(() => _softwareStorageContract.GetElementById(software.Id),
Is.Null);
var software = SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(_manufacturer.Id, isDeleted: true);
Assert.That(() => _softwareStorageContract.GetElementById(software.Id), Is.Null);
}
[Test]
public void Try_GetElementByName_WhenHaveRecord_Test()
{
var software =
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(Guid.NewGuid().ToString(), _manufacturer.Id);
AssertElement(_softwareStorageContract.GetElementByName(software.SoftwareName)
, software);
var software = SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(_manufacturer.Id);
AssertElement(_softwareStorageContract.GetElementByName(software.SoftwareName), software);
}
[Test]
public void Try_GetElementByName_WhenNoRecord_Test()
{
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(Guid.NewGuid().ToString(),
_manufacturer.Id);
Assert.That(() => _softwareStorageContract.GetElementByName("name"),
Is.Null);
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(_manufacturer.Id);
Assert.That(() => _softwareStorageContract.GetElementByName("name"), Is.Null);
}
[Test]
public void Try_GetElementByName_WhenRecordHasDeleted_Test()
public void Try_GetElementByName_WhenRecordWasDeleted_Test()
{
var software =
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(Guid.NewGuid().ToString(), _manufacturer.Id,
isDeleted: true);
Assert.That(() =>
_softwareStorageContract.GetElementById(software.SoftwareName), Is.Null);
var software = SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(_manufacturer.Id, isDeleted: true);
Assert.That(() => _softwareStorageContract.GetElementById(software.SoftwareName), Is.Null);
}
[Test]
public void Try_AddElement_Test()
{
var software = CreateModel(Guid.NewGuid().ToString(),
_manufacturer.Id, isDeleted: false);
var software = CreateModel(Guid.NewGuid().ToString(), _manufacturer.Id, isDeleted: false);
_softwareStorageContract.AddElement(software);
AssertElement(GetSoftwareFromDatabaseById(software.Id), software);
AssertElement(SmallSoftwareDbContext.GetSoftwareFromDatabaseById(software.Id), software);
}
[Test]
public void Try_AddElement_WhenIsDeletedIsTrue_Test()
{
var software = CreateModel(Guid.NewGuid().ToString(),
_manufacturer.Id, isDeleted: true);
Assert.That(() => _softwareStorageContract.AddElement(software),
Throws.Nothing);
AssertElement(GetSoftwareFromDatabaseById(software.Id),
CreateModel(software.Id, _manufacturer.Id, isDeleted: false));
var software = CreateModel(Guid.NewGuid().ToString(), _manufacturer.Id, isDeleted: true);
Assert.That(() => _softwareStorageContract.AddElement(software), Throws.Nothing);
AssertElement(SmallSoftwareDbContext.GetSoftwareFromDatabaseById(software.Id), CreateModel(software.Id, _manufacturer.Id, isDeleted: false));
}
[Test]
public void Try_AddElement_WhenHaveRecordWithSameId_Test()
{
var software = CreateModel(Guid.NewGuid().ToString(),
_manufacturer.Id);
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(software.Id, _manufacturer.Id,
softwareName: "name unique");
Assert.That(() => _softwareStorageContract.AddElement(software),
Throws.TypeOf<ElementExistsException>());
var software = CreateModel(Guid.NewGuid().ToString(), _manufacturer.Id);
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(_manufacturer.Id, software.Id, softwareName: "name unique");
Assert.That(() => _softwareStorageContract.AddElement(software), Throws.TypeOf<ElementExistsException>());
}
[Test]
public void Try_AddElement_WhenHaveRecordWithSameName_Test()
{
var software = CreateModel(Guid.NewGuid().ToString(),
_manufacturer.Id, "name unique", isDeleted: false);
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(Guid.NewGuid().ToString(),
_manufacturer.Id, softwareName: software.SoftwareName, isDeleted: false);
Assert.That(() => _softwareStorageContract.AddElement(software),
Throws.TypeOf<ElementExistsException>());
var software = CreateModel(Guid.NewGuid().ToString(), _manufacturer.Id, "name unique", isDeleted: false);
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(_manufacturer.Id, softwareName: software.SoftwareName, isDeleted: false);
Assert.That(() => _softwareStorageContract.AddElement(software), Throws.TypeOf<ElementExistsException>());
}
[Test]
[Test]
public void Try_AddElement_WhenHaveRecordWithSameNameButOneWasDeleted_Test()
{
var software = CreateModel(Guid.NewGuid().ToString(),
_manufacturer.Id, "name unique", isDeleted: false);
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(Guid.NewGuid().ToString(),
_manufacturer.Id, softwareName: software.SoftwareName, isDeleted: true);
Assert.That(() => _softwareStorageContract.AddElement(software),
Throws.Nothing);
var software = CreateModel(Guid.NewGuid().ToString(), _manufacturer.Id, "name unique", isDeleted: false);
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(_manufacturer.Id, softwareName: software.SoftwareName, isDeleted: true);
Assert.That(() => _softwareStorageContract.AddElement(software), Throws.Nothing);
}
[Test]
public void Try_UpdElement_Test()
{
var software = CreateModel(Guid.NewGuid().ToString(),
_manufacturer.Id, isDeleted: false);
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(software.Id, _manufacturer.Id,
isDeleted: false);
var software = CreateModel(Guid.NewGuid().ToString(), _manufacturer.Id, isDeleted: false);
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(_manufacturer.Id, id: software.Id, isDeleted: false);
_softwareStorageContract.UpdElement(software);
AssertElement(GetSoftwareFromDatabaseById(software.Id), software);
AssertElement(SmallSoftwareDbContext.GetSoftwareFromDatabaseById(software.Id), software);
}
[Test]
public void Try_UpdElement_WhenIsDeletedIsTrue_Test()
{
var software = CreateModel(Guid.NewGuid().ToString(),
_manufacturer.Id, isDeleted: true);
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(software.Id, _manufacturer.Id,
isDeleted: false);
var software = CreateModel(Guid.NewGuid().ToString(), _manufacturer.Id, isDeleted: true);
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(_manufacturer.Id, software.Id, isDeleted: false);
_softwareStorageContract.UpdElement(software);
AssertElement(GetSoftwareFromDatabaseById(software.Id),
CreateModel(software.Id, _manufacturer.Id, isDeleted: false));
AssertElement(SmallSoftwareDbContext.GetSoftwareFromDatabaseById(software.Id), CreateModel(software.Id, _manufacturer.Id, isDeleted: false));
}
[Test]
public void Try_UpdElement_WhenNoRecordWithThisId_Test()
{
Assert.That(() =>
_softwareStorageContract.UpdElement(CreateModel(Guid.NewGuid().ToString(),
_manufacturer.Id)), Throws.TypeOf<ElementNotFoundException>());
Assert.That(() => _softwareStorageContract.UpdElement(CreateModel(Guid.NewGuid().ToString(), _manufacturer.Id)), Throws.TypeOf<ElementNotFoundException>());
}
[Test]
public void Try_UpdElement_WhenHaveRecordWithSameName_Test()
{
var software = CreateModel(Guid.NewGuid().ToString(),
_manufacturer.Id, "name unique", isDeleted: false);
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(software.Id, _manufacturer.Id,
softwareName: "name");
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(Guid.NewGuid().ToString(),
_manufacturer.Id, softwareName: software.SoftwareName);
Assert.That(() => _softwareStorageContract.UpdElement(software),
Throws.TypeOf<ElementExistsException>());
var software = CreateModel(Guid.NewGuid().ToString(), _manufacturer.Id, "name unique", isDeleted: false);
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(_manufacturer.Id, software.Id, softwareName: "name");
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(_manufacturer.Id, softwareName: software.SoftwareName);
Assert.That(() => _softwareStorageContract.UpdElement(software), Throws.TypeOf<ElementExistsException>());
}
[Test]
public void
Try_UpdElement_WhenHaveRecordWithSameNameButOneWasDeleted_Test()
public void Try_UpdElement_WhenHaveRecordWithSameNameButOneWasDeleted_Test()
{
var software = CreateModel(Guid.NewGuid().ToString(),
_manufacturer.Id, "name unique", isDeleted: false);
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(software.Id, _manufacturer.Id,
softwareName: "name");
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(Guid.NewGuid().ToString(),
_manufacturer.Id, softwareName: software.SoftwareName, isDeleted: true);
Assert.That(() => _softwareStorageContract.UpdElement(software),
Throws.Nothing);
var software = CreateModel(Guid.NewGuid().ToString(), _manufacturer.Id, "name unique", isDeleted: false);
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(_manufacturer.Id, software.Id, softwareName: "name");
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(_manufacturer.Id, softwareName: software.SoftwareName, isDeleted: true);
Assert.That(() => _softwareStorageContract.UpdElement(software), Throws.Nothing);
}
[Test]
public void Try_UpdElement_WhenRecordWasDeleted_Test()
{
var software = CreateModel(Guid.NewGuid().ToString(),
_manufacturer.Id);
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(software.Id, _manufacturer.Id,
isDeleted: true);
Assert.That(() => _softwareStorageContract.UpdElement(software),
Throws.TypeOf<ElementNotFoundException>());
var software = CreateModel(Guid.NewGuid().ToString(), _manufacturer.Id);
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(_manufacturer.Id, software.Id, isDeleted: true);
Assert.That(() => _softwareStorageContract.UpdElement(software), Throws.TypeOf<ElementNotFoundException>());
}
[Test]
public void Try_DelElement_Test()
{
var software =
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(Guid.NewGuid().ToString(), _manufacturer.Id,
isDeleted: false);
var software = SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(_manufacturer.Id, isDeleted: false);
_softwareStorageContract.DelElement(software.Id);
var element = GetSoftwareFromDatabaseById(software.Id);
var element = SmallSoftwareDbContext.GetSoftwareFromDatabaseById(software.Id);
Assert.Multiple(() =>
{
Assert.That(element, Is.Not.Null);
Assert.That(element!.IsDeleted);
});
}
[Test]
public void Try_DelElement_WhenNoRecordWithThisId_Test()
{
Assert.That(() =>
_softwareStorageContract.DelElement(Guid.NewGuid().ToString()),
Throws.TypeOf<ElementNotFoundException>());
Assert.That(() => _softwareStorageContract.DelElement(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
}
[Test]
public void Try_DelElement_WhenRecordWasDeleted_Test()
{
var software =
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(Guid.NewGuid().ToString(), _manufacturer.Id,
isDeleted: true);
Assert.That(() => _softwareStorageContract.DelElement(software.Id),
Throws.TypeOf<ElementNotFoundException>());
}
private Manufacturer InsertManufacturerToDatabaseAndReturn(string
manufacturerName = "name")
{
var manufacrurer = new Manufacturer()
{
Id =
Guid.NewGuid().ToString(),
ManufacturerName = manufacturerName
};
SmallSoftwareDbContext.Manufacturers.Add(manufacrurer);
SmallSoftwareDbContext.SaveChanges();
return manufacrurer;
var software = SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(_manufacturer.Id, isDeleted: true);
Assert.That(() => _softwareStorageContract.DelElement(software.Id), Throws.TypeOf<ElementNotFoundException>());
}
private SoftwareHistory InsertSoftwareHistoryToDatabaseAndReturn(string
softwareId, double price, DateTime changeDate)
{
var softwareHistory = new SoftwareHistory()
{
Id =
Guid.NewGuid().ToString(),
SoftwareId = softwareId,
OldPrice = price,
ChangeDate =
changeDate
};
SmallSoftwareDbContext.SoftwareHistories.Add(softwareHistory);
SmallSoftwareDbContext.SaveChanges();
return softwareHistory;
}
private static void AssertElement(SoftwareDataModel? actual, Software
expected)
private static void AssertElement(SoftwareDataModel? actual, Software expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.Id, Is.EqualTo(expected.Id));
Assert.That(actual.ManufacturerId,
Is.EqualTo(expected.ManufacturerId));
Assert.That(actual.SoftwareName,
Is.EqualTo(expected.SoftwareName));
Assert.That(actual.SoftwareType,
Is.EqualTo(expected.SoftwareType));
Assert.That(actual.ManufacturerId, Is.EqualTo(expected.ManufacturerId));
Assert.That(actual.SoftwareName, Is.EqualTo(expected.SoftwareName));
Assert.That(actual.SoftwareType, Is.EqualTo(expected.SoftwareType));
Assert.That(actual.Price, Is.EqualTo(expected.Price));
Assert.That(actual.IsDeleted, Is.EqualTo(expected.IsDeleted));
});
}
private static SoftwareDataModel CreateModel(string id, string
manufacturerId, string softwareName = "test", SoftwareType softwareType =
SoftwareType.Windows, double price = 1, bool isDeleted = false)
=> new(id, softwareName, softwareType, manufacturerId, price,
isDeleted);
private Software? GetSoftwareFromDatabaseById(string id) =>
SmallSoftwareDbContext.Softwares.FirstOrDefault(x => x.Id == id);
private static void AssertElement(Software? actual, SoftwareDataModel
expected)
private static SoftwareDataModel CreateModel(string id, string manufacturerId, string softwareName = "test", SoftwareType softwareType = SoftwareType.Windows, double price = 1, bool isDeleted = false)
=> new(id, softwareName, softwareType, manufacturerId, price, isDeleted);
private static void AssertElement(Software? actual, SoftwareDataModel expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.Id, Is.EqualTo(expected.Id));
Assert.That(actual.ManufacturerId,
Is.EqualTo(expected.ManufacturerId));
Assert.That(actual.SoftwareName,
Is.EqualTo(expected.SoftwareName));
Assert.That(actual.SoftwareType,
Is.EqualTo(expected.SoftwareType));
Assert.That(actual.ManufacturerId, Is.EqualTo(expected.ManufacturerId));
Assert.That(actual.SoftwareName, Is.EqualTo(expected.SoftwareName));
Assert.That(actual.SoftwareType, Is.EqualTo(expected.SoftwareType));
Assert.That(actual.Price, Is.EqualTo(expected.Price));
Assert.That(actual.IsDeleted, Is.EqualTo(expected.IsDeleted));
});
}
}

View File

@@ -0,0 +1,392 @@
using SmallSoftwareContracts.BindingModels;
using SmallSoftwareContracts.ViewModels;
using SmallSoftwareDatabase.Models;
using SmallSoftwareTests.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace SmallSoftwareTests.WebApiControllersApi;
[TestFixture]
internal class RequestControllerTests : BaseWebApiControllerTest
{
private string _workerId;
private string _manufacturerId;
private string _softwareId;
[SetUp]
public void SetUp()
{
_workerId = SmallSoftwareDbContext.InsertWorkerToDatabaseAndReturn().Id;
_manufacturerId = SmallSoftwareDbContext.InsertManufacturerToDatabaseAndReturn().Id;
_softwareId = SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(_manufacturerId).Id;
}
[TearDown]
public void TearDown()
{
SmallSoftwareDbContext.RemoveRequestsFromDatabase();
SmallSoftwareDbContext.RemoveWorkersFromDatabase();
SmallSoftwareDbContext.RemoveSoftwaresFromDatabase();
SmallSoftwareDbContext.RemoveManufacturersFromDatabase();
}
[Test]
public async Task GetList_WhenHaveRecords_ShouldSuccess_Test()
{
//Arrange
var request = SmallSoftwareDbContext.InsertRequestToDatabaseAndReturn(_workerId, "test@mail.ru", sum: 10, false, softwares: [(_softwareId, 10, 1.1)]);
//Act
var response = await HttpClient.GetAsync($"/api/requests/getrecords?fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
var data = await GetModelFromResponseAsync<List<RequestViewModel>>(response);
Assert.Multiple(() =>
{
Assert.That(data, Is.Not.Null);
Assert.That(data, Has.Count.EqualTo(3));
});
AssertElement(data.First(x => x.Sum == request.Sum), request);
}
[Test]
public async Task GetList_WhenNoRecords_ShouldSuccess_Test()
{
//Act
var response = await HttpClient.GetAsync($"/api/requests/getrecords?fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
var data = await GetModelFromResponseAsync<List<RequestViewModel>>(response);
Assert.Multiple(() =>
{
Assert.That(data, Is.Not.Null);
Assert.That(data, Has.Count.EqualTo(0));
});
}
[Test]
public async Task GetList_ByWorkerId_ShouldSuccess_Test()
{
//Arrange
var worker = SmallSoftwareDbContext.InsertWorkerToDatabaseAndReturn(fio: "Other worker");
SmallSoftwareDbContext.InsertRequestToDatabaseAndReturn(_workerId, "test@mail.ru", sum: 10, false, softwares: [(_softwareId, 10, 1.1)]);
SmallSoftwareDbContext.InsertRequestToDatabaseAndReturn(_workerId, "test@mail.ru", sum: 10, false, softwares: [(_softwareId, 10, 1.1)]);
SmallSoftwareDbContext.InsertRequestToDatabaseAndReturn(worker.Id, "test@mail.ru", sum: 10, false, softwares: [(_softwareId, 10, 1.1)]);
//Act
var response = await HttpClient.GetAsync($"/api/requests/getworkerrecords?id={_workerId}&fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
var data = await GetModelFromResponseAsync<List<RequestViewModel>>(response);
Assert.That(data, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(data, Has.Count.EqualTo(2));
Assert.That(data.All(x => x.WorkerId == _workerId));
});
}
[Test]
public async Task GetList_ByWorkerId_WhenNoRecords_ShouldSuccess_Test()
{
//Arrange
var worker = SmallSoftwareDbContext.InsertWorkerToDatabaseAndReturn(fio: "Other worker");
SmallSoftwareDbContext.InsertRequestToDatabaseAndReturn(_workerId, "test@mail.ru", sum: 10, false, softwares: [(_softwareId, 10, 1.1)]);
//Act
var response = await HttpClient.GetAsync($"/api/requests/getworkerrecords?id={worker.Id}&fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
var data = await GetModelFromResponseAsync<List<RequestViewModel>>(response);
Assert.That(data, Is.Not.Null);
Assert.That(data, Has.Count.EqualTo(0));
}
[Test]
public async Task GetList_ByWorkerId_WhenDateIsIncorrect_ShouldBadRequest_Test()
{
//Act
var response = await HttpClient.GetAsync($"/api/requests/getworkerrecords?id={_workerId}&fromDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}
[Test]
public async Task GetList_ByWorkerId_WhenIdIsIncorrect_ShouldBadRequest_Test()
{
//Act
var response = await HttpClient.GetAsync($"/api/requests/getworkerrecords?id=Id&fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}
[Test]
public async Task GetList_BySoftwareId_ShouldSuccess_Test()
{
//Arrange
var software = SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(_manufacturerId, softwareName: "Other name");
SmallSoftwareDbContext.InsertRequestToDatabaseAndReturn(_workerId, "test@mail.ru", sum: 10, false, softwares: [(_softwareId, 10, 1.1)]);
SmallSoftwareDbContext.InsertRequestToDatabaseAndReturn(_workerId, "test@mail.ru", softwares: [(_softwareId, 1, 1.1), (software.Id, 4, 1.1)]);
SmallSoftwareDbContext.InsertRequestToDatabaseAndReturn(_workerId, "test@mail.ru", sum: 10, false, softwares: [(software.Id, 10, 1.1)]);
SmallSoftwareDbContext.InsertRequestToDatabaseAndReturn(_workerId, "test@mail.ru", softwares: [(software.Id, 1, 1.1), (_softwareId, 1, 1.1)]);
//Act
var response = await HttpClient.GetAsync($"/api/requests/getsoftwarerecords?id={_softwareId}&fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
var data = await GetModelFromResponseAsync<List<RequestViewModel>>(response);
Assert.That(data, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(data, Has.Count.EqualTo(3));
Assert.That(data.All(x => x.Softwares.Any(y => y.SoftwareId == _softwareId)));
});
}
[Test]
public async Task GetList_BySoftwareId_WhenNoRecords_ShouldSuccess_Test()
{
//Arrange
var software = SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(_manufacturerId, softwareName: "Other software");
SmallSoftwareDbContext.InsertRequestToDatabaseAndReturn(_workerId, "test@mail.ru", sum: 10, false, softwares: [(_softwareId, 10, 1.1)]);
//Act
var response = await HttpClient.GetAsync($"/api/requests/getsoftwarerecords?id={software.Id}&fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
var data = await GetModelFromResponseAsync<List<RequestViewModel>>(response);
Assert.That(data, Is.Not.Null);
Assert.That(data, Has.Count.EqualTo(0));
}
[Test]
public async Task GetList_BySoftwareId_WhenDateIsIncorrect_ShouldBadRequest_Test()
{
//Act
var response = await HttpClient.GetAsync($"/api/requests/getsoftwarerecords?id={_softwareId}&fromDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}
[Test]
public async Task GetList_BySoftwareId_WhenIdIsIncorrect_ShouldBadRequest_Test()
{
//Act
var response = await HttpClient.GetAsync($"/api/requests/getsoftwarerecords?id=Id&fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}
[Test]
public async Task GetElement_ById_WhenHaveRecord_ShouldSuccess_Test()
{
//Arrange
var request = SmallSoftwareDbContext.InsertRequestToDatabaseAndReturn(_workerId, "test@mail.ru", sum: 10, false, softwares: [(_softwareId, 10, 1.1)]);
//Act
var response = await HttpClient.GetAsync($"/api/requests/getrecord/{request.Id}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
AssertElement(await GetModelFromResponseAsync<RequestViewModel>(response), request);
}
[Test]
public async Task GetElement_ById_WhenNoRecord_ShouldNotFound_Test()
{
//Arrange
SmallSoftwareDbContext.InsertRequestToDatabaseAndReturn(_workerId, "test@mail.ru", sum: 10, false, softwares: [(_softwareId, 10, 1.1)]);
//Act
var response = await HttpClient.GetAsync($"/api/requests/getrecord/{Guid.NewGuid()}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
}
[Test]
public async Task GetElement_ById_WhenRecordHasCanceled_ShouldSuccess_Test()
{
//Arrange
var request = SmallSoftwareDbContext.InsertRequestToDatabaseAndReturn(_workerId, "test@mail.ru", sum: 10, softwares: [(_softwareId, 1, 1.2)], isCancel: true);
//Act
var response = await HttpClient.GetAsync($"/api/requests/getrecord/{request.Id}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
}
[Test]
public async Task GetElement_ById_WhenIdIsIncorrect_ShouldBadRequest_Test()
{
//Act
var response = await HttpClient.GetAsync($"/api/requests/getrecord/Id");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}
[Test]
public async Task Post_WhenDataIsIncorrect_ShouldBadRequest_Test()
{
//Arrange
var requestId = Guid.NewGuid().ToString();
var requestModelWithIdIncorrect = new RequestBindingModel { Id = "Id", WorkerId = _workerId, Softwares = [new InstallationRequestBindingModel { RequestId = requestId, SoftwareId = _softwareId, Count = 10, Price = 1.1 }] };
var requestModelWithWorkerIdIncorrect = new RequestBindingModel { Id = requestId, WorkerId = "Id", Softwares = [new InstallationRequestBindingModel { RequestId = requestId, SoftwareId = _softwareId, Count = 10, Price = 1.1 }] };
var requestModelWithBuyerIdIncorrect = new RequestBindingModel {Id = requestId, WorkerId = _workerId, Softwares = [new InstallationRequestBindingModel { RequestId = requestId, SoftwareId = _softwareId, Count = 10, Price = 1.1 }] };
var requestModelWithSoftwaresIncorrect = new RequestBindingModel { Id = requestId, WorkerId = _workerId, Softwares = null };
var requestModelWithSoftwareIdIncorrect = new RequestBindingModel {Id = requestId, WorkerId = _workerId, Softwares = [new InstallationRequestBindingModel { RequestId = requestId, SoftwareId = "Id", Count = 10, Price = 1.1 }] };
var requestModelWithCountIncorrect = new RequestBindingModel {Id = requestId, WorkerId = _workerId , Softwares = [new InstallationRequestBindingModel { RequestId = requestId, SoftwareId = _softwareId, Count = -10, Price = 1.1 }] };
var requestModelWithPriceIncorrect = new RequestBindingModel {Id = requestId, WorkerId = _workerId, Softwares = [new InstallationRequestBindingModel { RequestId = requestId, SoftwareId = _softwareId, Count = 10, Price = -1.1 }] };
//Act
var responseWithIdIncorrect = await HttpClient.PostAsync($"/api/requests/request", MakeContent(requestModelWithIdIncorrect));
var responseWithWorkerIdIncorrect = await HttpClient.PostAsync($"/api/requests/request", MakeContent(requestModelWithWorkerIdIncorrect));
var responseWithBuyerIdIncorrect = await HttpClient.PostAsync($"/api/requests/request", MakeContent(requestModelWithBuyerIdIncorrect));
var responseWithSoftwaresIncorrect = await HttpClient.PostAsync($"/api/requests/request", MakeContent(requestModelWithSoftwaresIncorrect));
var responseWithSoftwareIdIncorrect = await HttpClient.PostAsync($"/api/requests/request", MakeContent(requestModelWithSoftwareIdIncorrect));
var responseWithCountIncorrect = await HttpClient.PostAsync($"/api/requests/request", MakeContent(requestModelWithCountIncorrect));
var responseWithPriceIncorrect = await HttpClient.PostAsync($"/api/requests/request", MakeContent(requestModelWithPriceIncorrect));
//Assert
Assert.Multiple(() =>
{
Assert.That(responseWithIdIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "WorkerId is incorrect");
Assert.That(responseWithWorkerIdIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "WorkerId is incorrect");
Assert.That(responseWithBuyerIdIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "BuyerId is incorrect");
Assert.That(responseWithSoftwaresIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Softwares is incorrect");
Assert.That(responseWithSoftwareIdIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "SoftwareId is incorrect");
Assert.That(responseWithCountIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Count is incorrect");
Assert.That(responseWithPriceIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Price is incorrect");
});
}
[Test]
public async Task Post_WhenSendEmptyData_ShouldBadRequest_Test()
{
//Act
var response = await HttpClient.PostAsync($"/api/requests/request", MakeContent(string.Empty));
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}
[Test]
public async Task Post_WhenSendWrongFormatData_ShouldBadRequest_Test()
{
//Act
var response = await HttpClient.PostAsync($"/api/requests/request", MakeContent(new { Data = "test", Position = 10 }));
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}
[Test]
public async Task Delete_ShouldSuccess_Test()
{
//Arrange
var request = SmallSoftwareDbContext.InsertRequestToDatabaseAndReturn(_workerId, "email@mail.ru", 10, true, softwares: [(_softwareId, 5, 1.1)]);
//Act
var response = await HttpClient.DeleteAsync($"/api/requests/cancel/{request.Id}");
SmallSoftwareDbContext.ChangeTracker.Clear();
//Assert
Assert.Multiple(() =>
{
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
Assert.That(SmallSoftwareDbContext.GetRequestFromDatabaseById(request.Id)!.IsCancel);
});
}
[Test]
public async Task Delete_WhenNoFoundRecord_ShouldBadRequest_Test()
{
//Arrange
SmallSoftwareDbContext.InsertRequestToDatabaseAndReturn(_workerId, "email@mail.ru", 10, false, softwares: [(_softwareId, 5, 1.1)]);
//Act
var response = await HttpClient.DeleteAsync($"/api/requests/cancel/{Guid.NewGuid()}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}
[Test]
public async Task Delete_WhenIsCanceled_ShouldBadRequest_Test()
{
//Arrange
var request = SmallSoftwareDbContext.InsertRequestToDatabaseAndReturn(_workerId, "email@mail.ru", 10, true, softwares: [(_softwareId, 5, 1.1)]);
//Act
var response = await HttpClient.DeleteAsync($"/api/requests/cancel/{request.Id}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}
[Test]
public async Task Delete_WhenSendWrongFormatData_ShouldBadRequest_Test()
{
//Act
var response = await HttpClient.DeleteAsync($"/api/requests/cancel/id");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}
private static void AssertElement(RequestViewModel? actual, Request expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.Id, Is.EqualTo(expected.Id));
Assert.That(actual.WorkerFIO, Is.EqualTo(expected.Worker!.FIO));
Assert.That(actual.IsCancel, Is.EqualTo(expected.IsCancel));
});
if (expected.InstallationRequests is not null)
{
Assert.That(actual.Softwares, Is.Not.Null);
Assert.That(actual.Softwares, Has.Count.EqualTo(expected.InstallationRequests.Count));
for (int i = 0; i < actual.Softwares.Count; ++i)
{
Assert.Multiple(() =>
{
Assert.That(actual.Softwares[i].SoftwareName, Is.EqualTo(expected.InstallationRequests[i].Software!.SoftwareName));
Assert.That(actual.Softwares[i].Count, Is.EqualTo(expected.InstallationRequests[i].Count));
});
}
}
else
{
Assert.That(actual.Softwares, Is.Null);
}
}
private static RequestBindingModel CreateModel(string workerId, string softwareId, string? id = null, int count = 1, double price = 1.1)
{
var requestId = id ?? Guid.NewGuid().ToString();
return new()
{
Id = requestId,
WorkerId = workerId,
Softwares = [new InstallationRequestBindingModel { RequestId = requestId, SoftwareId = softwareId, Count = count, Price = price }]
};
}
private static void AssertElement(Request? actual, RequestBindingModel expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.WorkerId, Is.EqualTo(expected.WorkerId));
Assert.That(!actual.IsCancel);
});
if (expected.Softwares is not null)
{
Assert.That(actual.InstallationRequests, Is.Not.Null);
Assert.That(actual.InstallationRequests, Has.Count.EqualTo(expected.Softwares.Count));
for (int i = 0; i < actual.InstallationRequests.Count; ++i)
{
Assert.Multiple(() =>
{
Assert.That(actual.InstallationRequests[i].SoftwareId, Is.EqualTo(expected.Softwares[i].SoftwareId));
Assert.That(actual.InstallationRequests[i].Count, Is.EqualTo(expected.Softwares[i].Count));
Assert.That(actual.InstallationRequests[i].Price, Is.EqualTo(expected.Softwares[i].Price));
});
}
}
else
{
Assert.That(actual.InstallationRequests, Is.Null);
}
}
}

View File

@@ -0,0 +1,709 @@

using SmallSoftwareContracts.BindingModels;
using SmallSoftwareContracts.Enums;
using SmallSoftwareContracts.ViewModels;
using SmallSoftwareDatabase.Models;
using SmallSoftwareTests.Infrastructure;
using System.Net;
namespace SmallSoftwareTests.WebApiControllersApi;
[TestFixture]
internal class SoftwareControllerTests : BaseWebApiControllerTest
{
private string _manufacturerId;
[SetUp]
public void SetUp()
{
_manufacturerId =
SmallSoftwareDbContext.InsertManufacturerToDatabaseAndReturn().Id;
}
[TearDown]
public void TearDown()
{
SmallSoftwareDbContext.RemoveSoftwaresFromDatabase();
SmallSoftwareDbContext.RemoveManufacturersFromDatabase();
}
[Test]
public async Task GetList_WhenHaveRecords_ShouldSuccess_Test()
{
//Arrange
var software =
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(_manufacturerId,
softwareName: "name 1");
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(_manufacturerId,
softwareName: "name 2");
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(_manufacturerId,
softwareName: "name 3");
//Act
var response = await
HttpClient.GetAsync("/api/softwares/getrecords?includeDeleted=false");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
var data = await
GetModelFromResponseAsync<List<SoftwareViewModel>>(response);
Assert.Multiple(() =>
{
Assert.That(data, Is.Not.Null);
Assert.That(data, Has.Count.EqualTo(3));
});
AssertElement(data.First(x => x.Id == software.Id), software);
}
[Test]
public async Task GetList_WhenNoRecords_ShouldSuccess_Test()
{
//Act
var response = await
HttpClient.GetAsync("/api/softwares/getrecords?includeDeleted=false");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
var data = await
GetModelFromResponseAsync<List<SoftwareViewModel>>(response);
Assert.Multiple(() =>
{
Assert.That(data, Is.Not.Null);
Assert.That(data, Has.Count.EqualTo(0));
});
}
[Test]
public async Task GetList_OnlyActual_ShouldSuccess_Test()
{
//Arrange
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(_manufacturerId,
softwareName: "name 1", isDeleted: true);
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(_manufacturerId,
softwareName: "name 2", isDeleted: false);
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(_manufacturerId,
softwareName: "name 3", isDeleted: false);
//Act
var response = await
HttpClient.GetAsync("/api/softwares/getrecords?includeDeleted=false");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
var data = await
GetModelFromResponseAsync<List<SoftwareViewModel>>(response);
Assert.That(data, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(data, Has.Count.EqualTo(2));
Assert.That(data.All(x => !x.IsDeleted));
});
}
[Test]
public async Task GetList_IncludeNoActual_ShouldSuccess_Test()
{
//Arrange
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(_manufacturerId,
softwareName: "name 1", isDeleted: true);
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(_manufacturerId,
softwareName: "name 2", isDeleted: true);
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(_manufacturerId,
softwareName: "name 3", isDeleted: false);
//Act
var response = await
HttpClient.GetAsync("/api/softwares/getrecords?includeDeleted=true");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
var data = await
GetModelFromResponseAsync<List<SoftwareViewModel>>(response);
Assert.That(data, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(data, Has.Count.EqualTo(3));
Assert.That(data.Any(x => x.IsDeleted));
Assert.That(data.Any(x => !x.IsDeleted));
});
}
[Test]
public async Task GetList_ByManufacturer_ShouldSuccess_Test()
{
//Arrange
var manufacruer =
SmallSoftwareDbContext.InsertManufacturerToDatabaseAndReturn(manufacturerName: "name 2");
var software =
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(_manufacturerId,
softwareName: "name 1", isDeleted: true);
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(_manufacturerId,
softwareName: "name 2", isDeleted: false);
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(manufacruer.Id,
softwareName: "name 3", isDeleted: false);
//Act
var response = await
HttpClient.GetAsync($"/api/softwares/getmanufacturerrecords?id={_manufacturerId}&includeDeleted=true");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
var data = await
GetModelFromResponseAsync<List<SoftwareViewModel>>(response);
Assert.That(data, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(data, Has.Count.EqualTo(2));
Assert.That(data.All(x => x.ManufacturerId ==
_manufacturerId));
});
AssertElement(data.First(x => x.Id == software.Id), software);
}
[Test]
public async Task GetList_ByManufacturerOnlyActual_ShouldSuccess_Test()
{
//Arrange
var manufacruer =
SmallSoftwareDbContext.InsertManufacturerToDatabaseAndReturn(manufacturerName: "name 2");
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(_manufacturerId,
softwareName: "name 1", isDeleted: true);
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(_manufacturerId,
softwareName: "name 2", isDeleted: false);
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(manufacruer.Id,
softwareName: "name 3", isDeleted: false);
//Act
var response = await
HttpClient.GetAsync($"/api/softwares/getmanufacturerrecords?id={_manufacturerId}&includeDeleted = false");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
var data = await
GetModelFromResponseAsync<List<SoftwareViewModel>>(response);
Assert.That(data, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(data, Has.Count.EqualTo(1));
Assert.That(data.All(x => x.ManufacturerId == _manufacturerId
&& !x.IsDeleted));
});
}
[Test]
public async Task GetList_ManufacturerIdIsNotGuid_ShouldBadRequest_Test()
{
//Act
var response = await
HttpClient.GetAsync($"/api/softwares/getmanufacturerrecords?id=id&includeDeleted=false");
//Assert
Assert.That(response.StatusCode,
Is.EqualTo(HttpStatusCode.BadRequest));
}
[Test]
public async Task
GetHistoryBySoftwareId_WhenHaveRecords_ShouldSuccess_Test()
{
//Arrange
var software =
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(_manufacturerId);
SmallSoftwareDbContext.InsertSoftwareHistoryToDatabaseAndReturn(software.Id, 20,
DateTime.UtcNow.AddDays(-1));
SmallSoftwareDbContext.InsertSoftwareHistoryToDatabaseAndReturn(software.Id, 30,
DateTime.UtcNow.AddMinutes(-10));
var history =
SmallSoftwareDbContext.InsertSoftwareHistoryToDatabaseAndReturn(software.Id, 40,
DateTime.UtcNow.AddDays(1));
//Act
var response = await
HttpClient.GetAsync($"/api/softwares/gethistory?id={software.Id}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
var data = await
GetModelFromResponseAsync<List<SoftwareHistoryViewModel>>(response);
Assert.That(data, Is.Not.Null);
Assert.That(data, Has.Count.EqualTo(3));
AssertElement(data[0], history);
}
[Test]
public async Task GetHistoryBySoftwareId_WhenNoRecords_ShouldSuccess_Test()
{
//Arrange
var software =
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(_manufacturerId);
SmallSoftwareDbContext.InsertSoftwareHistoryToDatabaseAndReturn(software.Id, 20,
DateTime.UtcNow.AddDays(-1));
SmallSoftwareDbContext.InsertSoftwareHistoryToDatabaseAndReturn(software.Id, 30,
DateTime.UtcNow.AddMinutes(-10));
SmallSoftwareDbContext.InsertSoftwareHistoryToDatabaseAndReturn(software.Id, 40,
DateTime.UtcNow.AddDays(1));
//Act
var response = await
HttpClient.GetAsync($"/api/softwares/gethistory?id={Guid.NewGuid()}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
var data = await
GetModelFromResponseAsync<List<SoftwareViewModel>>(response);
Assert.That(data, Is.Not.Null);
Assert.That(data, Has.Count.EqualTo(0));
}
[Test]
public async Task
GetHistoryBySoftwareId_SoftwareIdIsNotGuid_ShouldBadRequest_Test()
{
//Act
var response = await
HttpClient.GetAsync($"/api/softwares/gethistory?id=id");
//Assert
Assert.That(response.StatusCode,
Is.EqualTo(HttpStatusCode.BadRequest));
}
[Test]
public async Task GetElement_ById_WhenHaveRecord_ShouldSuccess_Test()
{
//Arrange
var software =
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(_manufacturerId);
//Act
var response = await
HttpClient.GetAsync($"/api/softwares/getrecord/{software.Id}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
AssertElement(await
GetModelFromResponseAsync<SoftwareViewModel>(response), software);
}
[Test]
public async Task GetElement_ById_WhenNoRecord_ShouldNotFound_Test()
{
//Arrange
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(_manufacturerId);
//Act
var response = await
HttpClient.GetAsync($"/api/softwares/getrecord/{Guid.NewGuid()}");
//Assert
Assert.That(response.StatusCode,
Is.EqualTo(HttpStatusCode.NotFound));
}
[Test]
public async Task
GetElement_ById_WhenRecordWasDeleted_ShouldNotFound_Test()
{
//Arrange
var software =
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(_manufacturerId, isDeleted:
true);
//Act
var response = await
HttpClient.GetAsync($"/api/softwares/getrecord/{software.Id}");
//Assert
Assert.That(response.StatusCode,
Is.EqualTo(HttpStatusCode.NotFound));
}
[Test]
public async Task GetElement_ByName_WhenHaveRecord_ShouldSuccess_Test()
{
//Arrange
var software =
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(_manufacturerId);
//Act
var response = await
HttpClient.GetAsync($"/api/softwares/getrecord/{software.SoftwareName}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
AssertElement(await
GetModelFromResponseAsync<SoftwareViewModel>(response), software);
}
[Test]
public async Task GetElement_ByName_WhenNoRecord_ShouldNotFound_Test()
{
//Arrange
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(_manufacturerId);
//Act
var response = await
HttpClient.GetAsync($"/api/softwares/getrecord/New%20Name");
//Assert
Assert.That(response.StatusCode,
Is.EqualTo(HttpStatusCode.NotFound));
}
[Test]
public async Task
GetElement_ByName_WhenRecordWasDeleted_ShouldNotFound_Test()
{
//Arrange
var software =
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(_manufacturerId, isDeleted:
true);
//Act
var response = await
HttpClient.GetAsync($"/api/softwares/getrecord/{software.SoftwareName}");
//Assert
Assert.That(response.StatusCode,
Is.EqualTo(HttpStatusCode.NotFound));
}
[Test]
public async Task Post_ShouldSuccess_Test()
{
//Arrange
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(_manufacturerId);
var softwareModel = CreateModel(_manufacturerId);
//Act
var response = await HttpClient.PostAsync($"/api/softwares/register",
MakeContent(softwareModel));
//Assert
Assert.That(response.StatusCode,
Is.EqualTo(HttpStatusCode.NoContent));
AssertElement(SmallSoftwareDbContext.GetSoftwareFromDatabaseById(softwareModel.Id!), softwareModel);
}
[Test]
public async Task Post_WhenHaveRecordWithSameId_ShouldBadRequest_Test()
{
//Arrange
var softwareModel = CreateModel(_manufacturerId);
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(_manufacturerId,
softwareModel.Id);
//Act
var response = await HttpClient.PostAsync($"/api/softwares/register",
MakeContent(softwareModel));
//Assert
Assert.That(response.StatusCode,
Is.EqualTo(HttpStatusCode.BadRequest));
}
[Test]
public async Task Post_WhenHaveRecordWithSameName_ShouldBadRequest_Test()
{
//Arrange
var softwareModel = CreateModel(_manufacturerId, softwareName: "unique name");
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(_manufacturerId,
softwareName: softwareModel.SoftwareName!);
//Act
var response = await HttpClient.PostAsync($"/api/softwares/register",
MakeContent(softwareModel));
//Assert
Assert.That(response.StatusCode,
Is.EqualTo(HttpStatusCode.BadRequest));
}
[Test]
public async Task Post_WhenDataIsIncorrect_ShouldBadRequest_Test()
{
//Arrange
var softwareModelWithIdIncorrect = new SoftwareBindingModel
{
Id = "Id",
ManufacturerId = _manufacturerId,
SoftwareName = "name",
Price = 100,
SoftwareType = SoftwareType.Windows.ToString()
};
var softwareModelWithNameIncorrect = new SoftwareBindingModel
{
Id = Guid.NewGuid().ToString(),
ManufacturerId = _manufacturerId,
SoftwareName = string.Empty,
Price = 100,
SoftwareType = SoftwareType.Windows.ToString()
};
var softwareModelWithSoftwareTypeIncorrect = new SoftwareBindingModel
{
Id = Guid.NewGuid().ToString(),
ManufacturerId = _manufacturerId,
SoftwareName =
"name",
Price = 100,
SoftwareType = string.Empty
};
var softwareModelWithPriceIncorrect = new SoftwareBindingModel
{
Id =
Guid.NewGuid().ToString(),
ManufacturerId = _manufacturerId,
SoftwareName =
"name",
Price = 0,
SoftwareType = SoftwareType.Windows.ToString()
};
//Act
var responseWithIdIncorrect = await
HttpClient.PostAsync($"/api/softwares/register",
MakeContent(softwareModelWithIdIncorrect));
var responseWithNameIncorrect = await
HttpClient.PostAsync($"/api/softwares/register",
MakeContent(softwareModelWithNameIncorrect));
var responseWithSoftwareTypeIncorrect = await
HttpClient.PostAsync($"/api/softwares/register",
MakeContent(softwareModelWithSoftwareTypeIncorrect));
var responseWithPriceIncorrect = await
HttpClient.PostAsync($"/api/softwares/register",
MakeContent(softwareModelWithPriceIncorrect));
//Assert
Assert.Multiple(() =>
{
Assert.That(responseWithIdIncorrect.StatusCode,
Is.EqualTo(HttpStatusCode.BadRequest), "Id is incorrect");
Assert.That(responseWithNameIncorrect.StatusCode,
Is.EqualTo(HttpStatusCode.BadRequest), "Name is incorrect");
Assert.That(responseWithSoftwareTypeIncorrect.StatusCode,
Is.EqualTo(HttpStatusCode.BadRequest), "Name is incorrect");
Assert.That(responseWithPriceIncorrect.StatusCode,
Is.EqualTo(HttpStatusCode.BadRequest), "Name is incorrect");
});
}
[Test]
public async Task Post_WhenSendEmptyData_ShouldBadRequest_Test()
{
//Act
var response = await HttpClient.PostAsync($"/api/softwares/register",
MakeContent(string.Empty));
//Assert
Assert.That(response.StatusCode,
Is.EqualTo(HttpStatusCode.BadRequest));
}
[Test]
public async Task Post_WhenSendWrongFormatData_ShouldBadRequest_Test()
{
//Act
var response = await HttpClient.PostAsync($"/api/softwares/register",
MakeContent(new { Data = "test", Position = 10 }));
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}
[Test]
public async Task Put_ShouldSuccess_Test()
{
//Arrange
var softwareModel = CreateModel(_manufacturerId);
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(_manufacturerId,
softwareModel.Id);
//Act
var response = await HttpClient.PutAsync($"/api/softwares/changeinfo",
MakeContent(softwareModel));
//Assert
Assert.That(response.StatusCode,
Is.EqualTo(HttpStatusCode.NoContent));
SmallSoftwareDbContext.ChangeTracker.Clear();
AssertElement(SmallSoftwareDbContext.GetSoftwareFromDatabaseById(softwareModel.Id!), softwareModel);
}
[Test]
public async Task Put_WhenNoFoundRecord_ShouldBadRequest_Test()
{
//Arrange
var softwareModel = CreateModel(_manufacturerId);
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(_manufacturerId);
//Act
var response = await HttpClient.PutAsync($"/api/softwares/changeinfo",
MakeContent(softwareModel));
//Assert
Assert.That(response.StatusCode,
Is.EqualTo(HttpStatusCode.BadRequest));
}
[Test]
public async Task Put_WhenHaveRecordWithSameName_ShouldBadRequest_Test()
{
//Arrange
var softwareModel = CreateModel(_manufacturerId, softwareName: "unique name");
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(_manufacturerId, softwareModel.Id);
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(_manufacturerId,
softwareName: softwareModel.SoftwareName!);
//Act
var response = await HttpClient.PutAsync($"/api/softwares/changeinfo",
MakeContent(softwareModel));
//Assert
Assert.That(response.StatusCode,
Is.EqualTo(HttpStatusCode.BadRequest));
}
[Test]
public async Task Put_WhenRecordWasDeleted_ShouldBadRequest_Test()
{
//Arrange
var softwareModel = CreateModel(_manufacturerId);
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(_manufacturerId,
softwareModel.Id, isDeleted: true);
//Act
var response = await HttpClient.PutAsync($"/api/softwares/changeinfo",
MakeContent(softwareModel));
//Assert
Assert.That(response.StatusCode,
Is.EqualTo(HttpStatusCode.BadRequest));
}
[Test]
public async Task Put_WhenDataIsIncorrect_ShouldBadRequest_Test()
{
//Arrange
var softwareModelWithIdIncorrect = new SoftwareBindingModel
{
Id = "Id",
ManufacturerId = _manufacturerId,
SoftwareName = "name",
Price = 100,
SoftwareType = SoftwareType.Windows.ToString()
};
var softwareModelWithNameIncorrect = new SoftwareBindingModel
{
Id =
Guid.NewGuid().ToString(),
ManufacturerId = _manufacturerId,
SoftwareName =
string.Empty,
Price = 100,
SoftwareType = SoftwareType.Windows.ToString()
};
var softwareModelWithSoftwareTypeIncorrect = new SoftwareBindingModel
{
Id = Guid.NewGuid().ToString(),
ManufacturerId = _manufacturerId,
SoftwareName =
"name",
Price = 100,
SoftwareType = string.Empty
};
var softwareModelWithPriceIncorrect = new SoftwareBindingModel
{
Id =
Guid.NewGuid().ToString(),
ManufacturerId = _manufacturerId,
SoftwareName =
"name",
Price = 0,
SoftwareType = SoftwareType.Windows.ToString()
};
//Act
var responseWithIdIncorrect = await
HttpClient.PutAsync($"/api/softwares/changeinfo",
MakeContent(softwareModelWithIdIncorrect));
var responseWithNameIncorrect = await
HttpClient.PutAsync($"/api/softwares/changeinfo",
MakeContent(softwareModelWithNameIncorrect));
var responseWithSoftwareTypeIncorrect = await
HttpClient.PutAsync($"/api/softwares/changeinfo",
MakeContent(softwareModelWithSoftwareTypeIncorrect));
var responseWithPriceIncorrect = await
HttpClient.PutAsync($"/api/softwares/changeinfo",
MakeContent(softwareModelWithPriceIncorrect));
//Assert
Assert.Multiple(() =>
{
Assert.That(responseWithIdIncorrect.StatusCode,
Is.EqualTo(HttpStatusCode.BadRequest), "Id is incorrect");
Assert.That(responseWithNameIncorrect.StatusCode,
Is.EqualTo(HttpStatusCode.BadRequest), "Name is incorrect");
Assert.That(responseWithSoftwareTypeIncorrect.StatusCode,
Is.EqualTo(HttpStatusCode.BadRequest), "Name is incorrect");
Assert.That(responseWithPriceIncorrect.StatusCode,
Is.EqualTo(HttpStatusCode.BadRequest), "Name is incorrect");
});
}
[Test]
public async Task Put_WhenSendEmptyData_ShouldBadRequest_Test()
{
//Act
var response = await HttpClient.PutAsync($"/api/softwares/changeinfo",
MakeContent(string.Empty));
//Assert
Assert.That(response.StatusCode,
Is.EqualTo(HttpStatusCode.BadRequest));
}
[Test]
public async Task Put_WhenSendWrongFormatData_ShouldBadRequest_Test()
{
//Act
var response = await HttpClient.PutAsync($"/api/softwares/changeinfo",
MakeContent(new { Data = "test", Position = 10 }));
//Assert
Assert.That(response.StatusCode,
Is.EqualTo(HttpStatusCode.BadRequest));
}
[Test]
public async Task Delete_ShouldSuccess_Test()
{
//Arrange
var softwareId = Guid.NewGuid().ToString();
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(_manufacturerId,
softwareId);
//Act
var response = await
HttpClient.DeleteAsync($"/api/softwares/delete/{softwareId}");
SmallSoftwareDbContext.ChangeTracker.Clear();
//Assert
Assert.Multiple(() =>
{
Assert.That(response.StatusCode,
Is.EqualTo(HttpStatusCode.NoContent));
Assert.That(SmallSoftwareDbContext.GetSoftwareFromDatabaseById(softwareId)!.IsDeleted);
});
}
[Test]
public async Task Delete_WhenNoFoundRecord_ShouldBadRequest_Test()
{
//Arrange
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(_manufacturerId);
//Act
var response = await
HttpClient.DeleteAsync($"/api/softwares/delete/{Guid.NewGuid()}");
//Assert
Assert.That(response.StatusCode,
Is.EqualTo(HttpStatusCode.BadRequest));
}
[Test]
public async Task Delete_WhenRecordWasDeleted_ShouldBadRequest_Test()
{
//Arrange
var softwareId =
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(_manufacturerId, isDeleted:
true).Id;
//Act
var response = await
HttpClient.DeleteAsync($"/api/softwares/delete/{softwareId}");
//Assert
Assert.That(response.StatusCode,
Is.EqualTo(HttpStatusCode.BadRequest));
}
[Test]
public async Task Delete_WhenSendWrongFormatData_ShouldBadRequest_Test()
{
//Act
var response = await
HttpClient.DeleteAsync($"/api/softwares/delete/id");
//Assert
Assert.That(response.StatusCode,
Is.EqualTo(HttpStatusCode.BadRequest));
}
private static void AssertElement(SoftwareViewModel? actual, Software expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.Id, Is.EqualTo(expected.Id));
Assert.That(actual.ManufacturerId,
Is.EqualTo(expected.ManufacturerId));
Assert.That(actual.SoftwareName,
Is.EqualTo(expected.SoftwareName));
Assert.That(actual.SoftwareType,
Is.EqualTo(expected.SoftwareType.ToString()));
Assert.That(actual.Price, Is.EqualTo(expected.Price));
Assert.That(actual.IsDeleted, Is.EqualTo(expected.IsDeleted));
Assert.That(actual.ManufacturerName,
Is.EqualTo(expected.Manufacturer!.ManufacturerName));
});
}
private static void AssertElement(SoftwareHistoryViewModel? actual,
SoftwareHistory expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.SoftwareName,
Is.EqualTo(expected.Software!.SoftwareName));
Assert.That(actual.OldPrice, Is.EqualTo(expected.OldPrice));
Assert.That(actual.ChangeDate.ToString(),
Is.EqualTo(expected.ChangeDate.ToString()));
});
}
private static SoftwareBindingModel CreateModel(string manufacturerId,
string? id = null, string softwareName = "name", SoftwareType softwareType =
SoftwareType.Windows, double price = 1)
=> new()
{
Id = id ?? Guid.NewGuid().ToString(),
ManufacturerId = manufacturerId,
SoftwareName = softwareName,
SoftwareType = softwareType.ToString(),
Price = price
};
private static void AssertElement(Software? actual, SoftwareBindingModel
expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.Id, Is.EqualTo(expected.Id));
Assert.That(actual.ManufacturerId,
Is.EqualTo(expected.ManufacturerId));
Assert.That(actual.SoftwareName,
Is.EqualTo(expected.SoftwareName));
Assert.That(actual.SoftwareType.ToString(),
Is.EqualTo(expected.SoftwareType));
Assert.That(actual.Price, Is.EqualTo(expected.Price));
Assert.That(!actual.IsDeleted);
});
}
}

View File

@@ -0,0 +1,232 @@
using AutoMapper;
using SmallSoftwareContracts.AdapterContracts;
using SmallSoftwareContracts.AdapterContracts.OperationResponses;
using SmallSoftwareContracts.BindingModels;
using SmallSoftwareContracts.BusinessLogicsContracts;
using SmallSoftwareContracts.DataModels;
using SmallSoftwareContracts.Exceptions;
using SmallSoftwareContracts.ViewModels;
namespace SmallSoftwareWebApi.Adapters;
public class RequestAdapter : IRequestAdapter
{
private readonly IRequestBusinessLogicContract _requestBusinessLogicContract;
private readonly ILogger _logger;
private readonly Mapper _mapper;
public RequestAdapter(IRequestBusinessLogicContract requestBusinessLogicContract, ILogger<RequestAdapter> logger)
{
_requestBusinessLogicContract = requestBusinessLogicContract;
_logger = logger;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<RequestBindingModel, RequestDataModel>();
cfg.CreateMap<RequestDataModel, RequestViewModel>();
cfg.CreateMap<InstallationRequestBindingModel, InstallationRequestDataModel>();
cfg.CreateMap<InstallationRequestDataModel, InstallationRequestViewModel>();
});
_mapper = new Mapper(config);
}
public RequestOperationResponse GetList(DateTime fromDate, DateTime toDate)
{
try
{
return RequestOperationResponse.OK([.. _requestBusinessLogicContract.GetAllRequestsByPeriod(fromDate, toDate).Select(x => _mapper.Map<RequestViewModel>(x))]);
}
catch (IncorrectDatesException ex)
{
_logger.LogError(ex, "IncorrectDatesException");
return RequestOperationResponse.BadRequest($"Incorrect dates: {ex.Message}");
}
catch (NullListException)
{
_logger.LogError("NullListException");
return RequestOperationResponse.NotFound("The list is not initialized");
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return RequestOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
}
catch (Exception ex)
{
_logger.LogError(ex, "Exception");
return RequestOperationResponse.InternalServerError(ex.Message);
}
}
public RequestOperationResponse GetWorkerList(string id, DateTime fromDate, DateTime toDate)
{
try
{
return RequestOperationResponse.OK([.. _requestBusinessLogicContract.GetAllRequestsByWorkerByPeriod(id, fromDate, toDate).Select(x => _mapper.Map<RequestViewModel>(x))]);
}
catch (IncorrectDatesException ex)
{
_logger.LogError(ex, "IncorrectDatesException");
return RequestOperationResponse.BadRequest($"Incorrect dates: {ex.Message}");
}
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return RequestOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
}
catch (NullListException)
{
_logger.LogError("NullListException");
return RequestOperationResponse.NotFound("The list is not initialized");
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return RequestOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
}
catch (Exception ex)
{
_logger.LogError(ex, "Exception");
return RequestOperationResponse.InternalServerError(ex.Message);
}
}
public RequestOperationResponse GetSoftwareList(string id, DateTime fromDate, DateTime toDate)
{
try
{
return RequestOperationResponse.OK([.. _requestBusinessLogicContract.GetAllRequestsBySoftwareByPeriod(id, fromDate, toDate).Select(x => _mapper.Map<RequestViewModel>(x))]);
}
catch (IncorrectDatesException ex)
{
_logger.LogError(ex, "IncorrectDatesException");
return RequestOperationResponse.BadRequest($"Incorrect dates: {ex.Message}");
}
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return RequestOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
}
catch (NullListException)
{
_logger.LogError("NullListException");
return RequestOperationResponse.NotFound("The list is not initialized");
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return RequestOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
}
catch (Exception ex)
{
_logger.LogError(ex, "Exception");
return RequestOperationResponse.InternalServerError(ex.Message);
}
}
public RequestOperationResponse GetElement(string id)
{
try
{
return RequestOperationResponse.OK(_mapper.Map<RequestViewModel>(_requestBusinessLogicContract.GetRequestByData(id)));
}
catch (ArgumentNullException ex)
{
_logger.LogError(ex, "ArgumentNullException");
return RequestOperationResponse.BadRequest("Data is empty");
}
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return RequestOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
}
catch (ElementNotFoundException ex)
{
_logger.LogError(ex, "ElementNotFoundException");
return RequestOperationResponse.NotFound($"Not found element by data {id}");
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return RequestOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
}
catch (Exception ex)
{
_logger.LogError(ex, "Exception");
return RequestOperationResponse.InternalServerError(ex.Message);
}
}
public RequestOperationResponse MakeRequest(RequestBindingModel requestModel)
{
try
{
var data = _mapper.Map<RequestDataModel>(requestModel);
_requestBusinessLogicContract.InsertRequest(_mapper.Map<RequestDataModel>(requestModel));
return RequestOperationResponse.NoContent();
}
catch (ArgumentNullException ex)
{
_logger.LogError(ex, "ArgumentNullException");
return RequestOperationResponse.BadRequest("Data is empty");
}
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return RequestOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return RequestOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
}
catch (Exception ex)
{
_logger.LogError(ex, "Exception");
return RequestOperationResponse.InternalServerError(ex.Message);
}
}
public RequestOperationResponse CancelRequest(string id)
{
try
{
_requestBusinessLogicContract.CancelRequest(id);
return RequestOperationResponse.NoContent();
}
catch (ArgumentNullException ex)
{
_logger.LogError(ex, "ArgumentNullException");
return RequestOperationResponse.BadRequest("Id is empty");
}
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return RequestOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
}
catch (ElementNotFoundException ex)
{
_logger.LogError(ex, "ElementNotFoundException");
return RequestOperationResponse.BadRequest($"Not found element by id: {id}");
}
catch (ElementDeletedException ex)
{
_logger.LogError(ex, "ElementDeletedException");
return RequestOperationResponse.BadRequest($"Element by id: {id} was deleted");
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return RequestOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
}
catch (Exception ex)
{
_logger.LogError(ex, "Exception");
return RequestOperationResponse.InternalServerError(ex.Message);
}
}
}

View File

@@ -0,0 +1,266 @@
using AutoMapper;
using SmallSoftwareContracts.AdapterContracts;
using SmallSoftwareContracts.AdapterContracts.OperationResponses;
using SmallSoftwareContracts.BindingModels;
using SmallSoftwareContracts.BusinessLogicsContracts;
using SmallSoftwareContracts.DataModels;
using SmallSoftwareContracts.Exceptions;
using SmallSoftwareContracts.ViewModels;
namespace SmallSoftwareWebApi.Adapters;
public class SoftwareAdapter : ISoftwareAdapter
{
private readonly ISoftwareBusinessLogicContract _softwareBusinessLogicContract;
private readonly ILogger _logger;
private readonly Mapper _mapper;
public SoftwareAdapter(ISoftwareBusinessLogicContract softwareBusinessLogicContract, ILogger<SoftwareAdapter> logger)
{
_softwareBusinessLogicContract = softwareBusinessLogicContract;
_logger = logger;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<SoftwareBindingModel, SoftwareDataModel>();
cfg.CreateMap<SoftwareDataModel, SoftwareViewModel>();
cfg.CreateMap<SoftwareHistoryDataModel, SoftwareHistoryViewModel>();
});
_mapper = new Mapper(config);
}
public SoftwareOperationResponse GetList(bool includeDeleted)
{
try
{
return SoftwareOperationResponse.OK([.. _softwareBusinessLogicContract.GetAllSoftwares(!includeDeleted).Select(x => _mapper.Map<SoftwareViewModel>(x))]);
}
catch (NullListException)
{
_logger.LogError("NullListException");
return SoftwareOperationResponse.NotFound("The list is not initialized");
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return SoftwareOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
}
catch (Exception ex)
{
_logger.LogError(ex, "Exception");
return SoftwareOperationResponse.InternalServerError(ex.Message);
}
}
public SoftwareOperationResponse GetManufacturerList(string id, bool includeDeleted)
{
try
{
return SoftwareOperationResponse.OK([.. _softwareBusinessLogicContract.GetAllSoftwaresByManufacturer(id, !includeDeleted).Select(x => _mapper.Map<SoftwareViewModel>(x))]);
}
catch (ArgumentNullException ex)
{
_logger.LogError(ex, "ArgumentNullException");
return SoftwareOperationResponse.BadRequest("Data is empty");
}
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return SoftwareOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
}
catch (NullListException)
{
_logger.LogError("NullListException");
return SoftwareOperationResponse.NotFound("The list is not initialized");
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return SoftwareOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
}
catch (Exception ex)
{
_logger.LogError(ex, "Exception");
return SoftwareOperationResponse.InternalServerError(ex.Message);
}
}
public SoftwareOperationResponse GetHistory(string id)
{
try
{
return SoftwareOperationResponse.OK([.. _softwareBusinessLogicContract.GetSoftwareHistoryBySoftware(id).Select(x => _mapper.Map<SoftwareHistoryViewModel>(x))]);
}
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return SoftwareOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
}
catch (NullListException)
{
_logger.LogError("NullListException");
return SoftwareOperationResponse.NotFound("The list is not initialized");
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return SoftwareOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
}
catch (Exception ex)
{
_logger.LogError(ex, "Exception");
return SoftwareOperationResponse.InternalServerError(ex.Message);
}
}
public SoftwareOperationResponse GetElement(string data)
{
try
{
return SoftwareOperationResponse.OK(_mapper.Map<SoftwareViewModel>(_softwareBusinessLogicContract.GetSoftwareByData(data)));
}
catch (ArgumentNullException ex)
{
_logger.LogError(ex, "ArgumentNullException");
return SoftwareOperationResponse.BadRequest("Data is empty");
}
catch (ElementNotFoundException ex)
{
_logger.LogError(ex, "ElementNotFoundException");
return SoftwareOperationResponse.NotFound($"Not found element by data {data}");
}
catch (ElementDeletedException ex)
{
_logger.LogError(ex, "ElementDeletedException");
return SoftwareOperationResponse.BadRequest($"Element by data: {data} was deleted");
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return SoftwareOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
}
catch (Exception ex)
{
_logger.LogError(ex, "Exception");
return SoftwareOperationResponse.InternalServerError(ex.Message);
}
}
public SoftwareOperationResponse RegisterSoftware(SoftwareBindingModel softwareModel)
{
try
{
_softwareBusinessLogicContract.InsertSoftware(_mapper.Map<SoftwareDataModel>(softwareModel));
return SoftwareOperationResponse.NoContent();
}
catch (ArgumentNullException ex)
{
_logger.LogError(ex, "ArgumentNullException");
return SoftwareOperationResponse.BadRequest("Data is empty");
}
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return SoftwareOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
}
catch (ElementExistsException ex)
{
_logger.LogError(ex, "ElementExistsException");
return SoftwareOperationResponse.BadRequest(ex.Message);
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return SoftwareOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
}
catch (Exception ex)
{
_logger.LogError(ex, "Exception");
return SoftwareOperationResponse.InternalServerError(ex.Message);
}
}
public SoftwareOperationResponse ChangeSoftwareInfo(SoftwareBindingModel softwareModel)
{
try
{
_softwareBusinessLogicContract.UpdateSoftware(_mapper.Map<SoftwareDataModel>(softwareModel));
return SoftwareOperationResponse.NoContent();
}
catch (ArgumentNullException ex)
{
_logger.LogError(ex, "ArgumentNullException");
return SoftwareOperationResponse.BadRequest("Data is empty");
}
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return SoftwareOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
}
catch (ElementNotFoundException ex)
{
_logger.LogError(ex, "ElementNotFoundException");
return SoftwareOperationResponse.BadRequest($"Not found element by Id {softwareModel.Id}");
}
catch (ElementExistsException ex)
{
_logger.LogError(ex, "ElementExistsException");
return SoftwareOperationResponse.BadRequest(ex.Message);
}
catch (ElementDeletedException ex)
{
_logger.LogError(ex, "ElementDeletedException");
return SoftwareOperationResponse.BadRequest($"Element by id: {softwareModel.Id} was deleted");
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return SoftwareOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
}
catch (Exception ex)
{
_logger.LogError(ex, "Exception");
return SoftwareOperationResponse.InternalServerError(ex.Message);
}
}
public SoftwareOperationResponse RemoveSoftware(string id)
{
try
{
_softwareBusinessLogicContract.DeleteSoftware(id);
return SoftwareOperationResponse.NoContent();
}
catch (ArgumentNullException ex)
{
_logger.LogError(ex, "ArgumentNullException");
return SoftwareOperationResponse.BadRequest("Id is empty");
}
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return SoftwareOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
}
catch (ElementNotFoundException ex)
{
_logger.LogError(ex, "ElementNotFoundException");
return SoftwareOperationResponse.BadRequest($"Not found element by id: {id}");
}
catch (ElementDeletedException ex)
{
_logger.LogError(ex, "ElementDeletedException");
return SoftwareOperationResponse.BadRequest($"Element by id: {id} was deleted");
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return SoftwareOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
}
catch (Exception ex)
{
_logger.LogError(ex, "Exception");
return SoftwareOperationResponse.InternalServerError(ex.Message);
}
}
}

View File

@@ -0,0 +1,51 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SmallSoftwareContracts.AdapterContracts;
using SmallSoftwareContracts.BindingModels;
namespace SmallSoftwareWebApi.Controllers;
[Authorize]
[Route("api/[controller]/[action]")]
[ApiController]
[Produces("application/json")]
public class RequestsController(IRequestAdapter adapter) : ControllerBase
{
private readonly IRequestAdapter _adapter = adapter;
[HttpGet]
public IActionResult GetRecords(DateTime fromDate, DateTime toDate)
{
return _adapter.GetList(fromDate, toDate).GetResponse(Request, Response);
}
[HttpGet]
public IActionResult GetWorkerRecords(string id, DateTime fromDate,
DateTime toDate)
{
return _adapter.GetWorkerList(id, fromDate,
toDate).GetResponse(Request, Response);
}
[HttpGet]
[HttpGet]
public IActionResult GetSoftwareRecords(string id, DateTime fromDate,
DateTime toDate)
{
return _adapter.GetSoftwareList(id, fromDate,
toDate).GetResponse(Request, Response);
}
[HttpGet("{data}")]
public IActionResult GetRecord(string data)
{
return _adapter.GetElement(data).GetResponse(Request, Response);
}
[HttpPost]
public IActionResult Request_([FromBody] RequestBindingModel model)
{
return _adapter.MakeRequest(model).GetResponse(Request, Response);
}
[HttpDelete("{id}")]
public IActionResult Cancel(string id)
{
return _adapter.CancelRequest(id).GetResponse(Request, Response);
}
}

View File

@@ -0,0 +1,58 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using SmallSoftwareContracts.AdapterContracts;
using SmallSoftwareContracts.BindingModels;
namespace SmallSoftwareWebApi.Controllers;
[Authorize]
[Route("api/[controller]/[action]")]
[ApiController]
[Produces("application/json")]
public class SoftwaresController(ISoftwareAdapter adapter) : ControllerBase
{
private readonly ISoftwareAdapter _adapter = adapter;
[HttpGet]
public IActionResult GetRecords(bool includeDeleted)
{
return _adapter.GetList(includeDeleted).GetResponse(Request,
Response);
}
[HttpGet]
public IActionResult GetManufacturerRecords(string id, bool includeDeleted)
{
return _adapter.GetManufacturerList(id,
includeDeleted).GetResponse(Request, Response);
}
[HttpGet]
public IActionResult GetHistory(string id)
{
return _adapter.GetHistory(id).GetResponse(Request, Response);
}
[HttpGet("{data}")]
public IActionResult GetRecord(string data)
{
return _adapter.GetElement(data).GetResponse(Request, Response);
}
[HttpPost]
public IActionResult Register([FromBody] SoftwareBindingModel model)
{
return _adapter.RegisterSoftware(model).GetResponse(Request,
Response);
}
[HttpPut]
public IActionResult ChangeInfo([FromBody] SoftwareBindingModel model)
{
return _adapter.ChangeSoftwareInfo(model).GetResponse(Request,
Response);
}
[HttpDelete("{id}")]
public IActionResult Delete(string id)
{
return _adapter.RemoveSoftware(id).GetResponse(Request, Response);
}
}

View File

@@ -65,7 +65,9 @@ builder.Services.AddTransient<IRequestStorageContract, RequestStorageContract>()
builder.Services.AddTransient<IWorkerStorageContract, WorkerStorageContract>();
builder.Services.AddTransient<IManufacturerAdapter, ManufacturerAdapter>();
builder.Services.AddTransient<IPostAdapter, PostAdapter>();
builder.Services.AddTransient<IPostAdapter, PostAdapter>();
builder.Services.AddTransient<ISoftwareAdapter, SoftwareAdapter>();
builder.Services.AddTransient<IRequestAdapter, RequestAdapter>();
// Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi
builder.Services.AddOpenApi();