From 79291a4ba19c15d5cd8d6e2ebba4d625845f668c Mon Sep 17 00:00:00 2001 From: Dmytro Date: Sun, 31 Mar 2024 21:14:59 +0300 Subject: [PATCH 01/25] add: update endpoint for historicalContext --- .../Update/UpdateHistoricalContextCommand.cs | 8 +++ .../Update/UpdateHistoricalContextHandler.cs | 55 +++++++++++++++++++ .../Timeline/HistoricalContextController.cs | 15 ++++- .../Streetcode.WebApi/appsettings.Local.json | 2 +- 4 files changed, 78 insertions(+), 2 deletions(-) create mode 100644 Streetcode/Streetcode.BLL/MediatR/Timeline/HistoricalContext/Update/UpdateHistoricalContextCommand.cs create mode 100644 Streetcode/Streetcode.BLL/MediatR/Timeline/HistoricalContext/Update/UpdateHistoricalContextHandler.cs diff --git a/Streetcode/Streetcode.BLL/MediatR/Timeline/HistoricalContext/Update/UpdateHistoricalContextCommand.cs b/Streetcode/Streetcode.BLL/MediatR/Timeline/HistoricalContext/Update/UpdateHistoricalContextCommand.cs new file mode 100644 index 000000000..5de899063 --- /dev/null +++ b/Streetcode/Streetcode.BLL/MediatR/Timeline/HistoricalContext/Update/UpdateHistoricalContextCommand.cs @@ -0,0 +1,8 @@ +using FluentResults; +using MediatR; +using Streetcode.BLL.DTO.Timeline; + +namespace Streetcode.BLL.MediatR.Timeline.HistoricalContext.Update +{ + public record UpdateHistoricalContextCommand(HistoricalContextDTO HistoricalContext) : IRequest>; +} \ No newline at end of file diff --git a/Streetcode/Streetcode.BLL/MediatR/Timeline/HistoricalContext/Update/UpdateHistoricalContextHandler.cs b/Streetcode/Streetcode.BLL/MediatR/Timeline/HistoricalContext/Update/UpdateHistoricalContextHandler.cs new file mode 100644 index 000000000..af0d110cc --- /dev/null +++ b/Streetcode/Streetcode.BLL/MediatR/Timeline/HistoricalContext/Update/UpdateHistoricalContextHandler.cs @@ -0,0 +1,55 @@ +using AutoMapper; +using FluentResults; +using MediatR; +using Streetcode.BLL.DTO.Timeline; +using Streetcode.BLL.Interfaces.Logging; +using Streetcode.DAL.Entities.Timeline; +using Streetcode.DAL.Repositories.Interfaces.Base; + +namespace Streetcode.BLL.MediatR.Timeline.HistoricalContext.Update +{ + public class + UpdateHistoricalContextHandler : IRequestHandler> + { + private readonly IMapper _mapper; + private readonly IRepositoryWrapper _repositoryWrapper; + private readonly ILoggerService _logger; + + public UpdateHistoricalContextHandler(IRepositoryWrapper repository, IMapper mapper, ILoggerService logger) + { + _repositoryWrapper = repository; + _mapper = mapper; + _logger = logger; + } + + public async Task> Handle( + UpdateHistoricalContextCommand request, + CancellationToken cancellationToken) + { + /* have some shitty code right here, if you delete the DAL.Entities.Timeline. part it will show error + even if you have using Streetcode.DAL.Entities.Timeline; so sad :( */ + var historicalContext = + await _repositoryWrapper.HistoricalContextRepository.GetFirstOrDefaultAsync(x => + x.Id == request.HistoricalContext.Id); + if (historicalContext is null) + { + string exMessage = $"No context found by entered Id - {request.HistoricalContext.Id}"; + _logger.LogError(request, exMessage); + return Result.Fail(exMessage); + } + + try + { + var contextToUpdate = _mapper.Map(request.HistoricalContext); + _repositoryWrapper.HistoricalContextRepository.Update(contextToUpdate); + await _repositoryWrapper.SaveChangesAsync(); + return Result.Ok(_mapper.Map(contextToUpdate)); + } + catch (Exception ex) + { + _logger.LogError(request, ex.Message); + return Result.Fail(ex.Message); + } + } + } +} \ No newline at end of file diff --git a/Streetcode/Streetcode.WebApi/Controllers/Timeline/HistoricalContextController.cs b/Streetcode/Streetcode.WebApi/Controllers/Timeline/HistoricalContextController.cs index 4de031357..20489c2c0 100644 --- a/Streetcode/Streetcode.WebApi/Controllers/Timeline/HistoricalContextController.cs +++ b/Streetcode/Streetcode.WebApi/Controllers/Timeline/HistoricalContextController.cs @@ -1,5 +1,9 @@ -using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using Streetcode.BLL.DTO.Timeline; using Streetcode.BLL.MediatR.Timeline.HistoricalContext.GetAll; +using Streetcode.BLL.MediatR.Timeline.HistoricalContext.Update; +using Streetcode.DAL.Enums; namespace Streetcode.WebApi.Controllers.Timeline { @@ -10,5 +14,14 @@ public async Task GetAll() { return HandleResult(await Mediator.Send(new GetAllHistoricalContextQuery())); } + + [HttpPut] + [Authorize(Roles = nameof(UserRole.Admin))] + [ProducesResponseType(StatusCodes.Status401Unauthorized)] + [ProducesResponseType(StatusCodes.Status403Forbidden)] + public async Task Update([FromBody]HistoricalContextDTO contextDto) + { + return HandleResult(await Mediator.Send(new UpdateHistoricalContextCommand(contextDto))); + } } } diff --git a/Streetcode/Streetcode.WebApi/appsettings.Local.json b/Streetcode/Streetcode.WebApi/appsettings.Local.json index 8258a37e6..825a42304 100644 --- a/Streetcode/Streetcode.WebApi/appsettings.Local.json +++ b/Streetcode/Streetcode.WebApi/appsettings.Local.json @@ -1,5 +1,5 @@ { "ConnectionStrings": { - "DefaultConnection": "Server=127.0.0.1;Database=StreetcodeDb;User Id=sa;Password=Admin@1234;MultipleActiveResultSets=true" + "DefaultConnection": "Server=PC;Database=Streetcode1;MultipleActiveResultSets=true;Trusted_Connection=True;TrustServerCertificate=True;" } } From deb182186af99f81cb991efab80c8aa85906f160 Mon Sep 17 00:00:00 2001 From: Dmytro Date: Sun, 31 Mar 2024 22:10:03 +0300 Subject: [PATCH 02/25] add: getById endpoint for historicalContext --- .../GetHistoricalContextByIdHandler.cs | 46 +++++++++++++++++++ .../GetById/GetHistoricalContextByIdQuery.cs | 8 ++++ .../Streetcode.BLL/Streetcode.BLL.csproj | 1 + .../Timeline/HistoricalContextController.cs | 7 +++ 4 files changed, 62 insertions(+) create mode 100644 Streetcode/Streetcode.BLL/MediatR/Timeline/HistoricalContext/GetById/GetHistoricalContextByIdHandler.cs create mode 100644 Streetcode/Streetcode.BLL/MediatR/Timeline/HistoricalContext/GetById/GetHistoricalContextByIdQuery.cs diff --git a/Streetcode/Streetcode.BLL/MediatR/Timeline/HistoricalContext/GetById/GetHistoricalContextByIdHandler.cs b/Streetcode/Streetcode.BLL/MediatR/Timeline/HistoricalContext/GetById/GetHistoricalContextByIdHandler.cs new file mode 100644 index 000000000..37db2635e --- /dev/null +++ b/Streetcode/Streetcode.BLL/MediatR/Timeline/HistoricalContext/GetById/GetHistoricalContextByIdHandler.cs @@ -0,0 +1,46 @@ +using AutoMapper; +using FluentResults; +using MediatR; +using Streetcode.BLL.DTO.Timeline; +using Streetcode.BLL.Interfaces.Logging; +using Streetcode.DAL.Repositories.Interfaces.Base; + +namespace Streetcode.BLL.MediatR.Timeline.HistoricalContext.GetById +{ + public class GetHistoricalContextByIdHandler : IRequestHandler> + { + private readonly IMapper _mapper; + private readonly IRepositoryWrapper _repository; + private readonly ILoggerService _loggerService; + + public GetHistoricalContextByIdHandler(IMapper mapper, IRepositoryWrapper repository, ILoggerService loggerService) + { + _mapper = mapper; + _repository = repository; + _loggerService = loggerService; + } + + public async Task> Handle(GetHistoricalContextByIdQuery request, CancellationToken cancellationToken) + { + var context = await _repository.HistoricalContextRepository.GetFirstOrDefaultAsync(j => j.Id == request.contextId); + + if (context is null) + { + string exceptionMessege = $"No context found by entered Id - {request.contextId}"; + _loggerService.LogError(request, exceptionMessege); + return Result.Fail(exceptionMessege); + } + + try + { + var contextDto = _mapper.Map(context); + return Result.Ok(contextDto); + } + catch (Exception ex) + { + _loggerService.LogError(request, ex.Message); + return Result.Fail(ex.Message); + } + } + } +} \ No newline at end of file diff --git a/Streetcode/Streetcode.BLL/MediatR/Timeline/HistoricalContext/GetById/GetHistoricalContextByIdQuery.cs b/Streetcode/Streetcode.BLL/MediatR/Timeline/HistoricalContext/GetById/GetHistoricalContextByIdQuery.cs new file mode 100644 index 000000000..73410bc96 --- /dev/null +++ b/Streetcode/Streetcode.BLL/MediatR/Timeline/HistoricalContext/GetById/GetHistoricalContextByIdQuery.cs @@ -0,0 +1,8 @@ +using FluentResults; +using MediatR; +using Streetcode.BLL.DTO.Timeline; + +namespace Streetcode.BLL.MediatR.Timeline.HistoricalContext.GetById; + +public record GetHistoricalContextByIdQuery(int contextId) + : IRequest>; \ No newline at end of file diff --git a/Streetcode/Streetcode.BLL/Streetcode.BLL.csproj b/Streetcode/Streetcode.BLL/Streetcode.BLL.csproj index 783023d51..216cb3fb6 100644 --- a/Streetcode/Streetcode.BLL/Streetcode.BLL.csproj +++ b/Streetcode/Streetcode.BLL/Streetcode.BLL.csproj @@ -42,6 +42,7 @@ + diff --git a/Streetcode/Streetcode.WebApi/Controllers/Timeline/HistoricalContextController.cs b/Streetcode/Streetcode.WebApi/Controllers/Timeline/HistoricalContextController.cs index 20489c2c0..236ba3ecd 100644 --- a/Streetcode/Streetcode.WebApi/Controllers/Timeline/HistoricalContextController.cs +++ b/Streetcode/Streetcode.WebApi/Controllers/Timeline/HistoricalContextController.cs @@ -2,6 +2,7 @@ using Microsoft.AspNetCore.Mvc; using Streetcode.BLL.DTO.Timeline; using Streetcode.BLL.MediatR.Timeline.HistoricalContext.GetAll; +using Streetcode.BLL.MediatR.Timeline.HistoricalContext.GetById; using Streetcode.BLL.MediatR.Timeline.HistoricalContext.Update; using Streetcode.DAL.Enums; @@ -15,6 +16,12 @@ public async Task GetAll() return HandleResult(await Mediator.Send(new GetAllHistoricalContextQuery())); } + [HttpGet("{id:int}")] + public async Task GetById(int id) + { + return HandleResult(await Mediator.Send(new GetHistoricalContextByIdQuery(id))); + } + [HttpPut] [Authorize(Roles = nameof(UserRole.Admin))] [ProducesResponseType(StatusCodes.Status401Unauthorized)] From 222e2d77d84dadbbfe260c32d9e8b8325df8a773 Mon Sep 17 00:00:00 2001 From: Dmytro Date: Mon, 1 Apr 2024 15:35:02 +0300 Subject: [PATCH 03/25] add: delete endpoint for historicalContext, todo: create --- .../Delete/DeleteHistoricalContextCommand.cs | 9 ++++ .../Delete/DeleteHistoricalContextHandler.cs | 43 +++++++++++++++++++ .../Streetcode.BLL/Streetcode.BLL.csproj | 1 - .../Timeline/HistoricalContextController.cs | 10 +++++ 4 files changed, 62 insertions(+), 1 deletion(-) create mode 100644 Streetcode/Streetcode.BLL/MediatR/Timeline/HistoricalContext/Delete/DeleteHistoricalContextCommand.cs create mode 100644 Streetcode/Streetcode.BLL/MediatR/Timeline/HistoricalContext/Delete/DeleteHistoricalContextHandler.cs diff --git a/Streetcode/Streetcode.BLL/MediatR/Timeline/HistoricalContext/Delete/DeleteHistoricalContextCommand.cs b/Streetcode/Streetcode.BLL/MediatR/Timeline/HistoricalContext/Delete/DeleteHistoricalContextCommand.cs new file mode 100644 index 000000000..c931173c9 --- /dev/null +++ b/Streetcode/Streetcode.BLL/MediatR/Timeline/HistoricalContext/Delete/DeleteHistoricalContextCommand.cs @@ -0,0 +1,9 @@ +using FluentResults; +using MediatR; +using Streetcode.BLL.DTO.Timeline; + +namespace Streetcode.BLL.MediatR.Timeline.HistoricalContext.Delete +{ + public record DeleteHistoricalContextCommand(int contextId) + : IRequest>; +} \ No newline at end of file diff --git a/Streetcode/Streetcode.BLL/MediatR/Timeline/HistoricalContext/Delete/DeleteHistoricalContextHandler.cs b/Streetcode/Streetcode.BLL/MediatR/Timeline/HistoricalContext/Delete/DeleteHistoricalContextHandler.cs new file mode 100644 index 000000000..221b8d6b7 --- /dev/null +++ b/Streetcode/Streetcode.BLL/MediatR/Timeline/HistoricalContext/Delete/DeleteHistoricalContextHandler.cs @@ -0,0 +1,43 @@ +using FluentResults; +using MediatR; +using Streetcode.BLL.Interfaces.Logging; +using Streetcode.DAL.Repositories.Interfaces.Base; + +namespace Streetcode.BLL.MediatR.Timeline.HistoricalContext.Delete +{ + public class DeleteHistoricalContextHandler : IRequestHandler> + { + private readonly IRepositoryWrapper _repositoryWrapper; + private readonly ILoggerService _logger; + + public DeleteHistoricalContextHandler(IRepositoryWrapper repository, ILoggerService logger) + { + _repositoryWrapper = repository; + _logger = logger; + } + + public async Task> Handle(DeleteHistoricalContextCommand request, CancellationToken cancellationToken) + { + var contextToDelete = + await _repositoryWrapper.HistoricalContextRepository.GetFirstOrDefaultAsync(x => x.Id == request.contextId); + if (contextToDelete is null) + { + string exMessage = $"No context found by entered Id - {request.contextId}"; + _logger.LogError(request, exMessage); + return Result.Fail(exMessage); + } + + try + { + _repositoryWrapper.HistoricalContextRepository.Delete(contextToDelete); + await _repositoryWrapper.SaveChangesAsync(); + return Result.Ok(request.contextId); + } + catch(Exception ex) + { + _logger.LogError(request, ex.Message); + return Result.Fail(ex.Message); + } + } + } +} \ No newline at end of file diff --git a/Streetcode/Streetcode.BLL/Streetcode.BLL.csproj b/Streetcode/Streetcode.BLL/Streetcode.BLL.csproj index 216cb3fb6..783023d51 100644 --- a/Streetcode/Streetcode.BLL/Streetcode.BLL.csproj +++ b/Streetcode/Streetcode.BLL/Streetcode.BLL.csproj @@ -42,7 +42,6 @@ - diff --git a/Streetcode/Streetcode.WebApi/Controllers/Timeline/HistoricalContextController.cs b/Streetcode/Streetcode.WebApi/Controllers/Timeline/HistoricalContextController.cs index 236ba3ecd..f96a69a68 100644 --- a/Streetcode/Streetcode.WebApi/Controllers/Timeline/HistoricalContextController.cs +++ b/Streetcode/Streetcode.WebApi/Controllers/Timeline/HistoricalContextController.cs @@ -1,6 +1,7 @@ using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Streetcode.BLL.DTO.Timeline; +using Streetcode.BLL.MediatR.Timeline.HistoricalContext.Delete; using Streetcode.BLL.MediatR.Timeline.HistoricalContext.GetAll; using Streetcode.BLL.MediatR.Timeline.HistoricalContext.GetById; using Streetcode.BLL.MediatR.Timeline.HistoricalContext.Update; @@ -30,5 +31,14 @@ public async Task Update([FromBody]HistoricalContextDTO contextDt { return HandleResult(await Mediator.Send(new UpdateHistoricalContextCommand(contextDto))); } + + [HttpDelete("{id:int}")] + [Authorize(Roles = nameof(UserRole.Admin))] + [ProducesResponseType(StatusCodes.Status401Unauthorized)] + [ProducesResponseType(StatusCodes.Status403Forbidden)] + public async Task Delete(int id) + { + return HandleResult(await Mediator.Send(new DeleteHistoricalContextCommand(id))); + } } } From 158c2372934bd62275506f4636c150701fe40c1f Mon Sep 17 00:00:00 2001 From: Dmytro Date: Mon, 1 Apr 2024 16:08:10 +0300 Subject: [PATCH 04/25] add: create for historicaContext + validation for unique context. --- .../Create/CreateHistoricalContextCommand.cs | 9 ++++ .../Create/CreateHistoricalContextHandler.cs | 49 +++++++++++++++++++ .../Delete/DeleteHistoricalContextCommand.cs | 1 - .../GetAll/GetAllHistoricalContextHandler.cs | 1 - .../Update/UpdateHistoricalContextHandler.cs | 1 - .../Timeline/HistoricalContextController.cs | 10 ++++ 6 files changed, 68 insertions(+), 3 deletions(-) create mode 100644 Streetcode/Streetcode.BLL/MediatR/Timeline/HistoricalContext/Create/CreateHistoricalContextCommand.cs create mode 100644 Streetcode/Streetcode.BLL/MediatR/Timeline/HistoricalContext/Create/CreateHistoricalContextHandler.cs diff --git a/Streetcode/Streetcode.BLL/MediatR/Timeline/HistoricalContext/Create/CreateHistoricalContextCommand.cs b/Streetcode/Streetcode.BLL/MediatR/Timeline/HistoricalContext/Create/CreateHistoricalContextCommand.cs new file mode 100644 index 000000000..543ea31ff --- /dev/null +++ b/Streetcode/Streetcode.BLL/MediatR/Timeline/HistoricalContext/Create/CreateHistoricalContextCommand.cs @@ -0,0 +1,9 @@ +using FluentResults; +using MediatR; +using Streetcode.BLL.DTO.Timeline; + +namespace Streetcode.BLL.MediatR.Timeline.HistoricalContext.Create +{ + public record CreateHistoricalContextCommand(HistoricalContextDTO context) + : IRequest>; +} \ No newline at end of file diff --git a/Streetcode/Streetcode.BLL/MediatR/Timeline/HistoricalContext/Create/CreateHistoricalContextHandler.cs b/Streetcode/Streetcode.BLL/MediatR/Timeline/HistoricalContext/Create/CreateHistoricalContextHandler.cs new file mode 100644 index 000000000..46877b030 --- /dev/null +++ b/Streetcode/Streetcode.BLL/MediatR/Timeline/HistoricalContext/Create/CreateHistoricalContextHandler.cs @@ -0,0 +1,49 @@ +using AutoMapper; +using FluentResults; +using MediatR; +using Streetcode.BLL.DTO.Timeline; +using Streetcode.BLL.Interfaces.Logging; +using Streetcode.DAL.Repositories.Interfaces.Base; + +namespace Streetcode.BLL.MediatR.Timeline.HistoricalContext.Create +{ + public class CreateHistoricalContextHandler : IRequestHandler> + { + private readonly IMapper _mapper; + private readonly IRepositoryWrapper _repositoryWrapper; + private readonly ILoggerService _logger; + + public CreateHistoricalContextHandler(IMapper mapper, IRepositoryWrapper repositoryWrapper, ILoggerService logger) + { + _mapper = mapper; + _repositoryWrapper = repositoryWrapper; + _logger = logger; + } + + public async Task> Handle(CreateHistoricalContextCommand request, CancellationToken cancellationToken) + { + try + { + /* read comment at Streetcode.BLL.MediatR.Timeline.HistoricalContext.Update line 29 */ + var context = _mapper.Map(request.context); + var checkIfContextExists = await _repositoryWrapper.HistoricalContextRepository.GetFirstOrDefaultAsync(j => j.Title == request.context.Title); + + if (checkIfContextExists is not null) + { + string exceptionMessege = $"Context with title '{request.context.Title}' is already exists."; + _logger.LogError(request, exceptionMessege); + return Result.Fail(exceptionMessege); + } + + var createdContext = await _repositoryWrapper.HistoricalContextRepository.CreateAsync(context); + await _repositoryWrapper.SaveChangesAsync(); + return Result.Ok(_mapper.Map(createdContext)); + } + catch (Exception ex) + { + _logger.LogError(request, ex.Message); + return Result.Fail(ex.Message); + } + } + } +} \ No newline at end of file diff --git a/Streetcode/Streetcode.BLL/MediatR/Timeline/HistoricalContext/Delete/DeleteHistoricalContextCommand.cs b/Streetcode/Streetcode.BLL/MediatR/Timeline/HistoricalContext/Delete/DeleteHistoricalContextCommand.cs index c931173c9..89a1dacc9 100644 --- a/Streetcode/Streetcode.BLL/MediatR/Timeline/HistoricalContext/Delete/DeleteHistoricalContextCommand.cs +++ b/Streetcode/Streetcode.BLL/MediatR/Timeline/HistoricalContext/Delete/DeleteHistoricalContextCommand.cs @@ -1,6 +1,5 @@ using FluentResults; using MediatR; -using Streetcode.BLL.DTO.Timeline; namespace Streetcode.BLL.MediatR.Timeline.HistoricalContext.Delete { diff --git a/Streetcode/Streetcode.BLL/MediatR/Timeline/HistoricalContext/GetAll/GetAllHistoricalContextHandler.cs b/Streetcode/Streetcode.BLL/MediatR/Timeline/HistoricalContext/GetAll/GetAllHistoricalContextHandler.cs index 666849bfc..beb585baf 100644 --- a/Streetcode/Streetcode.BLL/MediatR/Timeline/HistoricalContext/GetAll/GetAllHistoricalContextHandler.cs +++ b/Streetcode/Streetcode.BLL/MediatR/Timeline/HistoricalContext/GetAll/GetAllHistoricalContextHandler.cs @@ -1,7 +1,6 @@ using AutoMapper; using FluentResults; using MediatR; -using Streetcode.BLL.DTO.AdditionalContent.Subtitles; using Microsoft.Extensions.Localization; using Streetcode.BLL.DTO.Timeline; using Streetcode.BLL.Interfaces.Logging; diff --git a/Streetcode/Streetcode.BLL/MediatR/Timeline/HistoricalContext/Update/UpdateHistoricalContextHandler.cs b/Streetcode/Streetcode.BLL/MediatR/Timeline/HistoricalContext/Update/UpdateHistoricalContextHandler.cs index af0d110cc..a3402d5a5 100644 --- a/Streetcode/Streetcode.BLL/MediatR/Timeline/HistoricalContext/Update/UpdateHistoricalContextHandler.cs +++ b/Streetcode/Streetcode.BLL/MediatR/Timeline/HistoricalContext/Update/UpdateHistoricalContextHandler.cs @@ -3,7 +3,6 @@ using MediatR; using Streetcode.BLL.DTO.Timeline; using Streetcode.BLL.Interfaces.Logging; -using Streetcode.DAL.Entities.Timeline; using Streetcode.DAL.Repositories.Interfaces.Base; namespace Streetcode.BLL.MediatR.Timeline.HistoricalContext.Update diff --git a/Streetcode/Streetcode.WebApi/Controllers/Timeline/HistoricalContextController.cs b/Streetcode/Streetcode.WebApi/Controllers/Timeline/HistoricalContextController.cs index f96a69a68..48bad0436 100644 --- a/Streetcode/Streetcode.WebApi/Controllers/Timeline/HistoricalContextController.cs +++ b/Streetcode/Streetcode.WebApi/Controllers/Timeline/HistoricalContextController.cs @@ -1,6 +1,7 @@ using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Streetcode.BLL.DTO.Timeline; +using Streetcode.BLL.MediatR.Timeline.HistoricalContext.Create; using Streetcode.BLL.MediatR.Timeline.HistoricalContext.Delete; using Streetcode.BLL.MediatR.Timeline.HistoricalContext.GetAll; using Streetcode.BLL.MediatR.Timeline.HistoricalContext.GetById; @@ -40,5 +41,14 @@ public async Task Delete(int id) { return HandleResult(await Mediator.Send(new DeleteHistoricalContextCommand(id))); } + + [HttpPost] + [Authorize(Roles = nameof(UserRole.Admin))] + [ProducesResponseType(StatusCodes.Status401Unauthorized)] + [ProducesResponseType(StatusCodes.Status403Forbidden)] + public async Task Create([FromBody]HistoricalContextDTO contextDto) + { + return HandleResult(await Mediator.Send(new CreateHistoricalContextCommand(contextDto))); + } } } From 6fe64ecf8a231de0f9b1bfb3a47305eddd2f8e24 Mon Sep 17 00:00:00 2001 From: VladyslavPavlysko Date: Sun, 14 Apr 2024 18:41:03 +0300 Subject: [PATCH 05/25] Update Delete tag --- .../DTO/AdditionalContent/Tag/UpdateTagDTO.cs | 9 ++++ .../Mapping/AdditionalContent/TagProfile.cs | 1 + .../Tag/Delete/DeleteTagCommand.cs | 8 ++++ .../Tag/Delete/DeleteTagHandler.cs | 43 +++++++++++++++++ .../Tag/Update/UpdateTagCommand.cs | 10 ++++ .../Tag/Update/UpdateTagHandler.cs | 48 +++++++++++++++++++ .../AdditionalContent/TagController.cs | 20 ++++++++ 7 files changed, 139 insertions(+) create mode 100644 Streetcode/Streetcode.BLL/DTO/AdditionalContent/Tag/UpdateTagDTO.cs create mode 100644 Streetcode/Streetcode.BLL/MediatR/AdditionalContent/Tag/Delete/DeleteTagCommand.cs create mode 100644 Streetcode/Streetcode.BLL/MediatR/AdditionalContent/Tag/Delete/DeleteTagHandler.cs create mode 100644 Streetcode/Streetcode.BLL/MediatR/AdditionalContent/Tag/Update/UpdateTagCommand.cs create mode 100644 Streetcode/Streetcode.BLL/MediatR/AdditionalContent/Tag/Update/UpdateTagHandler.cs diff --git a/Streetcode/Streetcode.BLL/DTO/AdditionalContent/Tag/UpdateTagDTO.cs b/Streetcode/Streetcode.BLL/DTO/AdditionalContent/Tag/UpdateTagDTO.cs new file mode 100644 index 000000000..1a4816c69 --- /dev/null +++ b/Streetcode/Streetcode.BLL/DTO/AdditionalContent/Tag/UpdateTagDTO.cs @@ -0,0 +1,9 @@ +namespace Streetcode.BLL.DTO.AdditionalContent.Tag +{ + public class UpdateTagDTO + { + public int Id { get; set; } + + public string Title { get; set; } + } +} diff --git a/Streetcode/Streetcode.BLL/Mapping/AdditionalContent/TagProfile.cs b/Streetcode/Streetcode.BLL/Mapping/AdditionalContent/TagProfile.cs index b5e79aec4..f86bfcb88 100644 --- a/Streetcode/Streetcode.BLL/Mapping/AdditionalContent/TagProfile.cs +++ b/Streetcode/Streetcode.BLL/Mapping/AdditionalContent/TagProfile.cs @@ -10,6 +10,7 @@ public class TagProfile : Profile public TagProfile() { CreateMap().ForMember(x => x.Streetcodes, conf => conf.Ignore()); + CreateMap().ReverseMap(); CreateMap().ReverseMap(); CreateMap() .ForMember(x => x.Id, conf => conf.MapFrom(ti => ti.TagId)) diff --git a/Streetcode/Streetcode.BLL/MediatR/AdditionalContent/Tag/Delete/DeleteTagCommand.cs b/Streetcode/Streetcode.BLL/MediatR/AdditionalContent/Tag/Delete/DeleteTagCommand.cs new file mode 100644 index 000000000..fc12021ee --- /dev/null +++ b/Streetcode/Streetcode.BLL/MediatR/AdditionalContent/Tag/Delete/DeleteTagCommand.cs @@ -0,0 +1,8 @@ +using FluentResults; +using MediatR; + +namespace Streetcode.BLL.MediatR.AdditionalContent.Tag.Delete +{ + public record DeleteTagCommand(int id) + : IRequest>; +} diff --git a/Streetcode/Streetcode.BLL/MediatR/AdditionalContent/Tag/Delete/DeleteTagHandler.cs b/Streetcode/Streetcode.BLL/MediatR/AdditionalContent/Tag/Delete/DeleteTagHandler.cs new file mode 100644 index 000000000..2c9ce1c43 --- /dev/null +++ b/Streetcode/Streetcode.BLL/MediatR/AdditionalContent/Tag/Delete/DeleteTagHandler.cs @@ -0,0 +1,43 @@ +using FluentResults; +using MediatR; +using Streetcode.BLL.Interfaces.Logging; +using Streetcode.DAL.Repositories.Interfaces.Base; + +namespace Streetcode.BLL.MediatR.AdditionalContent.Tag.Delete +{ + public class DeleteTagHandler : IRequestHandler> + { + private readonly IRepositoryWrapper _repositoryWrapper; + private readonly ILoggerService _logger; + + public DeleteTagHandler(IRepositoryWrapper repository, ILoggerService logger) + { + _repositoryWrapper = repository; + _logger = logger; + } + + public async Task> Handle(DeleteTagCommand request, CancellationToken cancellationToken) + { + var tagToDelete = + await _repositoryWrapper.TagRepository.GetFirstOrDefaultAsync(x => x.Id == request.id); + if (tagToDelete is null) + { + string exMessage = $"No tag found by entered Id - {request.id}"; + _logger.LogError(request, exMessage); + return Result.Fail(exMessage); + } + + try + { + _repositoryWrapper.TagRepository.Delete(tagToDelete); + await _repositoryWrapper.SaveChangesAsync(); + return Result.Ok(request.id); + } + catch (Exception ex) + { + _logger.LogError(request, ex.Message); + return Result.Fail(ex.Message); + } + } + } +} diff --git a/Streetcode/Streetcode.BLL/MediatR/AdditionalContent/Tag/Update/UpdateTagCommand.cs b/Streetcode/Streetcode.BLL/MediatR/AdditionalContent/Tag/Update/UpdateTagCommand.cs new file mode 100644 index 000000000..1cd09e065 --- /dev/null +++ b/Streetcode/Streetcode.BLL/MediatR/AdditionalContent/Tag/Update/UpdateTagCommand.cs @@ -0,0 +1,10 @@ +using FluentResults; +using MediatR; +using Streetcode.BLL.DTO.AdditionalContent; +using Streetcode.BLL.DTO.AdditionalContent.Tag; + +namespace Streetcode.BLL.MediatR.AdditionalContent.Tag.Update +{ + public record UpdateTagCommand(UpdateTagDTO tag) + : IRequest>; +} diff --git a/Streetcode/Streetcode.BLL/MediatR/AdditionalContent/Tag/Update/UpdateTagHandler.cs b/Streetcode/Streetcode.BLL/MediatR/AdditionalContent/Tag/Update/UpdateTagHandler.cs new file mode 100644 index 000000000..d34209647 --- /dev/null +++ b/Streetcode/Streetcode.BLL/MediatR/AdditionalContent/Tag/Update/UpdateTagHandler.cs @@ -0,0 +1,48 @@ +using AutoMapper; +using FluentResults; +using MediatR; +using Streetcode.BLL.DTO.AdditionalContent; +using Streetcode.BLL.Interfaces.Logging; +using Streetcode.DAL.Repositories.Interfaces.Base; +using TagEntity = Streetcode.DAL.Entities.AdditionalContent.Tag; + +namespace Streetcode.BLL.MediatR.AdditionalContent.Tag.Update +{ + public class UpdateTagHandler : IRequestHandler> + { + private readonly IRepositoryWrapper _repositoryWrapper; + private readonly IMapper _mapper; + private readonly ILoggerService _logger; + public UpdateTagHandler(IRepositoryWrapper repository, IMapper mapper, ILoggerService logger) + { + _repositoryWrapper = repository; + _mapper = mapper; + _logger = logger; + } + + public async Task> Handle(UpdateTagCommand request, CancellationToken cancellationToken) + { + var existedTag = + await _repositoryWrapper.TagRepository.GetFirstOrDefaultAsync(x => x.Id == request.tag.Id); + if (existedTag is null) + { + string exMessage = $"No tag found by entered Id - {request.tag.Id}"; + _logger.LogError(request, exMessage); + return Result.Fail(exMessage); + } + + try + { + var tagToUpdate = _mapper.Map(request.tag); + _repositoryWrapper.TagRepository.Update(tagToUpdate); + await _repositoryWrapper.SaveChangesAsync(); + return Result.Ok(_mapper.Map(tagToUpdate)); + } + catch(Exception ex) + { + _logger.LogError(request, ex.Message); + return Result.Fail(ex.Message); + } + } + } +} diff --git a/Streetcode/Streetcode.WebApi/Controllers/AdditionalContent/TagController.cs b/Streetcode/Streetcode.WebApi/Controllers/AdditionalContent/TagController.cs index a89baa1d3..ba3acb1c7 100644 --- a/Streetcode/Streetcode.WebApi/Controllers/AdditionalContent/TagController.cs +++ b/Streetcode/Streetcode.WebApi/Controllers/AdditionalContent/TagController.cs @@ -3,9 +3,11 @@ using Streetcode.BLL.DTO.AdditionalContent; using Streetcode.BLL.DTO.AdditionalContent.Tag; using Streetcode.BLL.MediatR.AdditionalContent.Tag.Create; +using Streetcode.BLL.MediatR.AdditionalContent.Tag.Delete; using Streetcode.BLL.MediatR.AdditionalContent.Tag.GetAll; using Streetcode.BLL.MediatR.AdditionalContent.Tag.GetById; using Streetcode.BLL.MediatR.AdditionalContent.Tag.GetByStreetcodeId; +using Streetcode.BLL.MediatR.AdditionalContent.Tag.Update; using Streetcode.DAL.Enums; namespace Streetcode.WebApi.Controllers.AdditionalContent; @@ -44,4 +46,22 @@ public async Task Create([FromBody] CreateTagDTO tagTitle) { return HandleResult(await Mediator.Send(new CreateTagQuery(tagTitle))); } + + [HttpDelete("{id:int}")] + [Authorize(Roles = nameof(UserRole.Admin))] + [ProducesResponseType(StatusCodes.Status401Unauthorized)] + [ProducesResponseType(StatusCodes.Status403Forbidden)] + public async Task Delete(int id) + { + return HandleResult(await Mediator.Send(new DeleteTagCommand(id))); + } + + [HttpPut] + [Authorize(Roles = nameof(UserRole.Admin))] + [ProducesResponseType(StatusCodes.Status401Unauthorized)] + [ProducesResponseType(StatusCodes.Status403Forbidden)] + public async Task Update([FromBody] UpdateTagDTO tagDto) + { + return HandleResult(await Mediator.Send(new UpdateTagCommand(tagDto))); + } } From 9b838d7147f9c0c964d7768973ed6ff49479e076 Mon Sep 17 00:00:00 2001 From: VladyslavPavlysko Date: Wed, 17 Apr 2024 18:04:42 +0300 Subject: [PATCH 06/25] sort tags --- .../MediatR/AdditionalContent/Tag/GetAll/GetAllTagsHandler.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Streetcode/Streetcode.BLL/MediatR/AdditionalContent/Tag/GetAll/GetAllTagsHandler.cs b/Streetcode/Streetcode.BLL/MediatR/AdditionalContent/Tag/GetAll/GetAllTagsHandler.cs index 79757e25a..caa07cd2f 100644 --- a/Streetcode/Streetcode.BLL/MediatR/AdditionalContent/Tag/GetAll/GetAllTagsHandler.cs +++ b/Streetcode/Streetcode.BLL/MediatR/AdditionalContent/Tag/GetAll/GetAllTagsHandler.cs @@ -29,7 +29,7 @@ public GetAllTagsHandler(IRepositoryWrapper repositoryWrapper, IMapper mapper, I public async Task>> Handle(GetAllTagsQuery request, CancellationToken cancellationToken) { var tags = await _repositoryWrapper.TagRepository.GetAllAsync(); - + var sorted_tags = tags.OrderByDescending(tag => tag.Title); if (tags is null) { string errorMsg = _stringLocalizerCannotFind?["CannotFindAnyTags"].Value; @@ -37,6 +37,6 @@ public async Task>> Handle(GetAllTagsQuery request, C return Result.Fail(new Error(errorMsg)); } - return Result.Ok(_mapper.Map>(tags)); + return Result.Ok(_mapper.Map>(sorted_tags)); } } From 561abe64e8734ca707c68a2cf5265919d1ede72b Mon Sep 17 00:00:00 2001 From: VladyslavPavlysko Date: Wed, 17 Apr 2024 18:25:02 +0300 Subject: [PATCH 07/25] change sort order --- .../MediatR/AdditionalContent/Tag/GetAll/GetAllTagsHandler.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Streetcode/Streetcode.BLL/MediatR/AdditionalContent/Tag/GetAll/GetAllTagsHandler.cs b/Streetcode/Streetcode.BLL/MediatR/AdditionalContent/Tag/GetAll/GetAllTagsHandler.cs index caa07cd2f..04b0c95a0 100644 --- a/Streetcode/Streetcode.BLL/MediatR/AdditionalContent/Tag/GetAll/GetAllTagsHandler.cs +++ b/Streetcode/Streetcode.BLL/MediatR/AdditionalContent/Tag/GetAll/GetAllTagsHandler.cs @@ -29,7 +29,7 @@ public GetAllTagsHandler(IRepositoryWrapper repositoryWrapper, IMapper mapper, I public async Task>> Handle(GetAllTagsQuery request, CancellationToken cancellationToken) { var tags = await _repositoryWrapper.TagRepository.GetAllAsync(); - var sorted_tags = tags.OrderByDescending(tag => tag.Title); + var sorted_tags = tags.OrderBy(tag => tag.Title); if (tags is null) { string errorMsg = _stringLocalizerCannotFind?["CannotFindAnyTags"].Value; From c3042f338ad41e870523de8abf8c6be6c9f9c201 Mon Sep 17 00:00:00 2001 From: Dmytro Date: Mon, 22 Apr 2024 15:55:41 +0300 Subject: [PATCH 08/25] add: validation for unique update --- .../Update/UpdateHistoricalContextHandler.cs | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/Streetcode/Streetcode.BLL/MediatR/Timeline/HistoricalContext/Update/UpdateHistoricalContextHandler.cs b/Streetcode/Streetcode.BLL/MediatR/Timeline/HistoricalContext/Update/UpdateHistoricalContextHandler.cs index a3402d5a5..2cf7f13bb 100644 --- a/Streetcode/Streetcode.BLL/MediatR/Timeline/HistoricalContext/Update/UpdateHistoricalContextHandler.cs +++ b/Streetcode/Streetcode.BLL/MediatR/Timeline/HistoricalContext/Update/UpdateHistoricalContextHandler.cs @@ -25,8 +25,6 @@ public async Task> Handle( UpdateHistoricalContextCommand request, CancellationToken cancellationToken) { - /* have some shitty code right here, if you delete the DAL.Entities.Timeline. part it will show error - even if you have using Streetcode.DAL.Entities.Timeline; so sad :( */ var historicalContext = await _repositoryWrapper.HistoricalContextRepository.GetFirstOrDefaultAsync(x => x.Id == request.HistoricalContext.Id); @@ -37,8 +35,21 @@ await _repositoryWrapper.HistoricalContextRepository.GetFirstOrDefaultAsync(x => return Result.Fail(exMessage); } + var historicalContextRepeat = await _repositoryWrapper.HistoricalContextRepository.GetFirstOrDefaultAsync( + x => + x.Title == request.HistoricalContext.Title); + + if (historicalContextRepeat is not null) + { + string exMessage = $"There is already a context with title - {request.HistoricalContext.Title}"; + _logger.LogError(request, exMessage); + return Result.Fail(exMessage); + } + try { + /* have some shitty code right here, if you delete the DAL.Entities.Timeline. part it will show error + even if you have using Streetcode.DAL.Entities.Timeline; so sad :( */ var contextToUpdate = _mapper.Map(request.HistoricalContext); _repositoryWrapper.HistoricalContextRepository.Update(contextToUpdate); await _repositoryWrapper.SaveChangesAsync(); From 8cf70f1e6699a4460b39c877705deb496cebcb7a Mon Sep 17 00:00:00 2001 From: Dmytro Date: Mon, 22 Apr 2024 18:51:56 +0300 Subject: [PATCH 09/25] add: sorting --- .../HistoricalContext/GetAll/GetAllHistoricalContextHandler.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Streetcode/Streetcode.BLL/MediatR/Timeline/HistoricalContext/GetAll/GetAllHistoricalContextHandler.cs b/Streetcode/Streetcode.BLL/MediatR/Timeline/HistoricalContext/GetAll/GetAllHistoricalContextHandler.cs index beb585baf..667a2389f 100644 --- a/Streetcode/Streetcode.BLL/MediatR/Timeline/HistoricalContext/GetAll/GetAllHistoricalContextHandler.cs +++ b/Streetcode/Streetcode.BLL/MediatR/Timeline/HistoricalContext/GetAll/GetAllHistoricalContextHandler.cs @@ -29,6 +29,7 @@ public async Task>> Handle(GetAllHistor var historicalContextItems = await _repositoryWrapper .HistoricalContextRepository .GetAllAsync(); + var historicalContexts = historicalContextItems.OrderBy(context => context.Title); if (historicalContextItems is null) { @@ -37,7 +38,7 @@ public async Task>> Handle(GetAllHistor return Result.Fail(new Error(errorMsg)); } - return Result.Ok(_mapper.Map>(historicalContextItems)); + return Result.Ok(_mapper.Map>(historicalContexts)); } } } From 871ae2dcf271663aa92c4505ffc2fad344a2f160 Mon Sep 17 00:00:00 2001 From: VladyslavPavlysko Date: Tue, 23 Apr 2024 16:11:43 +0300 Subject: [PATCH 10/25] Handler changes --- .../AdditionalContent/Tag/Create/CreateTagHandler.cs | 9 +++++++++ .../AdditionalContent/Tag/GetAll/GetAllTagsHandler.cs | 2 +- .../AdditionalContent/Tag/Update/UpdateTagHandler.cs | 9 +++++++++ 3 files changed, 19 insertions(+), 1 deletion(-) diff --git a/Streetcode/Streetcode.BLL/MediatR/AdditionalContent/Tag/Create/CreateTagHandler.cs b/Streetcode/Streetcode.BLL/MediatR/AdditionalContent/Tag/Create/CreateTagHandler.cs index 0c18d7a36..85ffab6cf 100644 --- a/Streetcode/Streetcode.BLL/MediatR/AdditionalContent/Tag/Create/CreateTagHandler.cs +++ b/Streetcode/Streetcode.BLL/MediatR/AdditionalContent/Tag/Create/CreateTagHandler.cs @@ -22,6 +22,15 @@ public CreateTagHandler(IRepositoryWrapper repositoryWrapper, IMapper mapper, IL public async Task> Handle(CreateTagQuery request, CancellationToken cancellationToken) { + var exists = await _repositoryWrapper.TagRepository.GetFirstOrDefaultAsync(t => request.tag.Title == t.Title); + + if (exists is not null) + { + var errMessage = $"Tag with title {request.tag.Title} already exists"; + _logger.LogError(request, errMessage); + return Result.Fail(errMessage); + } + var newTag = await _repositoryWrapper.TagRepository.CreateAsync(new DAL.Entities.AdditionalContent.Tag() { Title = request.tag.Title diff --git a/Streetcode/Streetcode.BLL/MediatR/AdditionalContent/Tag/GetAll/GetAllTagsHandler.cs b/Streetcode/Streetcode.BLL/MediatR/AdditionalContent/Tag/GetAll/GetAllTagsHandler.cs index 04b0c95a0..17f869aff 100644 --- a/Streetcode/Streetcode.BLL/MediatR/AdditionalContent/Tag/GetAll/GetAllTagsHandler.cs +++ b/Streetcode/Streetcode.BLL/MediatR/AdditionalContent/Tag/GetAll/GetAllTagsHandler.cs @@ -29,7 +29,6 @@ public GetAllTagsHandler(IRepositoryWrapper repositoryWrapper, IMapper mapper, I public async Task>> Handle(GetAllTagsQuery request, CancellationToken cancellationToken) { var tags = await _repositoryWrapper.TagRepository.GetAllAsync(); - var sorted_tags = tags.OrderBy(tag => tag.Title); if (tags is null) { string errorMsg = _stringLocalizerCannotFind?["CannotFindAnyTags"].Value; @@ -37,6 +36,7 @@ public async Task>> Handle(GetAllTagsQuery request, C return Result.Fail(new Error(errorMsg)); } + var sorted_tags = tags.OrderBy(tag => tag.Title); return Result.Ok(_mapper.Map>(sorted_tags)); } } diff --git a/Streetcode/Streetcode.BLL/MediatR/AdditionalContent/Tag/Update/UpdateTagHandler.cs b/Streetcode/Streetcode.BLL/MediatR/AdditionalContent/Tag/Update/UpdateTagHandler.cs index d34209647..24860a368 100644 --- a/Streetcode/Streetcode.BLL/MediatR/AdditionalContent/Tag/Update/UpdateTagHandler.cs +++ b/Streetcode/Streetcode.BLL/MediatR/AdditionalContent/Tag/Update/UpdateTagHandler.cs @@ -31,6 +31,15 @@ public async Task> Handle(UpdateTagCommand request, CancellationT return Result.Fail(exMessage); } + existedTag = await _repositoryWrapper.TagRepository.GetFirstOrDefaultAsync(x => x.Title == request.tag.Title); + + if (existedTag is not null) + { + var errMessage = $"Tag with title {request.tag.Title} already exists"; + _logger.LogError(request, errMessage); + return Result.Fail(errMessage); + } + try { var tagToUpdate = _mapper.Map(request.tag); From bb0b55fd934ba7b71970c9993c8a628e3534a5f8 Mon Sep 17 00:00:00 2001 From: VladyslavPavlysko Date: Tue, 23 Apr 2024 16:12:33 +0300 Subject: [PATCH 11/25] Integration tests for tags --- .../AdditionalContent/TagControllerTests.cs | 623 ++++++++++++++---- .../Tag/ExtractCreateTestTag.cs | 32 + .../Tag/ExtractUpdateTestTag.cs | 33 + .../Utils/Client/Additional/TagClient.cs | 17 + .../AdditionalContent/TagExtracter.cs | 3 +- .../Streetcode.XIntegrationTest.csproj | 1 + 6 files changed, 589 insertions(+), 120 deletions(-) create mode 100644 Streetcode/Streetcode.XIntegrationTest/ControllerTests/Utils/BeforeAndAfterTestAtribute/AdditionalContent/Tag/ExtractCreateTestTag.cs create mode 100644 Streetcode/Streetcode.XIntegrationTest/ControllerTests/Utils/BeforeAndAfterTestAtribute/AdditionalContent/Tag/ExtractUpdateTestTag.cs diff --git a/Streetcode/Streetcode.XIntegrationTest/ControllerTests/AdditionalContent/TagControllerTests.cs b/Streetcode/Streetcode.XIntegrationTest/ControllerTests/AdditionalContent/TagControllerTests.cs index ea50c25b1..de1910188 100644 --- a/Streetcode/Streetcode.XIntegrationTest/ControllerTests/AdditionalContent/TagControllerTests.cs +++ b/Streetcode/Streetcode.XIntegrationTest/ControllerTests/AdditionalContent/TagControllerTests.cs @@ -1,122 +1,507 @@ -using Streetcode.BLL.DTO.AdditionalContent; -using Streetcode.BLL.DTO.AdditionalContent.Tag; -using Streetcode.DAL.Entities.AdditionalContent; -using Streetcode.DAL.Entities.Streetcode; -using Streetcode.DAL.Entities.Streetcode.TextContent; -using Streetcode.XIntegrationTest.Base; -using Streetcode.XIntegrationTest.ControllerTests.BaseController; -using Streetcode.XIntegrationTest.ControllerTests.Utils; -using Streetcode.XIntegrationTest.ControllerTests.Utils.Client.Tag; -using Streetcode.XIntegrationTest.ControllerTests.Utils.Extracter.AdditionalContent; -using Streetcode.XIntegrationTest.ControllerTests.Utils.Extracter.StreetcodeExtracter; -using Xunit; - -namespace Streetcode.XIntegrationTest.ControllerTests.AdditionalContent -{ - public class TagControllerTests : BaseControllerTests, IClassFixture> - { - private Tag _testTag; - private StreetcodeContent _testStreetcodeContent; - - public TagControllerTests(CustomWebApplicationFactory factory) - : base(factory, "/api/Tag") - { - int uniqueId = UniqueNumberGenerator.Generate(); - this._testTag = TagExtracter.Extract(uniqueId); - this._testStreetcodeContent = StreetcodeContentExtracter - .Extract( - uniqueId, - uniqueId, - Guid.NewGuid().ToString()); - } - +using Streetcode.BLL.DTO.AdditionalContent; +using Streetcode.BLL.DTO.AdditionalContent.Tag; +using TagEntity = Streetcode.DAL.Entities.AdditionalContent.Tag; +using Streetcode.DAL.Entities.Streetcode; +using Streetcode.DAL.Entities.Streetcode.TextContent; +using Streetcode.XIntegrationTest.Base; +using Streetcode.XIntegrationTest.ControllerTests.BaseController; +using Streetcode.XIntegrationTest.ControllerTests.Utils; +using Streetcode.XIntegrationTest.ControllerTests.Utils.Client.Tag; +using Streetcode.XIntegrationTest.ControllerTests.Utils.Extracter.AdditionalContent; +using Streetcode.XIntegrationTest.ControllerTests.Utils.Extracter.StreetcodeExtracter; +using Streetcode.XIntegrationTest.ControllerTests.Utils.BeforeAndAfterTestAtribute.AdditionalContent.Tag; +using System.Net; +using Moq; +using Xunit; +using Streetcode.DAL.Repositories.Interfaces.AdditionalContent; +using AutoMapper; +using Microsoft.Extensions.Localization; +using Streetcode.BLL.MediatR.AdditionalContent.Tag.GetAll; +using Streetcode.DAL.Repositories.Interfaces.Base; +using Streetcode.BLL.Interfaces.Logging; +using Streetcode.BLL.SharedResource; +using Streetcode.BLL.MediatR.AdditionalContent.Tag.Create; +using Streetcode.BLL.MediatR.AdditionalContent.Tag.Update; +using Microsoft.EntityFrameworkCore.ChangeTracking; +using System.Linq.Expressions; +using Microsoft.EntityFrameworkCore.Query; +using AutoMapper.Execution; +using Streetcode.BLL.MediatR.AdditionalContent.Tag.Delete; + +namespace Streetcode.XIntegrationTest.ControllerTests.AdditionalContent.Tag +{ + [Collection("Authorization")] + public class TagControllerTests : BaseAuthorizationControllerTests, IClassFixture> + { + private TagEntity _testCreateTag; + private TagEntity _testUpdateTag; + private StreetcodeContent _testStreetcodeContent; + + public TagControllerTests(CustomWebApplicationFactory factory, TokenStorage tokenStorage) + : base(factory, "/api/Tag", tokenStorage) + { + int uniqueId = UniqueNumberGenerator.Generate(); + this._testCreateTag = TagExtracter.Extract(uniqueId, Guid.NewGuid().ToString()); + this._testUpdateTag = TagExtracter.Extract(uniqueId, Guid.NewGuid().ToString()); + this._testStreetcodeContent = StreetcodeContentExtracter + .Extract( + uniqueId, + uniqueId, + Guid.NewGuid().ToString()); + } + public override void Dispose() { StreetcodeContentExtracter.Remove(this._testStreetcodeContent); - TagExtracter.Remove(this._testTag); - } - - [Fact] - public async Task GetAll_ReturnSuccessStatusCode() - { - var response = await this.client.GetAllAsync(); - var returnedValue = CaseIsensitiveJsonDeserializer.Deserialize>(response.Content); - - Assert.True(response.IsSuccessStatusCode); - Assert.NotNull(returnedValue); - } - - [Fact] - public async Task GetById_ReturnSuccessStatusCode() - { - Tag expectedTag = this._testTag; - var response = await this.client.GetByIdAsync(expectedTag.Id); - - var returnedValue = CaseIsensitiveJsonDeserializer.Deserialize(response.Content); - - Assert.True(response.IsSuccessStatusCode); - Assert.NotNull(returnedValue); - Assert.Multiple( - () => Assert.Equal(expectedTag.Id, returnedValue?.Id), - () => Assert.Equal(expectedTag.Title, returnedValue?.Title)); - } - - [Fact] - public async Task GetByIdIncorrect_ReturnBadRequest() - { - int incorrectId = -100; - var response = await this.client.GetByIdAsync(incorrectId); - - Assert.Multiple( - () => Assert.Equal(System.Net.HttpStatusCode.BadRequest, response.StatusCode), - () => Assert.False(response.IsSuccessStatusCode)); - } - - [Fact] - public async Task GetByStreetcodeId_ReturnSuccessStatusCode() - { - TagExtracter.AddStreetcodeTagIndex(this._testStreetcodeContent.Id, this._testTag.Id); - int streetcodeId = this._testStreetcodeContent.Id; - var response = await client.GetByStreetcodeId(streetcodeId); - var returnedValue = CaseIsensitiveJsonDeserializer.Deserialize>(response.Content); - - Assert.True(response.IsSuccessStatusCode); - Assert.NotNull(returnedValue); - } - - [Fact] - public async Task GetByStreetcodeId_Incorrect_ReturnBadRequest() - { - int streetcodeId = -100; - var response = await this.client.GetByStreetcodeId(streetcodeId); - - Assert.Multiple( - () => Assert.Equal(System.Net.HttpStatusCode.BadRequest, response.StatusCode), - () => Assert.False(response.IsSuccessStatusCode)); - } - - [Fact] - public async Task GetByTitle_ReturnSuccessStatusCode() - { - - Tag expectedTag = this._testTag; - var response = await this.client.GetTagByTitle(expectedTag.Title); - var returnedValue = CaseIsensitiveJsonDeserializer.Deserialize(response.Content); - - Assert.True(response.IsSuccessStatusCode); - Assert.NotNull(returnedValue); - Assert.Equal(expectedTag.Title, returnedValue?.Title); - } - - [Fact] - public async Task GetByTitle_Incorrect_ReturnBadRequest() - { - string title = "Some_Incorrect_Title"; - var response = await this.client.GetTagByTitle(title); - - Assert.Multiple( - () => Assert.Equal(System.Net.HttpStatusCode.BadRequest, response.StatusCode), - () => Assert.False(response.IsSuccessStatusCode)); - } - } -} + TagExtracter.Remove(this._testCreateTag); + } + + [Fact] + public async Task GetAll_ReturnSuccessStatusCode() + { + var response = await this.client.GetAllAsync(); + var returnedValue = CaseIsensitiveJsonDeserializer.Deserialize>(response.Content); + + Assert.True(response.IsSuccessStatusCode); + Assert.NotNull(returnedValue); + } + + [Fact] + public async Task GetAll_ReturnBadRequest() + { + var repositoryMock = new Mock(); + repositoryMock.Setup(repo => repo.GetAllAsync(default, default)).ReturnsAsync((IEnumerable)null); + + var repositoryWrapperMock = new Mock(); + repositoryWrapperMock.SetupGet(wrapper => wrapper.TagRepository) + .Returns(repositoryMock.Object); + + var mapperMock = new Mock(); + var stringLocalizerMock = new Mock>(); + stringLocalizerMock.Setup(x => x["CannotFindAnyTags"]).Returns(new LocalizedString("CannotFindAnyTags", "Error message")); + var loggerMock = new Mock(); + + var handler = new GetAllTagsHandler(repositoryWrapperMock.Object, mapperMock.Object, loggerMock.Object, stringLocalizerMock.Object); + + var query = new GetAllTagsQuery(); + var cancellationToken = CancellationToken.None; + + var result = await handler.Handle(query, cancellationToken); + + // Assert + Assert.False(result.IsSuccess); + } + + [Fact] + public async Task GetById_ReturnSuccessStatusCode() + { + TagEntity expectedTag = this._testCreateTag; + var response = await this.client.GetByIdAsync(expectedTag.Id); + + var returnedValue = CaseIsensitiveJsonDeserializer.Deserialize(response.Content); + + Assert.True(response.IsSuccessStatusCode); + Assert.NotNull(returnedValue); + Assert.Multiple( + () => Assert.Equal(expectedTag.Id, returnedValue?.Id), + () => Assert.Equal(expectedTag.Title, returnedValue?.Title)); + } + + [Fact] + public async Task GetByIdIncorrect_ReturnBadRequest() + { + int incorrectId = -100; + var response = await this.client.GetByIdAsync(incorrectId); + + Assert.Multiple( + () => Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode), + () => Assert.False(response.IsSuccessStatusCode)); + } + + [Fact] + public async Task GetByStreetcodeId_ReturnSuccessStatusCode() + { + TagExtracter.AddStreetcodeTagIndex(this._testStreetcodeContent.Id, this._testCreateTag.Id); + int streetcodeId = this._testStreetcodeContent.Id; + var response = await client.GetByStreetcodeId(streetcodeId); + var returnedValue = CaseIsensitiveJsonDeserializer.Deserialize>(response.Content); + + Assert.True(response.IsSuccessStatusCode); + Assert.NotNull(returnedValue); + } + + [Fact] + public async Task GetByStreetcodeId_ReturnBadRequest() + { + TagExtracter.AddStreetcodeTagIndex(this._testStreetcodeContent.Id, this._testCreateTag.Id); + int streetcodeId = -100; + var response = await client.GetByStreetcodeId(streetcodeId); + var returnedValue = CaseIsensitiveJsonDeserializer.Deserialize>(response.Content); + + Assert.Multiple( + () => Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode), + () => Assert.False(response.IsSuccessStatusCode)); + } + + [Fact] + public async Task GetByTagId_Incorrect_ReturnBadRequest() + { + int tagId = -100; + var response = await this.client.GetByIdAsync(tagId); + + Assert.Multiple( + () => Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode), + () => Assert.False(response.IsSuccessStatusCode)); + } + + [Fact] + public async Task GetByTitle_ReturnSuccessStatusCode() + { + + TagEntity expectedTag = this._testCreateTag; + var response = await this.client.GetTagByTitle(expectedTag.Title); + var returnedValue = CaseIsensitiveJsonDeserializer.Deserialize(response.Content); + + Assert.True(response.IsSuccessStatusCode); + Assert.NotNull(returnedValue); + Assert.Equal(expectedTag.Title, returnedValue?.Title); + } + + [Fact] + public async Task GetByTitle_Incorrect_ReturnBadRequest() + { + string title = "Some_Incorrect_Title"; + var response = await this.client.GetTagByTitle(title); + + Assert.Multiple( + () => Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode), + () => Assert.False(response.IsSuccessStatusCode)); + } + + [Fact] + [ExtractCreateTestTag] + public async Task Create_ReturnsSuccessStatusCode() + { + // Arrange + var tagCreateDTO = ExtractCreateTestTag.TagForTest; + + // Act + var response = await client.CreateAsync(tagCreateDTO, _tokenStorage.AdminToken); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact] + [ExtractCreateTestTag] + public async Task Create_ChangesNotSaved_ReturnsBadRequest() + { + + var tagCreateDTO = ExtractCreateTestTag.TagForTest; + + var repositoryMock = new Mock(); + var repositoryWrapperMock = new Mock(); + repositoryMock.Setup(r => r.GetFirstOrDefaultAsync(default, default)).ReturnsAsync((TagEntity)null); + repositoryMock.Setup(r => r.CreateAsync(default)).ReturnsAsync(this._testCreateTag); + repositoryWrapperMock.SetupGet(wrapper => wrapper.TagRepository).Returns(repositoryMock.Object); + repositoryWrapperMock.Setup(wrapper => wrapper.SaveChanges()).Returns(null); + repositoryWrapperMock.Setup(wrapper => wrapper.SaveChanges()).Throws(default(Exception)); + + var mapperMock = new Mock(); + var loggerMock = new Mock(); + + var handler = new CreateTagHandler(repositoryWrapperMock.Object, mapperMock.Object, loggerMock.Object); + + var query = new CreateTagQuery(tagCreateDTO); + var cancellationToken = CancellationToken.None; + + var result = await handler.Handle(query, cancellationToken); + + // Assert + Assert.False(result.IsSuccess); + } + + [Fact] + [ExtractCreateTestTag] + public async Task Create_TokenNotPassed_ReturnsUnauthorized() + { + // Arrange + var tagCreateDTO = ExtractCreateTestTag.TagForTest; + + // Act + var response = await client.CreateAsync(tagCreateDTO); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + } + + [Fact] + [ExtractCreateTestTag] + public async Task Create_NotAdminTokenPassed_ReturnsForbidden() + { + // Arrange + var tagCreateDTO = ExtractCreateTestTag.TagForTest; + + // Act + var response = await client.CreateAsync(tagCreateDTO, _tokenStorage.UserToken); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + } + + + [Fact] + [ExtractCreateTestTag] + public async Task Create_CreatesNewTag() + { + // Arrange + var tagCreateDTO = ExtractCreateTestTag.TagForTest; + + // Act + var response = await client.CreateAsync(tagCreateDTO, _tokenStorage.AdminToken); + var getResponse = await client.GetTagByTitle(tagCreateDTO.Title); + var fetchedStreetcode = CaseIsensitiveJsonDeserializer.Deserialize(getResponse.Content); + + // Assert + Assert.Equal(tagCreateDTO.Title, fetchedStreetcode.Title); + } + + [Fact] + [ExtractCreateTestTag] + public async Task Create_WithInvalidData_ReturnsBadRequest() + { + // Arrange + var tagCreateDTO = ExtractCreateTestTag.TagForTest; + tagCreateDTO.Title = null; // Invalid data + + // Act + var response = await client.CreateAsync(tagCreateDTO, _tokenStorage.AdminToken); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + } + + [Fact] + [ExtractCreateTestTag] + public async Task Create_WithExistingTag_ReturnsConflict() + { + // Arrange + var tagCreateDTO = ExtractCreateTestTag.TagForTest; + tagCreateDTO.Title = _testCreateTag.Title; + + // Act + var response = await client.CreateAsync(tagCreateDTO, _tokenStorage.AdminToken); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + } + + [Fact] + [ExtractUpdateTestTag] + public async Task Update_ReturnSuccessStatusCode() + { + // Arrange + var tagUpdateDTO = ExtractUpdateTestTag.TagForTest; + tagUpdateDTO.Id = this._testCreateTag.Id; + + // Act + var response = await client.UpdateAsync(tagUpdateDTO, _tokenStorage.AdminToken); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact] + [ExtractUpdateTestTag] + public async Task Update_Incorect_ReturnBadRequest() + { + // Arrange + var tagUpdateDTO = ExtractUpdateTestTag.TagForTest; + + // Act + var response = await client.UpdateAsync(tagUpdateDTO, _tokenStorage.AdminToken); + + // Assert + Assert.Multiple( + () => Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode), + () => Assert.False(response.IsSuccessStatusCode)); + } + + [Fact] + [ExtractUpdateTestTag] + public async Task Update_TokenNotPassed_ReturnsUnauthorized() + { + // Arrange + var tagUpdateDTO = ExtractUpdateTestTag.TagForTest; + + // Act + var response = await client.UpdateAsync(tagUpdateDTO); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + } + + [Fact] + [ExtractUpdateTestTag] + public async Task Update_NotAdminTokenPassed_ReturnsForbidden() + { + // Arrange + var tagUpdateDTO = ExtractUpdateTestTag.TagForTest; + + // Act + var response = await client.UpdateAsync(tagUpdateDTO, _tokenStorage.UserToken); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + } + + [Fact] + [ExtractUpdateTestTag] + public async Task Update_WithInvalidData_ReturnsBadRequest() + { + // Arrange + var tagUpdateDTO = ExtractUpdateTestTag.TagForTest; + tagUpdateDTO.Title = null; // Invalid data + + // Act + var response = await client.UpdateAsync(tagUpdateDTO, _tokenStorage.AdminToken); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + } + + [Fact] + [ExtractUpdateTestTag] + public async Task Update_WithExistingTitle_ReturnsBadRequest() + { + // Arrange + var tagUpdateDTO = ExtractUpdateTestTag.TagForTest; + tagUpdateDTO.Id = this._testCreateTag.Id; + tagUpdateDTO.Title = this._testUpdateTag.Title; + + // Act + var response = await client.UpdateAsync(tagUpdateDTO, _tokenStorage.AdminToken); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + } + + [Fact] + [ExtractUpdateTestTag] + public async Task Update_ChangesNotSaved_ReturnsBadRequest() + { + // Arrange + Expression> testExpression = x => x.Id == this._testUpdateTag.Id; + + var tagUpdateDTO = ExtractUpdateTestTag.TagForTest; + tagUpdateDTO.Id = this._testUpdateTag.Id; + + var repositoryMock = new Mock(); + var repositoryWrapperMock = new Mock(); + repositoryMock.Setup(r => r.GetFirstOrDefaultAsync(It.IsAny>>(), default)) + .ReturnsAsync((Expression> expr, IIncludableQueryable include) => + { + var compiledExpr = expr.Compile(); + return compiledExpr(this._testUpdateTag) ? this._testUpdateTag : null; + }); + + repositoryWrapperMock.SetupGet(wrapper => wrapper.TagRepository).Returns(repositoryMock.Object); + repositoryWrapperMock.Setup(wrapper => wrapper.SaveChangesAsync()).ReturnsAsync(null); + repositoryWrapperMock.Setup(wrapper => wrapper.SaveChangesAsync()).Throws(default(Exception)); + + var mapperMock = new Mock(); + mapperMock.Setup(m => m.Map(default)).Returns(this._testUpdateTag); + var loggerMock = new Mock(); + + var handler = new UpdateTagHandler(repositoryWrapperMock.Object, mapperMock.Object, loggerMock.Object); + + var query = new UpdateTagCommand(tagUpdateDTO); + var cancellationToken = CancellationToken.None; + // Act + var result = await handler.Handle(query, cancellationToken); + + // Assert + Assert.False(result.IsSuccess); + } + + [Fact] + public async Task Delete_ReturnsSuccessStatusCode() + { + // Arrange + int id = this._testCreateTag.Id; + + // Act + var response = await this.client.Delete(id, this._tokenStorage.AdminToken); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact] + public async Task Delete_TokenNotPassed_ReturnsUnathorized() + { + // Arrange + int id = this._testCreateTag.Id; + + // Act + var response = await this.client.Delete(id); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + } + + [Fact] + public async Task Delete_NotAdminTokenPassed_ReturnsForbidden() + { + // Arrange + int id = this._testCreateTag.Id; + + // Act + var response = await this.client.Delete(id, this._tokenStorage.UserToken); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + } + + [Fact] + public async Task Delete_WithInvalidData_ReturnsBadRequest() + { + // Arrange + int id = -100; + + // Act + var response = await this.client.Delete(id, this._tokenStorage.AdminToken); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + } + + [Fact] + public async Task Delete_ChangesNotSaved_ReturnsBadRequest() + { + int id = this._testUpdateTag.Id; + + var repositoryMock = new Mock(); + var repositoryWrapperMock = new Mock(); + repositoryMock.Setup(r => r.GetFirstOrDefaultAsync(It.IsAny>>(), default)) + .ReturnsAsync(this._testUpdateTag); + repositoryMock.Setup(r => r.Delete(default)); + + repositoryWrapperMock.SetupGet(wrapper => wrapper.TagRepository).Returns(repositoryMock.Object); + repositoryWrapperMock.Setup(wrapper => wrapper.SaveChangesAsync()).ReturnsAsync(null); + repositoryWrapperMock.Setup(wrapper => wrapper.SaveChangesAsync()).Throws(default(Exception)); + + var loggerMock = new Mock(); + + var handler = new DeleteTagHandler(repositoryWrapperMock.Object, loggerMock.Object); + + var query = new DeleteTagCommand(id); + var cancellationToken = CancellationToken.None; + // Act + var result = await handler.Handle(query, cancellationToken); + + // Assert + Assert.False(result.IsSuccess); + } + } +} diff --git a/Streetcode/Streetcode.XIntegrationTest/ControllerTests/Utils/BeforeAndAfterTestAtribute/AdditionalContent/Tag/ExtractCreateTestTag.cs b/Streetcode/Streetcode.XIntegrationTest/ControllerTests/Utils/BeforeAndAfterTestAtribute/AdditionalContent/Tag/ExtractCreateTestTag.cs new file mode 100644 index 000000000..6fd95240b --- /dev/null +++ b/Streetcode/Streetcode.XIntegrationTest/ControllerTests/Utils/BeforeAndAfterTestAtribute/AdditionalContent/Tag/ExtractCreateTestTag.cs @@ -0,0 +1,32 @@ +using Streetcode.BLL.DTO.AdditionalContent.Tag; +using Streetcode.XIntegrationTest.ControllerTests.BaseController; +using System.Reflection; +using Xunit.Sdk; + +namespace Streetcode.XIntegrationTest.ControllerTests.Utils.BeforeAndAfterTestAtribute.AdditionalContent.Tag +{ + [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] + public class ExtractCreateTestTag : BeforeAfterTestAttribute + { + public static CreateTagDTO TagForTest; + + public override void Before(MethodInfo methodUnderTest) + { + TagForTest = new CreateTagDTO + { + Title = "Test", + }; + } + + public override void After(MethodInfo methodUnderTest) + { + var sqlDbHelper = BaseControllerTests.GetSqlDbHelper(); + var tag = sqlDbHelper.GetExistItem(p => p.Title == TagForTest.Title); + if (tag != null) + { + sqlDbHelper.DeleteItem(tag); + sqlDbHelper.SaveChanges(); + } + } + } +} diff --git a/Streetcode/Streetcode.XIntegrationTest/ControllerTests/Utils/BeforeAndAfterTestAtribute/AdditionalContent/Tag/ExtractUpdateTestTag.cs b/Streetcode/Streetcode.XIntegrationTest/ControllerTests/Utils/BeforeAndAfterTestAtribute/AdditionalContent/Tag/ExtractUpdateTestTag.cs new file mode 100644 index 000000000..92b2ce937 --- /dev/null +++ b/Streetcode/Streetcode.XIntegrationTest/ControllerTests/Utils/BeforeAndAfterTestAtribute/AdditionalContent/Tag/ExtractUpdateTestTag.cs @@ -0,0 +1,33 @@ +using Streetcode.BLL.DTO.AdditionalContent.Tag; +using Streetcode.XIntegrationTest.ControllerTests.BaseController; +using System.Reflection; +using Xunit.Sdk; + +namespace Streetcode.XIntegrationTest.ControllerTests.Utils.BeforeAndAfterTestAtribute.AdditionalContent.Tag +{ + [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] + public class ExtractUpdateTestTag : BeforeAfterTestAttribute + { + public static UpdateTagDTO TagForTest; + + public override void Before(MethodInfo methodUnderTest) + { + TagForTest = new UpdateTagDTO + { + Id = 1, + Title = "New Title Test", + }; + } + + public override void After(MethodInfo methodUnderTest) + { + var sqlDbHelper = BaseControllerTests.GetSqlDbHelper(); + var tag = sqlDbHelper.GetExistItem(p => p.Title == TagForTest.Title); + if (tag != null) + { + sqlDbHelper.DeleteItem(tag); + sqlDbHelper.SaveChanges(); + } + } + } +} diff --git a/Streetcode/Streetcode.XIntegrationTest/ControllerTests/Utils/Client/Additional/TagClient.cs b/Streetcode/Streetcode.XIntegrationTest/ControllerTests/Utils/Client/Additional/TagClient.cs index 0be8b44d2..abc9fe9fc 100644 --- a/Streetcode/Streetcode.XIntegrationTest/ControllerTests/Utils/Client/Additional/TagClient.cs +++ b/Streetcode/Streetcode.XIntegrationTest/ControllerTests/Utils/Client/Additional/TagClient.cs @@ -1,4 +1,5 @@ using RestSharp; +using Streetcode.BLL.DTO.AdditionalContent.Tag; using Streetcode.XIntegrationTest.ControllerTests.Utils.Client.Base; namespace Streetcode.XIntegrationTest.ControllerTests.Utils.Client.Tag @@ -14,5 +15,21 @@ public async Task GetTagByTitle(string title, string authToken = " { return await this.SendQuery($"/GetTagByTitle/{title}", authToken); } + + public async Task UpdateAsync(UpdateTagDTO updateTagDTO, string authToken = "") + { + return await this.SendCommand("/Update", Method.Put, updateTagDTO, authToken); + } + + public async Task CreateAsync(CreateTagDTO createTagDTO, string authToken = "") + { + return await this.SendCommand("/Create", Method.Post, createTagDTO, authToken); + } + + public async Task Delete(int id, string authToken = "") + { + return await this.SendCommand($"/Delete/{id}", Method.Delete, new UpdateTagDTO(), authToken); + } + } } diff --git a/Streetcode/Streetcode.XIntegrationTest/ControllerTests/Utils/Extracter/AdditionalContent/TagExtracter.cs b/Streetcode/Streetcode.XIntegrationTest/ControllerTests/Utils/Extracter/AdditionalContent/TagExtracter.cs index e732927c6..6790603c6 100644 --- a/Streetcode/Streetcode.XIntegrationTest/ControllerTests/Utils/Extracter/AdditionalContent/TagExtracter.cs +++ b/Streetcode/Streetcode.XIntegrationTest/ControllerTests/Utils/Extracter/AdditionalContent/TagExtracter.cs @@ -4,11 +4,12 @@ namespace Streetcode.XIntegrationTest.ControllerTests.Utils.Extracter.Additional { public class TagExtracter { - public static Tag Extract(int tagId) + public static Tag Extract(int tagId, string tagTitle) { Tag testTag = TestDataProvider.GetTestData(); testTag.Id = tagId; + testTag.Title = tagTitle; return BaseExtracter.Extract(testTag, tag => tag.Id == tagId); } diff --git a/Streetcode/Streetcode.XIntegrationTest/Streetcode.XIntegrationTest.csproj b/Streetcode/Streetcode.XIntegrationTest/Streetcode.XIntegrationTest.csproj index f94ef13cd..35831f603 100644 --- a/Streetcode/Streetcode.XIntegrationTest/Streetcode.XIntegrationTest.csproj +++ b/Streetcode/Streetcode.XIntegrationTest/Streetcode.XIntegrationTest.csproj @@ -33,6 +33,7 @@ all runtime; build; native; contentfiles; analyzers; buildtransitive + From f24d0f4c2eaf634a065f883d0ab84fe41778e902 Mon Sep 17 00:00:00 2001 From: VladyslavPavlysko Date: Tue, 23 Apr 2024 23:14:15 +0300 Subject: [PATCH 12/25] Unit tests for tags --- .../TagTests/CreateTagHandlerTests.cs | 18 ------ .../TagTests/DeleteTagHandlerTests.cs | 43 ++++++++++++++ .../GetTagsByStreetcodeIdHandlerTests.cs | 3 - .../TagTests/UpdateTagHandlerTests.cs | 56 +++++++++++++++++++ 4 files changed, 99 insertions(+), 21 deletions(-) create mode 100644 Streetcode/Streetcode.XUnitTest/MediatRTests/AdditionalContent/AdditionalContentTests/TagTests/DeleteTagHandlerTests.cs create mode 100644 Streetcode/Streetcode.XUnitTest/MediatRTests/AdditionalContent/AdditionalContentTests/TagTests/UpdateTagHandlerTests.cs diff --git a/Streetcode/Streetcode.XUnitTest/MediatRTests/AdditionalContent/AdditionalContentTests/TagTests/CreateTagHandlerTests.cs b/Streetcode/Streetcode.XUnitTest/MediatRTests/AdditionalContent/AdditionalContentTests/TagTests/CreateTagHandlerTests.cs index 552e1bbf4..3b2188060 100644 --- a/Streetcode/Streetcode.XUnitTest/MediatRTests/AdditionalContent/AdditionalContentTests/TagTests/CreateTagHandlerTests.cs +++ b/Streetcode/Streetcode.XUnitTest/MediatRTests/AdditionalContent/AdditionalContentTests/TagTests/CreateTagHandlerTests.cs @@ -1,30 +1,12 @@ using AutoMapper; -using AutoMapper.Internal; -using FluentAssertions; -using FluentResults; -using MediatR; -using Microsoft.AspNetCore.Routing; -using Microsoft.EntityFrameworkCore.ChangeTracking; -using Microsoft.EntityFrameworkCore.ChangeTracking.Internal; -using Microsoft.EntityFrameworkCore.Metadata; -using Microsoft.EntityFrameworkCore.Query; using Moq; using Streetcode.BLL.DTO.AdditionalContent; using Streetcode.BLL.DTO.AdditionalContent.Tag; -using Streetcode.BLL.DTO.Streetcode.TextContent; -using Streetcode.BLL.DTO.Transactions; using Streetcode.BLL.Interfaces.Logging; using Streetcode.BLL.MediatR.AdditionalContent.Tag.Create; -using Streetcode.BLL.MediatR.Streetcode.Fact.Create; using Streetcode.DAL.Entities.AdditionalContent; -using Streetcode.DAL.Entities.Streetcode; using Streetcode.DAL.Entities.Streetcode.TextContent; -using Streetcode.DAL.Entities.Transactions; -using Streetcode.DAL.Repositories.Interfaces.AdditionalContent; using Streetcode.DAL.Repositories.Interfaces.Base; -using Streetcode.DAL.Repositories.Realizations.Base; -using System; -using System.Linq.Expressions; using Xunit; namespace Streetcode.XUnitTest.MediatRTests.AdditionalContent.TagTests diff --git a/Streetcode/Streetcode.XUnitTest/MediatRTests/AdditionalContent/AdditionalContentTests/TagTests/DeleteTagHandlerTests.cs b/Streetcode/Streetcode.XUnitTest/MediatRTests/AdditionalContent/AdditionalContentTests/TagTests/DeleteTagHandlerTests.cs new file mode 100644 index 000000000..b02ef6b53 --- /dev/null +++ b/Streetcode/Streetcode.XUnitTest/MediatRTests/AdditionalContent/AdditionalContentTests/TagTests/DeleteTagHandlerTests.cs @@ -0,0 +1,43 @@ +using Moq; +using Streetcode.BLL.Interfaces.Logging; +using Streetcode.BLL.MediatR.AdditionalContent.Tag.Delete; +using Streetcode.DAL.Entities.AdditionalContent; +using Streetcode.DAL.Entities.Streetcode.TextContent; +using Streetcode.DAL.Repositories.Interfaces.Base; +using System.Linq.Expressions; +using Xunit; + +namespace Streetcode.XUnitTest.MediatRTests.AdditionalContent.TagTests +{ + public class DeleteTagHandlerTests + { + private readonly Mock _mockRepo; + private readonly Mock _mockLogger; + public DeleteTagHandlerTests() + { + _mockRepo = new Mock(); + _mockLogger = new Mock(); + } + + [Fact] + public async Task ShouldReturnSuccessfully_IsCorrectAndSuccess() + { + // Arrange + _mockRepo.Setup(repo => repo.TagRepository.Delete(new Tag())); + _mockRepo.Setup(repo => repo.TagRepository.GetFirstOrDefaultAsync(It.IsAny>>(), default)).ReturnsAsync(new Tag()); + + _mockRepo.Setup(repo => repo.SaveChangesAsync()).ReturnsAsync(1); + + + var handler = new DeleteTagHandler(_mockRepo.Object, _mockLogger.Object); + + //Act + var result = await handler.Handle(new DeleteTagCommand(1), CancellationToken.None); + + //Assert + Assert.Multiple( + () => Assert.IsType(result.Value), + () => Assert.True(result.IsSuccess)); + } + } +} diff --git a/Streetcode/Streetcode.XUnitTest/MediatRTests/AdditionalContent/AdditionalContentTests/TagTests/GetTagsByStreetcodeIdHandlerTests.cs b/Streetcode/Streetcode.XUnitTest/MediatRTests/AdditionalContent/AdditionalContentTests/TagTests/GetTagsByStreetcodeIdHandlerTests.cs index dad33ac68..6141e49cb 100644 --- a/Streetcode/Streetcode.XUnitTest/MediatRTests/AdditionalContent/AdditionalContentTests/TagTests/GetTagsByStreetcodeIdHandlerTests.cs +++ b/Streetcode/Streetcode.XUnitTest/MediatRTests/AdditionalContent/AdditionalContentTests/TagTests/GetTagsByStreetcodeIdHandlerTests.cs @@ -3,10 +3,7 @@ using Microsoft.EntityFrameworkCore.Query; using Microsoft.Extensions.Localization; using Moq; -using Streetcode.BLL.DTO.AdditionalContent; using Streetcode.BLL.DTO.AdditionalContent.Tag; -using Streetcode.BLL.DTO.Streetcode; -using Streetcode.BLL.DTO.Streetcode.Types; using Streetcode.BLL.Interfaces.Logging; using Streetcode.BLL.MediatR.AdditionalContent.Tag.GetByStreetcodeId; using Streetcode.BLL.SharedResource; diff --git a/Streetcode/Streetcode.XUnitTest/MediatRTests/AdditionalContent/AdditionalContentTests/TagTests/UpdateTagHandlerTests.cs b/Streetcode/Streetcode.XUnitTest/MediatRTests/AdditionalContent/AdditionalContentTests/TagTests/UpdateTagHandlerTests.cs new file mode 100644 index 000000000..f17d54b56 --- /dev/null +++ b/Streetcode/Streetcode.XUnitTest/MediatRTests/AdditionalContent/AdditionalContentTests/TagTests/UpdateTagHandlerTests.cs @@ -0,0 +1,56 @@ +using AutoMapper; +using Microsoft.EntityFrameworkCore.Query; +using Moq; +using Streetcode.BLL.DTO.AdditionalContent; +using Streetcode.BLL.DTO.AdditionalContent.Tag; +using Streetcode.BLL.Interfaces.Logging; +using Streetcode.BLL.MediatR.AdditionalContent.Tag.Update; +using Streetcode.DAL.Entities.AdditionalContent; +using Streetcode.DAL.Entities.Streetcode.TextContent; +using Streetcode.DAL.Repositories.Interfaces.Base; +using System.Linq.Expressions; +using Xunit; + +namespace Streetcode.XUnitTest.MediatRTests.AdditionalContent.TagTests +{ + public class UpdateTagHandlerTests + { + private readonly Mock _mockRepo; + private readonly Mock _mockMapper; + private readonly Mock _mockLogger; + public UpdateTagHandlerTests() + { + _mockRepo = new Mock(); + _mockMapper = new Mock(); + _mockLogger = new Mock(); + } + + [Fact] + public async Task ShouldReturnSuccessfully_IsCorrectAndSuccess() + { + // Arrange + _mockRepo.Setup(repo => repo.TagRepository.Update(new Tag())); + _mockRepo.Setup(repo => repo.TagRepository.GetFirstOrDefaultAsync(It.IsAny>>(), default)) + .ReturnsAsync((Expression> expr, IIncludableQueryable include) => + { + BinaryExpression eq = (BinaryExpression)expr.Body; + MemberExpression member = (MemberExpression)eq.Left; + return member.Member.Name == "Id" ? new Tag() : null; + }); + + _mockRepo.Setup(repo => repo.SaveChangesAsync()).ReturnsAsync(1); + _mockMapper.Setup(x => x.Map(It.IsAny())).Returns(new TagDTO()); + + + var handler = new UpdateTagHandler(_mockRepo.Object, _mockMapper.Object, _mockLogger.Object); + + //Act + var result = await handler.Handle(new UpdateTagCommand(new UpdateTagDTO()), CancellationToken.None); + + //Assert + Assert.Multiple( + () => Assert.IsType(result.Value), + () => Assert.True(result.IsSuccess)); + } + } +} From de76ab7dd13a74cc4b076c6925c58321cb69532b Mon Sep 17 00:00:00 2001 From: Dmytro Date: Sat, 27 Apr 2024 12:28:18 +0300 Subject: [PATCH 13/25] add: unit test create, getById for historicalContext --- .../CreateHistoricalContextTest.cs | 45 +++++++++ .../GetByIdHistoricalContextTest.cs | 99 +++++++++++++++++++ 2 files changed, 144 insertions(+) create mode 100644 Streetcode/Streetcode.XUnitTest/MediatRTests/Timeline/HistoricalContextTests/CreateHistoricalContextTest.cs create mode 100644 Streetcode/Streetcode.XUnitTest/MediatRTests/Timeline/HistoricalContextTests/GetByIdHistoricalContextTest.cs diff --git a/Streetcode/Streetcode.XUnitTest/MediatRTests/Timeline/HistoricalContextTests/CreateHistoricalContextTest.cs b/Streetcode/Streetcode.XUnitTest/MediatRTests/Timeline/HistoricalContextTests/CreateHistoricalContextTest.cs new file mode 100644 index 000000000..c6d0f6513 --- /dev/null +++ b/Streetcode/Streetcode.XUnitTest/MediatRTests/Timeline/HistoricalContextTests/CreateHistoricalContextTest.cs @@ -0,0 +1,45 @@ +using AutoMapper; +using Moq; +using Streetcode.BLL.DTO.Timeline; +using Streetcode.BLL.Interfaces.Logging; +using Streetcode.BLL.MediatR.Timeline.HistoricalContext.Create; +using Streetcode.DAL.Entities.Timeline; +using Streetcode.DAL.Repositories.Interfaces.Base; +using Xunit; + +namespace Streetcode.XUnitTest.MediatRTests.Timeline.HistoricalContextTests +{ + public class CreateHistoricalContextTest + { + private readonly Mock _mockRepo; + private readonly Mock _mockMapper; + private readonly Mock _mockLogger; + + public CreateHistoricalContextTest() + { + _mockRepo = new Mock(); + _mockMapper = new Mock(); + _mockLogger = new Mock(); + } + + [Fact] + public async Task ShouldReturnSuccessfully_IsCorrectAndSuccess() + { + // Arrange + _mockRepo.Setup(repo => repo.HistoricalContextRepository.CreateAsync(new HistoricalContext())); + _mockRepo.Setup(repo => repo.SaveChangesAsync()).ReturnsAsync(1); + + _mockMapper.Setup(x => x.Map(It.IsAny())).Returns(new HistoricalContextDTO()); + + var handler = new CreateHistoricalContextHandler(_mockMapper.Object, _mockRepo.Object, _mockLogger.Object); + + // Act + var result = await handler.Handle(new CreateHistoricalContextCommand(new HistoricalContextDTO()), CancellationToken.None); + + // Assert + Assert.Multiple( + () => Assert.IsType(result.Value), + () => Assert.True(result.IsSuccess)); + } + } +} diff --git a/Streetcode/Streetcode.XUnitTest/MediatRTests/Timeline/HistoricalContextTests/GetByIdHistoricalContextTest.cs b/Streetcode/Streetcode.XUnitTest/MediatRTests/Timeline/HistoricalContextTests/GetByIdHistoricalContextTest.cs new file mode 100644 index 000000000..5826948e5 --- /dev/null +++ b/Streetcode/Streetcode.XUnitTest/MediatRTests/Timeline/HistoricalContextTests/GetByIdHistoricalContextTest.cs @@ -0,0 +1,99 @@ +using System.Linq.Expressions; +using AutoMapper; +using Microsoft.EntityFrameworkCore.Query; +using Microsoft.Extensions.Localization; +using Moq; +using Streetcode.BLL.DTO.AdditionalContent; +using Streetcode.BLL.DTO.Timeline; +using Streetcode.BLL.Interfaces.Logging; +using Streetcode.BLL.MediatR.AdditionalContent.Tag.GetById; +using Streetcode.BLL.MediatR.Timeline.HistoricalContext.GetById; +using Streetcode.BLL.SharedResource; +using Streetcode.DAL.Entities.AdditionalContent; +using Streetcode.DAL.Entities.Timeline; +using Streetcode.DAL.Repositories.Interfaces.Base; +using Xunit; + +namespace Streetcode.XUnitTest.MediatRTests.Timeline.HistoricalContextTests +{ + public class GetByIdHistoricalContextTest + { + private readonly Mock _mockRepo; + private readonly Mock _mockMapper; + private readonly Mock _mockLogger; + private readonly Mock> _mockLocalizer; + + public GetByIdHistoricalContextTest() + { + _mockRepo = new Mock(); + _mockMapper = new Mock(); + _mockLogger = new Mock(); + _mockLocalizer = new Mock>(); + } + + private const int _id = 1; + + private readonly HistoricalContext context = new HistoricalContext + { + Id = _id, + Title = "some title 1" + }; + + private readonly HistoricalContextDTO contextDto = new HistoricalContextDTO + { + Id = _id, + Title = "some title 1" + }; + + async Task SetupRepository(HistoricalContext context) + { + _mockRepo.Setup(repo => repo.HistoricalContextRepository.GetFirstOrDefaultAsync( + It.IsAny>>(), + It.IsAny, + IIncludableQueryable>>())) + .ReturnsAsync(context); + } + + async Task SetupMapper(HistoricalContextDTO contextDto) + { + _mockMapper.Setup(x => x.Map(It.IsAny())) + .Returns(contextDto); + } + + [Fact] + public async Task Handler_Returns_Matching_Element() + { + //Arrange + await SetupRepository(context); + await SetupMapper(contextDto); + + var handler = new GetHistoricalContextByIdHandler(_mockMapper.Object, _mockRepo.Object, _mockLogger.Object); + + //Act + var result = await handler.Handle(new GetHistoricalContextByIdQuery(_id), CancellationToken.None); + + //Assert + Assert.Multiple( + () => Assert.IsType(result.Value), + () => Assert.True(result.Value.Id.Equals(_id))); + } + + [Fact] + public async Task Handler_Returns_NoMatching_Element() + { + //Arrange + await SetupRepository(new HistoricalContext()); + await SetupMapper(new HistoricalContextDTO()); + + var handler = new GetHistoricalContextByIdHandler(_mockMapper.Object, _mockRepo.Object, _mockLogger.Object); + + //Act + var result = await handler.Handle(new GetHistoricalContextByIdQuery(_id), CancellationToken.None); + + //Assert + Assert.Multiple( + () => Assert.IsType(result.Value), + () => Assert.False(result.Value.Id.Equals(_id))); + } + } +} \ No newline at end of file From fa8334975e8a8cc19a74ade484d6415cf48acbe0 Mon Sep 17 00:00:00 2001 From: Dmytro Date: Sat, 27 Apr 2024 12:45:02 +0300 Subject: [PATCH 14/25] fix: getAllHistoricalContextTest.cs --- .../HistoricalContext/GetAll/GetAllHistoricalContextHandler.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Streetcode/Streetcode.BLL/MediatR/Timeline/HistoricalContext/GetAll/GetAllHistoricalContextHandler.cs b/Streetcode/Streetcode.BLL/MediatR/Timeline/HistoricalContext/GetAll/GetAllHistoricalContextHandler.cs index 667a2389f..efb5b3543 100644 --- a/Streetcode/Streetcode.BLL/MediatR/Timeline/HistoricalContext/GetAll/GetAllHistoricalContextHandler.cs +++ b/Streetcode/Streetcode.BLL/MediatR/Timeline/HistoricalContext/GetAll/GetAllHistoricalContextHandler.cs @@ -29,7 +29,6 @@ public async Task>> Handle(GetAllHistor var historicalContextItems = await _repositoryWrapper .HistoricalContextRepository .GetAllAsync(); - var historicalContexts = historicalContextItems.OrderBy(context => context.Title); if (historicalContextItems is null) { @@ -38,6 +37,8 @@ public async Task>> Handle(GetAllHistor return Result.Fail(new Error(errorMsg)); } + var historicalContexts = historicalContextItems.OrderBy(context => context.Title); + return Result.Ok(_mapper.Map>(historicalContexts)); } } From c7bced2c9a202915e2fb2bfed0f7ddc8184624e7 Mon Sep 17 00:00:00 2001 From: Dmytro Date: Sun, 28 Apr 2024 13:23:07 +0300 Subject: [PATCH 15/25] add: test for delete --- .../DeleteHistoricalContextTest.cs | 91 +++++++++++++++++++ 1 file changed, 91 insertions(+) create mode 100644 Streetcode/Streetcode.XUnitTest/MediatRTests/Timeline/HistoricalContextTests/DeleteHistoricalContextTest.cs diff --git a/Streetcode/Streetcode.XUnitTest/MediatRTests/Timeline/HistoricalContextTests/DeleteHistoricalContextTest.cs b/Streetcode/Streetcode.XUnitTest/MediatRTests/Timeline/HistoricalContextTests/DeleteHistoricalContextTest.cs new file mode 100644 index 000000000..ccb4df990 --- /dev/null +++ b/Streetcode/Streetcode.XUnitTest/MediatRTests/Timeline/HistoricalContextTests/DeleteHistoricalContextTest.cs @@ -0,0 +1,91 @@ +using System.Linq.Expressions; +using Moq; +using Streetcode.BLL.Interfaces.Logging; +using Streetcode.BLL.MediatR.Timeline.HistoricalContext.Delete; +using Streetcode.DAL.Entities.Timeline; +using Streetcode.DAL.Repositories.Interfaces.Base; +using Xunit; + +namespace Streetcode.XUnitTest.MediatRTests.Timeline.HistoricalContextTests +{ + public class DeleteHistoricalContextTest + { + private Mock _mockRepository; + private readonly Mock _mockLogger; + + public DeleteHistoricalContextTest() + { + _mockRepository = new Mock(); + _mockLogger = new Mock(); + } + + [Fact] + public async Task ShouldDeleteSuccessfully() + { + // Arrange + var testContexts = DeleteContext(); + SetupMockRepositoryGetFirstOrDefault(testContexts); + SetupMockRepositorySaveChangesReturns(1); + + var handler = new DeleteHistoricalContextHandler(_mockRepository.Object, _mockLogger.Object); + + // Act + var result = await handler.Handle(new DeleteHistoricalContextCommand(testContexts.Id), + CancellationToken.None); + + // Assert + Assert.Multiple( + () => Assert.NotNull(result), + () => Assert.True(result.IsSuccess) + ); + + _mockRepository.Verify( + x => x.HistoricalContextRepository.Delete(It.Is(x => x.Id == testContexts.Id)), + Times.Once); + _mockRepository.Verify(x => x.SaveChangesAsync(), Times.Once); + } + + [Fact] + public async Task ShouldThrowException_IdNotExisting() + { + // Arrange + var testContexts = DeleteContext(); + var expectedError = $"No context found by entered Id - {testContexts.Id}"; + SetupMockRepositoryGetFirstOrDefault(null); + + var handler = new DeleteHistoricalContextHandler(_mockRepository.Object, _mockLogger.Object); + + // Act + var result = await handler.Handle(new DeleteHistoricalContextCommand(testContexts.Id), CancellationToken.None); + + // Assert + Assert.Equal(expectedError, result.Errors.First().Message); + _mockRepository.Verify(x => x.HistoricalContextRepository.Delete(It.IsAny()), Times.Never); + } + + private void SetupMockRepositoryGetFirstOrDefault(HistoricalContext context) + { + _mockRepository.Setup(x => x.HistoricalContextRepository.GetFirstOrDefaultAsync( + It.IsAny>>(), null)) + .ReturnsAsync(context); + } + + private void SetupMockRepositorySaveChangesException(string expectedError) + { + _mockRepository.Setup(x => x.SaveChanges()).Throws(new Exception(expectedError)); + } + + private void SetupMockRepositorySaveChangesReturns(int number) + { + _mockRepository.Setup(x => x.SaveChangesAsync()).ReturnsAsync(number); + } + + private static HistoricalContext DeleteContext() + { + return new HistoricalContext + { + Id = 1 + }; + } + } +} \ No newline at end of file From 8aef160eacb59231fc301c223ff7d52c0eb8bc76 Mon Sep 17 00:00:00 2001 From: Dmytro Date: Wed, 1 May 2024 16:53:37 +0300 Subject: [PATCH 16/25] add: update unit test --- .../UpdateHistoricalContextTest.cs | 57 +++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 Streetcode/Streetcode.XUnitTest/MediatRTests/Timeline/HistoricalContextTests/UpdateHistoricalContextTest.cs diff --git a/Streetcode/Streetcode.XUnitTest/MediatRTests/Timeline/HistoricalContextTests/UpdateHistoricalContextTest.cs b/Streetcode/Streetcode.XUnitTest/MediatRTests/Timeline/HistoricalContextTests/UpdateHistoricalContextTest.cs new file mode 100644 index 000000000..8862b44c5 --- /dev/null +++ b/Streetcode/Streetcode.XUnitTest/MediatRTests/Timeline/HistoricalContextTests/UpdateHistoricalContextTest.cs @@ -0,0 +1,57 @@ +using System.Linq.Expressions; +using AutoMapper; +using Microsoft.EntityFrameworkCore.Query; +using Moq; +using Streetcode.BLL.DTO.AdditionalContent; +using Streetcode.BLL.DTO.Timeline; +using Streetcode.BLL.Interfaces.Logging; +using Streetcode.BLL.MediatR.Timeline.HistoricalContext.Update; +using Streetcode.DAL.Entities.AdditionalContent; +using Streetcode.DAL.Entities.Timeline; +using Streetcode.DAL.Repositories.Interfaces.Base; +using Xunit; + +namespace Streetcode.XUnitTest.MediatRTests.Timeline.HistoricalContextTests; + +public class UpdateHistoricalContextTest +{ + private readonly Mock _mockRepo; + private readonly Mock _mockMapper; + private readonly Mock _mockLogger; + + public UpdateHistoricalContextTest() + { + _mockRepo = new Mock(); + _mockMapper = new Mock(); + _mockLogger = new Mock(); + } + + [Fact] + public async Task ShouldReturnSuccessfully_IsCorrectAndSuccess() + { + // Arrange + _mockRepo.Setup(repo => repo.HistoricalContextRepository.Update(new HistoricalContext())); + _mockRepo.Setup(repo => + repo.HistoricalContextRepository.GetFirstOrDefaultAsync(It.IsAny>>(), default)) + .ReturnsAsync((Expression> expr, IIncludableQueryable include) => + { + BinaryExpression eq = (BinaryExpression)expr.Body; + MemberExpression member = (MemberExpression)eq.Left; + return member.Member.Name == "Id" ? new HistoricalContext() : null; + }); + + _mockRepo.Setup(repo => repo.SaveChangesAsync()).ReturnsAsync(1); + _mockMapper.Setup(x => x.Map(It.IsAny())).Returns(new HistoricalContextDTO()); + + + var handler = new UpdateHistoricalContextHandler(_mockRepo.Object, _mockMapper.Object, _mockLogger.Object); + + //Act + var result = await handler.Handle(new UpdateHistoricalContextCommand(new HistoricalContextDTO()), CancellationToken.None); + + //Assert + Assert.Multiple( + () => Assert.IsType(result.Value), + () => Assert.True(result.IsSuccess)); + } +} \ No newline at end of file From 468732c5fc8b88a8d30ceede86e33b51cec21ea1 Mon Sep 17 00:00:00 2001 From: Dmytro Date: Wed, 1 May 2024 19:46:19 +0300 Subject: [PATCH 17/25] integrational tests, 2 not working --- .../appsettings.IntegrationTests.json | 2 +- .../Streetcode.WebApi/appsettings.Local.json | 2 +- .../HistoricalContextControllerTests.cs | 415 ++++++++++++++++++ .../ExtractCreateTestHistoricalContext.cs | 32 ++ .../ExtractUpdateTestHistoricalContext.cs | 33 ++ .../Timeline/HistoricalContextClient.cs | 27 ++ .../Timeline/HistoricalContextExtracter.cs | 20 + .../Streetcode.XIntegrationTest.csproj | 1 + .../TestData/HistoricalContext.json | 3 + 9 files changed, 533 insertions(+), 2 deletions(-) create mode 100644 Streetcode/Streetcode.XIntegrationTest/ControllerTests/Timeline/HistoricalContextControllerTests.cs create mode 100644 Streetcode/Streetcode.XIntegrationTest/ControllerTests/Utils/AdditionalContent/Timeline/ExtractCreateTestHistoricalContext.cs create mode 100644 Streetcode/Streetcode.XIntegrationTest/ControllerTests/Utils/AdditionalContent/Timeline/ExtractUpdateTestHistoricalContext.cs create mode 100644 Streetcode/Streetcode.XIntegrationTest/ControllerTests/Utils/Client/Timeline/HistoricalContextClient.cs create mode 100644 Streetcode/Streetcode.XIntegrationTest/ControllerTests/Utils/Extracter/Timeline/HistoricalContextExtracter.cs create mode 100644 Streetcode/Streetcode.XIntegrationTest/TestData/HistoricalContext.json diff --git a/Streetcode/Streetcode.WebApi/appsettings.IntegrationTests.json b/Streetcode/Streetcode.WebApi/appsettings.IntegrationTests.json index 7543311b1..562b4c681 100644 --- a/Streetcode/Streetcode.WebApi/appsettings.IntegrationTests.json +++ b/Streetcode/Streetcode.WebApi/appsettings.IntegrationTests.json @@ -1,6 +1,6 @@ { "ConnectionStrings": { - "DefaultConnection": "Server=localhost,1455;Database=Streetcode_IntegrationTests_Db;User Id=sa;Password=sdlLKMCD234!@#lkcmds;MultipleActiveResultSets=True;TrustServerCertificate=true" + "DefaultConnection": "Server=PC;Database=IntegrationalTests;MultipleActiveResultSets=True;TrustServerCertificate=true;Trusted_Connection=true" }, "Blob": { "BlobStoreKey": "BigThirtyTwoBiteCoolTestKeyCrypt", diff --git a/Streetcode/Streetcode.WebApi/appsettings.Local.json b/Streetcode/Streetcode.WebApi/appsettings.Local.json index 14b44479d..054d6bc70 100644 --- a/Streetcode/Streetcode.WebApi/appsettings.Local.json +++ b/Streetcode/Streetcode.WebApi/appsettings.Local.json @@ -1,6 +1,6 @@ { "ConnectionStrings": { - "DefaultConnection": "Server=127.0.0.1;Database=StreetcodeDb;User Id=sa;Password=Admin@1234;MultipleActiveResultSets=true" + "DefaultConnection": "Server=PC;Database=IntegrationalTests;MultipleActiveResultSets=True;TrustServerCertificate=true;Trusted_Connection=true" }, "CORS": { "AllowedOrigins": [ "http://localhost:3000" ], diff --git a/Streetcode/Streetcode.XIntegrationTest/ControllerTests/Timeline/HistoricalContextControllerTests.cs b/Streetcode/Streetcode.XIntegrationTest/ControllerTests/Timeline/HistoricalContextControllerTests.cs new file mode 100644 index 000000000..d3db9b860 --- /dev/null +++ b/Streetcode/Streetcode.XIntegrationTest/ControllerTests/Timeline/HistoricalContextControllerTests.cs @@ -0,0 +1,415 @@ +using System.Linq.Expressions; +using System.Net; +using AutoMapper; +using Microsoft.EntityFrameworkCore.Query; +using Moq; +using Streetcode.BLL.DTO.Timeline; +using Streetcode.BLL.Interfaces.Logging; +using Streetcode.BLL.MediatR.Timeline.HistoricalContext.Create; +using Streetcode.BLL.MediatR.Timeline.HistoricalContext.Delete; +using Streetcode.BLL.MediatR.Timeline.HistoricalContext.Update; +using Streetcode.DAL.Entities.Streetcode; +using Streetcode.DAL.Entities.Timeline; +using Streetcode.DAL.Repositories.Interfaces.AdditionalContent; +using Streetcode.DAL.Repositories.Interfaces.Base; +using Streetcode.DAL.Repositories.Interfaces.Timeline; +using Streetcode.XIntegrationTest.Base; +using Streetcode.XIntegrationTest.ControllerTests.BaseController; +using Streetcode.XIntegrationTest.ControllerTests.Utils; +using Streetcode.XIntegrationTest.ControllerTests.Utils.AdditionalContent.Timeline; +using Streetcode.XIntegrationTest.ControllerTests.Utils.Client.Timeline; +using Streetcode.XIntegrationTest.ControllerTests.Utils.Extracter.StreetcodeExtracter; +using Streetcode.XIntegrationTest.ControllerTests.Utils.Extracter.Timeline; +using Xunit; + +namespace Streetcode.XIntegrationTest.ControllerTests.Timeline; + +[Collection("Authorization")] +public class HistoricalContextControllerTests : BaseAuthorizationControllerTests, + IClassFixture> +{ + private HistoricalContext _testCreateContext; + private HistoricalContext _testUpdateContext; + private StreetcodeContent _testStreetcodeContent; + + public HistoricalContextControllerTests(CustomWebApplicationFactory factory, TokenStorage tokenStorage) + : base(factory, "/api/HistoricalContext", tokenStorage) + { + int uniqueId = UniqueNumberGenerator.GenerateInt(); + this._testCreateContext = HistoricalContextExtracter.Extract(uniqueId); + this._testUpdateContext = HistoricalContextExtracter.Extract(uniqueId); + this._testStreetcodeContent = StreetcodeContentExtracter + .Extract( + uniqueId, + uniqueId, + Guid.NewGuid().ToString()); + } + + public override void Dispose() + { + StreetcodeContentExtracter.Remove(this._testStreetcodeContent); + HistoricalContextExtracter.Remove(this._testCreateContext); + } + + [Fact] + public async Task GetAll_ReturnSuccessStatusCode() + { + var response = await this.client.GetAllAsync(); + var returnedValue = + CaseIsensitiveJsonDeserializer.Deserialize>(response.Content); + + Assert.True(response.IsSuccessStatusCode); + Assert.NotNull(returnedValue); + } + + [Fact] + public async Task GetById_ReturnSuccessStatusCode() + { + HistoricalContext expectedContext = this._testCreateContext; + var response = await this.client.GetByIdAsync(expectedContext.Id); + + var returnedValue = CaseIsensitiveJsonDeserializer.Deserialize(response.Content); + + Assert.True(response.IsSuccessStatusCode); + Assert.NotNull(returnedValue); + Assert.Multiple( + () => Assert.Equal(expectedContext.Id, returnedValue?.Id), + () => Assert.Equal(expectedContext.Title, returnedValue?.Title)); + } + + [Fact] + public async Task GetByIdIncorrect_ReturnBadRequest() + { + int incorrectId = -100; + var response = await this.client.GetByIdAsync(incorrectId); + + Assert.Multiple( + () => Assert.Equal(System.Net.HttpStatusCode.BadRequest, response.StatusCode), + () => Assert.False(response.IsSuccessStatusCode)); + } + + [Fact] + [ExtractCreateTestHistoricalContext] + public async Task Create_ReturnsSuccessStatusCode() + { + // Arrange + var historicalContextCreateDto = ExtractCreateTestHistoricalContext.HistoricalContextForTest; + + // Act + var response = await client.CreateAsync(historicalContextCreateDto, _tokenStorage.AdminToken); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact] + [ExtractCreateTestHistoricalContext] + public async Task Create_ChangesNotSaved_ReturnsBadRequest() + { + var historicalContextCreateDto = ExtractCreateTestHistoricalContext.HistoricalContextForTest; + + var repositoryMock = new Mock(); + var repositoryWrapperMock = new Mock(); + repositoryMock.Setup(r => r.GetFirstOrDefaultAsync(default, default)).ReturnsAsync((HistoricalContext)null); + repositoryMock.Setup(r => r.CreateAsync(default)).ReturnsAsync(this._testCreateContext); + repositoryWrapperMock.SetupGet(wrapper => wrapper.HistoricalContextRepository).Returns(repositoryMock.Object); + repositoryWrapperMock.Setup(wrapper => wrapper.SaveChanges()).Returns(null); + repositoryWrapperMock.Setup(wrapper => wrapper.SaveChanges()).Throws(default(Exception)); + + var mapperMock = new Mock(); + var loggerMock = new Mock(); + + var handler = new CreateHistoricalContextHandler(mapperMock.Object, repositoryWrapperMock.Object, loggerMock.Object); + + var query = new CreateHistoricalContextCommand(historicalContextCreateDto); + var cancellationToken = CancellationToken.None; + + var result = await handler.Handle(query, cancellationToken); + + // Assert + Assert.False(result.IsSuccess); + } + + [Fact] + [ExtractCreateTestHistoricalContext] + public async Task Create_TokenNotPassed_ReturnsUnauthorized() + { + // Arrange + var historicalContextCreateDto = ExtractCreateTestHistoricalContext.HistoricalContextForTest; + + // Act + var response = await client.CreateAsync(historicalContextCreateDto); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + } + + [Fact] + [ExtractCreateTestHistoricalContext] + public async Task Create_NotAdminTokenPassed_ReturnsForbidden() + { + // Arrange + var historicalContextCreateDto = ExtractCreateTestHistoricalContext.HistoricalContextForTest; + + // Act + var response = await client.CreateAsync(historicalContextCreateDto, _tokenStorage.UserToken); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + } + + + [Fact] + [ExtractCreateTestHistoricalContext] + public async Task Create_CreatesNewHistoricalContext() + { + // Arrange + var historicalContextCreateDto = ExtractCreateTestHistoricalContext.HistoricalContextForTest; + + // Act + var response = await client.CreateAsync(historicalContextCreateDto, _tokenStorage.AdminToken); + var getResponse = await client.GetByIdAsync(historicalContextCreateDto.Id); + var fetchedStreetcode = CaseIsensitiveJsonDeserializer.Deserialize(getResponse.Content); + + // Assert + Assert.Equal(historicalContextCreateDto.Title, fetchedStreetcode.Title); + } + + [Fact] + [ExtractCreateTestHistoricalContext] + public async Task Create_WithInvalidData_ReturnsBadRequest() + { + // Arrange + var historicalContextCreateDto = ExtractCreateTestHistoricalContext.HistoricalContextForTest; + historicalContextCreateDto.Title = null; // Invalid data + + // Act + var response = await client.CreateAsync(historicalContextCreateDto, _tokenStorage.AdminToken); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + } + + [Fact] + [ExtractCreateTestHistoricalContext] + public async Task Create_WithExistingTag_ReturnsConflict() + { + // Arrange + var historicalContextCreateDto = ExtractCreateTestHistoricalContext.HistoricalContextForTest; + historicalContextCreateDto.Title = _testCreateContext.Title; + + // Act + var response = await client.CreateAsync(historicalContextCreateDto, _tokenStorage.AdminToken); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + } + + [Fact] + [ExtractUpdateTestHistoricalContext] + public async Task Update_ReturnSuccessStatusCode() + { + // Arrange + var historicalContextCreateDto = ExtractUpdateTestHistoricalContext.HistoricalContextForTest; + historicalContextCreateDto.Id = this._testCreateContext.Id; + + // Act + var response = await client.UpdateAsync(historicalContextCreateDto, _tokenStorage.AdminToken); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact] + [ExtractUpdateTestHistoricalContext] + public async Task Update_Incorect_ReturnBadRequest() + { + // Arrange + var historicalContextCreateDto = ExtractUpdateTestHistoricalContext.HistoricalContextForTest; + + // Act + var response = await client.UpdateAsync(historicalContextCreateDto, _tokenStorage.AdminToken); + + // Assert + Assert.Multiple( + () => Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode), + () => Assert.False(response.IsSuccessStatusCode)); + } + + [Fact] + [ExtractUpdateTestHistoricalContext] + public async Task Update_TokenNotPassed_ReturnsUnauthorized() + { + // Arrange + var historicalContextCreateDto = ExtractUpdateTestHistoricalContext.HistoricalContextForTest; + + // Act + var response = await client.UpdateAsync(historicalContextCreateDto); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + } + + [Fact] + [ExtractUpdateTestHistoricalContext] + public async Task Update_NotAdminTokenPassed_ReturnsForbidden() + { + // Arrange + var historicalContextCreateDto = ExtractUpdateTestHistoricalContext.HistoricalContextForTest; + + // Act + var response = await client.UpdateAsync(historicalContextCreateDto, _tokenStorage.UserToken); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + } + + [Fact] + [ExtractUpdateTestHistoricalContext] + public async Task Update_WithInvalidData_ReturnsBadRequest() + { + // Arrange + var historicalContextCreateDto = ExtractUpdateTestHistoricalContext.HistoricalContextForTest; + historicalContextCreateDto.Title = null; // Invalid data + + // Act + var response = await client.UpdateAsync(historicalContextCreateDto, _tokenStorage.AdminToken); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + } + + [Fact] + [ExtractUpdateTestHistoricalContext] + public async Task Update_WithExistingTitle_ReturnsBadRequest() + { + // Arrange + var historicalContextCreateDto = ExtractUpdateTestHistoricalContext.HistoricalContextForTest; + historicalContextCreateDto.Id = this._testCreateContext.Id; + historicalContextCreateDto.Title = this._testUpdateContext.Title; + + // Act + var response = await client.UpdateAsync(historicalContextCreateDto, _tokenStorage.AdminToken); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + } + + [Fact] + [ExtractUpdateTestHistoricalContext] + public async Task Update_ChangesNotSaved_ReturnsBadRequest() + { + // Arrange + Expression> testExpression = x => x.Id == this._testUpdateContext.Id; + + var historicalContextCreateDto = ExtractUpdateTestHistoricalContext.HistoricalContextForTest; + historicalContextCreateDto.Id = this._testUpdateContext.Id; + + var repositoryMock = new Mock(); + var repositoryWrapperMock = new Mock(); + repositoryMock.Setup(r => r.GetFirstOrDefaultAsync(It.IsAny>>(), default)) + .ReturnsAsync((Expression> expr, IIncludableQueryable include) => + { + var compiledExpr = expr.Compile(); + return compiledExpr(this._testUpdateContext) ? this._testUpdateContext : null; + }); + + repositoryWrapperMock.SetupGet(wrapper => wrapper.HistoricalContextRepository).Returns(repositoryMock.Object); + repositoryWrapperMock.Setup(wrapper => wrapper.SaveChangesAsync()).ReturnsAsync(null); + repositoryWrapperMock.Setup(wrapper => wrapper.SaveChangesAsync()).Throws(default(Exception)); + + var mapperMock = new Mock(); + mapperMock.Setup(m => m.Map(default)).Returns(this._testUpdateContext); + var loggerMock = new Mock(); + + var handler = new UpdateHistoricalContextHandler(repositoryWrapperMock.Object, mapperMock.Object, loggerMock.Object); + + var query = new UpdateHistoricalContextCommand(historicalContextCreateDto); + var cancellationToken = CancellationToken.None; + // Act + var result = await handler.Handle(query, cancellationToken); + + // Assert + Assert.False(result.IsSuccess); + } + + [Fact] + public async Task Delete_ReturnsSuccessStatusCode() + { + // Arrange + int id = this._testCreateContext.Id; + + // Act + var response = await this.client.Delete(id, this._tokenStorage.AdminToken); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact] + public async Task Delete_TokenNotPassed_ReturnsUnathorized() + { + // Arrange + int id = this._testCreateContext.Id; + + // Act + var response = await this.client.Delete(id); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + } + + [Fact] + public async Task Delete_NotAdminTokenPassed_ReturnsForbidden() + { + // Arrange + int id = this._testCreateContext.Id; + + // Act + var response = await this.client.Delete(id, this._tokenStorage.UserToken); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + } + + [Fact] + public async Task Delete_WithInvalidData_ReturnsBadRequest() + { + // Arrange + int id = -100; + + // Act + var response = await this.client.Delete(id, this._tokenStorage.AdminToken); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + } + + [Fact] + public async Task Delete_ChangesNotSaved_ReturnsBadRequest() + { + int id = this._testUpdateContext.Id; + + var repositoryMock = new Mock(); + var repositoryWrapperMock = new Mock(); + repositoryMock.Setup(r => r.GetFirstOrDefaultAsync(It.IsAny>>(), default)) + .ReturnsAsync(this._testUpdateContext); + repositoryMock.Setup(r => r.Delete(default)); + + repositoryWrapperMock.SetupGet(wrapper => wrapper.HistoricalContextRepository).Returns(repositoryMock.Object); + repositoryWrapperMock.Setup(wrapper => wrapper.SaveChangesAsync()).ReturnsAsync(null); + repositoryWrapperMock.Setup(wrapper => wrapper.SaveChangesAsync()).Throws(default(Exception)); + + var loggerMock = new Mock(); + + var handler = new DeleteHistoricalContextHandler(repositoryWrapperMock.Object, loggerMock.Object); + + var query = new DeleteHistoricalContextCommand(id); + var cancellationToken = CancellationToken.None; + // Act + var result = await handler.Handle(query, cancellationToken); + + // Assert + Assert.False(result.IsSuccess); + } +} \ No newline at end of file diff --git a/Streetcode/Streetcode.XIntegrationTest/ControllerTests/Utils/AdditionalContent/Timeline/ExtractCreateTestHistoricalContext.cs b/Streetcode/Streetcode.XIntegrationTest/ControllerTests/Utils/AdditionalContent/Timeline/ExtractCreateTestHistoricalContext.cs new file mode 100644 index 000000000..d26316867 --- /dev/null +++ b/Streetcode/Streetcode.XIntegrationTest/ControllerTests/Utils/AdditionalContent/Timeline/ExtractCreateTestHistoricalContext.cs @@ -0,0 +1,32 @@ +using System.Reflection; +using Streetcode.BLL.DTO.Timeline; +using Streetcode.DAL.Entities.Timeline; +using Streetcode.XIntegrationTest.ControllerTests.BaseController; +using Xunit.Sdk; + +namespace Streetcode.XIntegrationTest.ControllerTests.Utils.AdditionalContent.Timeline; + +[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] +public class ExtractCreateTestHistoricalContext: BeforeAfterTestAttribute +{ + public static HistoricalContextDTO HistoricalContextForTest; + + public override void Before(MethodInfo methodUnderTest) + { + HistoricalContextForTest = new HistoricalContextDTO + { + Title = "Test", + }; + } + + public override void After(MethodInfo methodUnderTest) + { + var sqlDbHelper = BaseControllerTests.GetSqlDbHelper(); + var context = sqlDbHelper.GetExistItem(p => p.Title == HistoricalContextForTest.Title); + if (context != null) + { + sqlDbHelper.DeleteItem(context); + sqlDbHelper.SaveChanges(); + } + } +} \ No newline at end of file diff --git a/Streetcode/Streetcode.XIntegrationTest/ControllerTests/Utils/AdditionalContent/Timeline/ExtractUpdateTestHistoricalContext.cs b/Streetcode/Streetcode.XIntegrationTest/ControllerTests/Utils/AdditionalContent/Timeline/ExtractUpdateTestHistoricalContext.cs new file mode 100644 index 000000000..fed8a383c --- /dev/null +++ b/Streetcode/Streetcode.XIntegrationTest/ControllerTests/Utils/AdditionalContent/Timeline/ExtractUpdateTestHistoricalContext.cs @@ -0,0 +1,33 @@ +using System.Reflection; +using Streetcode.BLL.DTO.Timeline; +using Streetcode.DAL.Entities.Timeline; +using Streetcode.XIntegrationTest.ControllerTests.BaseController; +using Xunit.Sdk; + +namespace Streetcode.XIntegrationTest.ControllerTests.Utils.AdditionalContent.Timeline; + +[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] +public class ExtractUpdateTestHistoricalContext : BeforeAfterTestAttribute +{ + public static HistoricalContextDTO HistoricalContextForTest; + + public override void Before(MethodInfo methodUnderTest) + { + HistoricalContextForTest = new HistoricalContextDTO + { + Id = 1, + Title = "New Title Test", + }; + } + + public override void After(MethodInfo methodUnderTest) + { + var sqlDbHelper = BaseControllerTests.GetSqlDbHelper(); + var context = sqlDbHelper.GetExistItem(p => p.Title == HistoricalContextForTest.Title); + if (context != null) + { + sqlDbHelper.DeleteItem(context); + sqlDbHelper.SaveChanges(); + } + } +} \ No newline at end of file diff --git a/Streetcode/Streetcode.XIntegrationTest/ControllerTests/Utils/Client/Timeline/HistoricalContextClient.cs b/Streetcode/Streetcode.XIntegrationTest/ControllerTests/Utils/Client/Timeline/HistoricalContextClient.cs new file mode 100644 index 000000000..95319aa4c --- /dev/null +++ b/Streetcode/Streetcode.XIntegrationTest/ControllerTests/Utils/Client/Timeline/HistoricalContextClient.cs @@ -0,0 +1,27 @@ +using RestSharp; +using Streetcode.BLL.DTO.Timeline; +using Streetcode.XIntegrationTest.ControllerTests.Utils.Client.Base; + +namespace Streetcode.XIntegrationTest.ControllerTests.Utils.Client.Timeline; + +public class HistoricalContextClient : StreetcodeRelatedBaseClient +{ + public HistoricalContextClient(HttpClient client, string secondPartUrl = "") + : base(client, secondPartUrl) + { + } + public async Task UpdateAsync(HistoricalContextDTO updateTagDTO, string authToken = "") + { + return await this.SendCommand("/Update", Method.Put, updateTagDTO, authToken); + } + + public async Task CreateAsync(HistoricalContextDTO createTagDTO, string authToken = "") + { + return await this.SendCommand("/Create", Method.Post, createTagDTO, authToken); + } + + public async Task Delete(int id, string authToken = "") + { + return await this.SendCommand($"/Delete/{id}", Method.Delete, new HistoricalContextDTO(), authToken); + } +} \ No newline at end of file diff --git a/Streetcode/Streetcode.XIntegrationTest/ControllerTests/Utils/Extracter/Timeline/HistoricalContextExtracter.cs b/Streetcode/Streetcode.XIntegrationTest/ControllerTests/Utils/Extracter/Timeline/HistoricalContextExtracter.cs new file mode 100644 index 000000000..f4b03abd5 --- /dev/null +++ b/Streetcode/Streetcode.XIntegrationTest/ControllerTests/Utils/Extracter/Timeline/HistoricalContextExtracter.cs @@ -0,0 +1,20 @@ +using Streetcode.DAL.Entities.Timeline; + +namespace Streetcode.XIntegrationTest.ControllerTests.Utils.Extracter.Timeline; + +public class HistoricalContextExtracter +{ + public static HistoricalContext Extract(int contextId) + { + HistoricalContext testContext = TestDataProvider.GetTestData(); + + testContext.Id = contextId; + + return BaseExtracter.Extract(testContext, context => context.Id == contextId); + } + + public static void Remove(HistoricalContext entity) + { + BaseExtracter.RemoveByPredicate(context => context.Id == entity.Id); + } +} \ No newline at end of file diff --git a/Streetcode/Streetcode.XIntegrationTest/Streetcode.XIntegrationTest.csproj b/Streetcode/Streetcode.XIntegrationTest/Streetcode.XIntegrationTest.csproj index f94ef13cd..0ee1a5f95 100644 --- a/Streetcode/Streetcode.XIntegrationTest/Streetcode.XIntegrationTest.csproj +++ b/Streetcode/Streetcode.XIntegrationTest/Streetcode.XIntegrationTest.csproj @@ -28,6 +28,7 @@ + all diff --git a/Streetcode/Streetcode.XIntegrationTest/TestData/HistoricalContext.json b/Streetcode/Streetcode.XIntegrationTest/TestData/HistoricalContext.json new file mode 100644 index 000000000..ddf63d923 --- /dev/null +++ b/Streetcode/Streetcode.XIntegrationTest/TestData/HistoricalContext.json @@ -0,0 +1,3 @@ +{ + "Title": "Title" +} \ No newline at end of file From ab856930e635b8e5c224e80e18ca1b6dd3751bd8 Mon Sep 17 00:00:00 2001 From: Dmytro Date: Wed, 1 May 2024 20:18:11 +0300 Subject: [PATCH 18/25] add: getByTitle, unit test. fix: integrationalTests --- .../GetHistoricalContextByTitleHandler.cs | 46 +++++++++ .../GetHistoricalContextByTitleQuery.cs | 8 ++ .../Timeline/HistoricalContextController.cs | 7 ++ .../Streetcode.WebApi/appsettings.Local.json | 2 +- .../HistoricalContextControllerTests.cs | 30 +----- .../Timeline/HistoricalContextClient.cs | 6 ++ .../GetByTitleHistoricalContextTest.cs | 93 +++++++++++++++++++ 7 files changed, 162 insertions(+), 30 deletions(-) create mode 100644 Streetcode/Streetcode.BLL/MediatR/Timeline/HistoricalContext/GetByTitle/GetHistoricalContextByTitleHandler.cs create mode 100644 Streetcode/Streetcode.BLL/MediatR/Timeline/HistoricalContext/GetByTitle/GetHistoricalContextByTitleQuery.cs create mode 100644 Streetcode/Streetcode.XUnitTest/MediatRTests/Timeline/HistoricalContextTests/GetByTitleHistoricalContextTest.cs diff --git a/Streetcode/Streetcode.BLL/MediatR/Timeline/HistoricalContext/GetByTitle/GetHistoricalContextByTitleHandler.cs b/Streetcode/Streetcode.BLL/MediatR/Timeline/HistoricalContext/GetByTitle/GetHistoricalContextByTitleHandler.cs new file mode 100644 index 000000000..ddb64131c --- /dev/null +++ b/Streetcode/Streetcode.BLL/MediatR/Timeline/HistoricalContext/GetByTitle/GetHistoricalContextByTitleHandler.cs @@ -0,0 +1,46 @@ +using AutoMapper; +using FluentResults; +using MediatR; +using Streetcode.BLL.DTO.Timeline; +using Streetcode.BLL.Interfaces.Logging; +using Streetcode.BLL.MediatR.Timeline.HistoricalContext.GetById; +using Streetcode.DAL.Repositories.Interfaces.Base; + +namespace Streetcode.BLL.MediatR.Timeline.HistoricalContext.GetByTitle; + +public class GetHistoricalContextByTitleHandler : IRequestHandler> +{ + private readonly IMapper _mapper; + private readonly IRepositoryWrapper _repository; + private readonly ILoggerService _loggerService; + + public GetHistoricalContextByTitleHandler(IMapper mapper, IRepositoryWrapper repository, ILoggerService loggerService) + { + _mapper = mapper; + _repository = repository; + _loggerService = loggerService; + } + + public async Task> Handle(GetHistoricalContextByTitleQuery request, CancellationToken cancellationToken) + { + var context = await _repository.HistoricalContextRepository.GetFirstOrDefaultAsync(j => j.Title == request.title); + + if (context is null) + { + string exceptionMessege = $"No context found by title - {request.title}"; + _loggerService.LogError(request, exceptionMessege); + return Result.Fail(exceptionMessege); + } + + try + { + var contextDto = _mapper.Map(context); + return Result.Ok(contextDto); + } + catch (Exception ex) + { + _loggerService.LogError(request, ex.Message); + return Result.Fail(ex.Message); + } + } +} \ No newline at end of file diff --git a/Streetcode/Streetcode.BLL/MediatR/Timeline/HistoricalContext/GetByTitle/GetHistoricalContextByTitleQuery.cs b/Streetcode/Streetcode.BLL/MediatR/Timeline/HistoricalContext/GetByTitle/GetHistoricalContextByTitleQuery.cs new file mode 100644 index 000000000..6fece034d --- /dev/null +++ b/Streetcode/Streetcode.BLL/MediatR/Timeline/HistoricalContext/GetByTitle/GetHistoricalContextByTitleQuery.cs @@ -0,0 +1,8 @@ +using FluentResults; +using MediatR; +using Streetcode.BLL.DTO.Timeline; + +namespace Streetcode.BLL.MediatR.Timeline.HistoricalContext.GetByTitle; + +public record GetHistoricalContextByTitleQuery(string title) + : IRequest>; \ No newline at end of file diff --git a/Streetcode/Streetcode.WebApi/Controllers/Timeline/HistoricalContextController.cs b/Streetcode/Streetcode.WebApi/Controllers/Timeline/HistoricalContextController.cs index 48bad0436..f0d874235 100644 --- a/Streetcode/Streetcode.WebApi/Controllers/Timeline/HistoricalContextController.cs +++ b/Streetcode/Streetcode.WebApi/Controllers/Timeline/HistoricalContextController.cs @@ -5,6 +5,7 @@ using Streetcode.BLL.MediatR.Timeline.HistoricalContext.Delete; using Streetcode.BLL.MediatR.Timeline.HistoricalContext.GetAll; using Streetcode.BLL.MediatR.Timeline.HistoricalContext.GetById; +using Streetcode.BLL.MediatR.Timeline.HistoricalContext.GetByTitle; using Streetcode.BLL.MediatR.Timeline.HistoricalContext.Update; using Streetcode.DAL.Enums; @@ -24,6 +25,12 @@ public async Task GetById(int id) return HandleResult(await Mediator.Send(new GetHistoricalContextByIdQuery(id))); } + [HttpGet("{title}")] + public async Task GetByTitle(string title) + { + return HandleResult(await Mediator.Send(new GetHistoricalContextByTitleQuery(title))); + } + [HttpPut] [Authorize(Roles = nameof(UserRole.Admin))] [ProducesResponseType(StatusCodes.Status401Unauthorized)] diff --git a/Streetcode/Streetcode.WebApi/appsettings.Local.json b/Streetcode/Streetcode.WebApi/appsettings.Local.json index 054d6bc70..7a665d789 100644 --- a/Streetcode/Streetcode.WebApi/appsettings.Local.json +++ b/Streetcode/Streetcode.WebApi/appsettings.Local.json @@ -1,6 +1,6 @@ { "ConnectionStrings": { - "DefaultConnection": "Server=PC;Database=IntegrationalTests;MultipleActiveResultSets=True;TrustServerCertificate=true;Trusted_Connection=true" + "DefaultConnection": "Server=PC;Database=Streetcode1;MultipleActiveResultSets=True;TrustServerCertificate=true;Trusted_Connection=true" }, "CORS": { "AllowedOrigins": [ "http://localhost:3000" ], diff --git a/Streetcode/Streetcode.XIntegrationTest/ControllerTests/Timeline/HistoricalContextControllerTests.cs b/Streetcode/Streetcode.XIntegrationTest/ControllerTests/Timeline/HistoricalContextControllerTests.cs index d3db9b860..88deb8ac4 100644 --- a/Streetcode/Streetcode.XIntegrationTest/ControllerTests/Timeline/HistoricalContextControllerTests.cs +++ b/Streetcode/Streetcode.XIntegrationTest/ControllerTests/Timeline/HistoricalContextControllerTests.cs @@ -102,34 +102,6 @@ public async Task Create_ReturnsSuccessStatusCode() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] - [ExtractCreateTestHistoricalContext] - public async Task Create_ChangesNotSaved_ReturnsBadRequest() - { - var historicalContextCreateDto = ExtractCreateTestHistoricalContext.HistoricalContextForTest; - - var repositoryMock = new Mock(); - var repositoryWrapperMock = new Mock(); - repositoryMock.Setup(r => r.GetFirstOrDefaultAsync(default, default)).ReturnsAsync((HistoricalContext)null); - repositoryMock.Setup(r => r.CreateAsync(default)).ReturnsAsync(this._testCreateContext); - repositoryWrapperMock.SetupGet(wrapper => wrapper.HistoricalContextRepository).Returns(repositoryMock.Object); - repositoryWrapperMock.Setup(wrapper => wrapper.SaveChanges()).Returns(null); - repositoryWrapperMock.Setup(wrapper => wrapper.SaveChanges()).Throws(default(Exception)); - - var mapperMock = new Mock(); - var loggerMock = new Mock(); - - var handler = new CreateHistoricalContextHandler(mapperMock.Object, repositoryWrapperMock.Object, loggerMock.Object); - - var query = new CreateHistoricalContextCommand(historicalContextCreateDto); - var cancellationToken = CancellationToken.None; - - var result = await handler.Handle(query, cancellationToken); - - // Assert - Assert.False(result.IsSuccess); - } - [Fact] [ExtractCreateTestHistoricalContext] public async Task Create_TokenNotPassed_ReturnsUnauthorized() @@ -168,7 +140,7 @@ public async Task Create_CreatesNewHistoricalContext() // Act var response = await client.CreateAsync(historicalContextCreateDto, _tokenStorage.AdminToken); - var getResponse = await client.GetByIdAsync(historicalContextCreateDto.Id); + var getResponse = await client.GetByTitle(historicalContextCreateDto.Title); var fetchedStreetcode = CaseIsensitiveJsonDeserializer.Deserialize(getResponse.Content); // Assert diff --git a/Streetcode/Streetcode.XIntegrationTest/ControllerTests/Utils/Client/Timeline/HistoricalContextClient.cs b/Streetcode/Streetcode.XIntegrationTest/ControllerTests/Utils/Client/Timeline/HistoricalContextClient.cs index 95319aa4c..f63b629f6 100644 --- a/Streetcode/Streetcode.XIntegrationTest/ControllerTests/Utils/Client/Timeline/HistoricalContextClient.cs +++ b/Streetcode/Streetcode.XIntegrationTest/ControllerTests/Utils/Client/Timeline/HistoricalContextClient.cs @@ -10,6 +10,12 @@ public HistoricalContextClient(HttpClient client, string secondPartUrl = "") : base(client, secondPartUrl) { } + + public async Task GetByTitle(string title, string authToken = "") + { + return await this.SendQuery($"/GetByTitle/{title}", authToken); + } + public async Task UpdateAsync(HistoricalContextDTO updateTagDTO, string authToken = "") { return await this.SendCommand("/Update", Method.Put, updateTagDTO, authToken); diff --git a/Streetcode/Streetcode.XUnitTest/MediatRTests/Timeline/HistoricalContextTests/GetByTitleHistoricalContextTest.cs b/Streetcode/Streetcode.XUnitTest/MediatRTests/Timeline/HistoricalContextTests/GetByTitleHistoricalContextTest.cs new file mode 100644 index 000000000..d1f77577c --- /dev/null +++ b/Streetcode/Streetcode.XUnitTest/MediatRTests/Timeline/HistoricalContextTests/GetByTitleHistoricalContextTest.cs @@ -0,0 +1,93 @@ +using System.Linq.Expressions; +using AutoMapper; +using Microsoft.EntityFrameworkCore.Query; +using Microsoft.Extensions.Localization; +using Moq; +using Streetcode.BLL.DTO.Timeline; +using Streetcode.BLL.Interfaces.Logging; +using Streetcode.BLL.MediatR.Timeline.HistoricalContext.GetByTitle; +using Streetcode.BLL.SharedResource; +using Streetcode.DAL.Entities.Timeline; +using Streetcode.DAL.Repositories.Interfaces.Base; +using Xunit; + +namespace Streetcode.XUnitTest.MediatRTests.Timeline.HistoricalContextTests; + +public class GetByTitleHistoricalContextTest +{ + private readonly Mock _mockRepo; + private readonly Mock _mockMapper; + private readonly Mock _mockLogger; + + public GetByTitleHistoricalContextTest() + { + _mockRepo = new Mock(); + _mockMapper = new Mock(); + _mockLogger = new Mock(); + } + + private static string _title = "test_title"; + + private readonly HistoricalContext context = new HistoricalContext + { + Id = 1, + Title = _title + }; + + private readonly HistoricalContextDTO contextDto = new HistoricalContextDTO + { + Id = 1, + Title = _title + }; + + async Task SetupRepository(HistoricalContext context) + { + _mockRepo.Setup(repo => repo.HistoricalContextRepository.GetFirstOrDefaultAsync( + It.IsAny>>(), + It.IsAny, + IIncludableQueryable>>())) + .ReturnsAsync(context); + } + + async Task SetupMapper(HistoricalContextDTO contextDto) + { + _mockMapper.Setup(x => x.Map(It.IsAny())) + .Returns(contextDto); + } + + [Fact] + public async Task Handler_Returns_Matching_Element() + { + //Arrange + await SetupRepository(context); + await SetupMapper(contextDto); + + var handler = new GetHistoricalContextByTitleHandler(_mockMapper.Object, _mockRepo.Object, _mockLogger.Object); + + //Act + var result = await handler.Handle(new GetHistoricalContextByTitleQuery(_title), CancellationToken.None); + + //Assert + Assert.Multiple( + () => Assert.IsType(result.Value), + () => Assert.Equal(result.Value.Title, _title)); + } + + [Fact] + public async Task Handler_Returns_NoMatching_Element() + { + //Arrange + await SetupRepository(new HistoricalContext()); + await SetupMapper(new HistoricalContextDTO()); + + var handler = new GetHistoricalContextByTitleHandler(_mockMapper.Object, _mockRepo.Object, _mockLogger.Object); + + //Act + var result = await handler.Handle(new GetHistoricalContextByTitleQuery(_title), CancellationToken.None); + + //Assert + Assert.Multiple( + () => Assert.IsType(result.Value), + () => Assert.Null(result.Value.Title)); + } +} \ No newline at end of file From 5373fd7ce078ff3cd175cc0f744025c61dae99ca Mon Sep 17 00:00:00 2001 From: Dmytro Date: Wed, 1 May 2024 20:25:30 +0300 Subject: [PATCH 19/25] returned appsettings string --- Streetcode/Streetcode.WebApi/appsettings.IntegrationTests.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Streetcode/Streetcode.WebApi/appsettings.IntegrationTests.json b/Streetcode/Streetcode.WebApi/appsettings.IntegrationTests.json index 562b4c681..166207209 100644 --- a/Streetcode/Streetcode.WebApi/appsettings.IntegrationTests.json +++ b/Streetcode/Streetcode.WebApi/appsettings.IntegrationTests.json @@ -1,6 +1,6 @@ { "ConnectionStrings": { - "DefaultConnection": "Server=PC;Database=IntegrationalTests;MultipleActiveResultSets=True;TrustServerCertificate=true;Trusted_Connection=true" + "DefaultConnection": "Server=localhost;Database=Streetcode_IntegrationTests_Db;User Id=sa;Password=sdlLKMCD234!@#lkcmds;MultipleActiveResultSets=True;TrustServerCertificate=true" }, "Blob": { "BlobStoreKey": "BigThirtyTwoBiteCoolTestKeyCrypt", From 5ff855fba594e4820690a5b4e6b4eef8829d8d8a Mon Sep 17 00:00:00 2001 From: Dmytro Date: Wed, 1 May 2024 21:10:16 +0300 Subject: [PATCH 20/25] add: nonsense change that might help --- .../Timeline/HistoricalContextControllerTests.cs | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/Streetcode/Streetcode.XIntegrationTest/ControllerTests/Timeline/HistoricalContextControllerTests.cs b/Streetcode/Streetcode.XIntegrationTest/ControllerTests/Timeline/HistoricalContextControllerTests.cs index 88deb8ac4..1468fa5b0 100644 --- a/Streetcode/Streetcode.XIntegrationTest/ControllerTests/Timeline/HistoricalContextControllerTests.cs +++ b/Streetcode/Streetcode.XIntegrationTest/ControllerTests/Timeline/HistoricalContextControllerTests.cs @@ -156,7 +156,7 @@ public async Task Create_WithInvalidData_ReturnsBadRequest() historicalContextCreateDto.Title = null; // Invalid data // Act - var response = await client.CreateAsync(historicalContextCreateDto, _tokenStorage.AdminToken); + var response = await client.CreateAsync(historicalContextCreateDto, this._tokenStorage.AdminToken); // Assert Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); @@ -171,7 +171,7 @@ public async Task Create_WithExistingTag_ReturnsConflict() historicalContextCreateDto.Title = _testCreateContext.Title; // Act - var response = await client.CreateAsync(historicalContextCreateDto, _tokenStorage.AdminToken); + var response = await client.CreateAsync(historicalContextCreateDto, this._tokenStorage.AdminToken); // Assert Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); @@ -186,7 +186,7 @@ public async Task Update_ReturnSuccessStatusCode() historicalContextCreateDto.Id = this._testCreateContext.Id; // Act - var response = await client.UpdateAsync(historicalContextCreateDto, _tokenStorage.AdminToken); + var response = await client.UpdateAsync(historicalContextCreateDto, this._tokenStorage.AdminToken); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -200,7 +200,7 @@ public async Task Update_Incorect_ReturnBadRequest() var historicalContextCreateDto = ExtractUpdateTestHistoricalContext.HistoricalContextForTest; // Act - var response = await client.UpdateAsync(historicalContextCreateDto, _tokenStorage.AdminToken); + var response = await client.UpdateAsync(historicalContextCreateDto, this._tokenStorage.AdminToken); // Assert Assert.Multiple( @@ -230,7 +230,7 @@ public async Task Update_NotAdminTokenPassed_ReturnsForbidden() var historicalContextCreateDto = ExtractUpdateTestHistoricalContext.HistoricalContextForTest; // Act - var response = await client.UpdateAsync(historicalContextCreateDto, _tokenStorage.UserToken); + var response = await client.UpdateAsync(historicalContextCreateDto, this._tokenStorage.UserToken); // Assert Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); @@ -245,7 +245,7 @@ public async Task Update_WithInvalidData_ReturnsBadRequest() historicalContextCreateDto.Title = null; // Invalid data // Act - var response = await client.UpdateAsync(historicalContextCreateDto, _tokenStorage.AdminToken); + var response = await client.UpdateAsync(historicalContextCreateDto, this._tokenStorage.AdminToken); // Assert Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); @@ -261,7 +261,7 @@ public async Task Update_WithExistingTitle_ReturnsBadRequest() historicalContextCreateDto.Title = this._testUpdateContext.Title; // Act - var response = await client.UpdateAsync(historicalContextCreateDto, _tokenStorage.AdminToken); + var response = await client.UpdateAsync(historicalContextCreateDto, this._tokenStorage.AdminToken); // Assert Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); From 25f852958042ae057371eb4394b9485f7a3df3c4 Mon Sep 17 00:00:00 2001 From: Dmytro Date: Thu, 2 May 2024 11:49:33 +0300 Subject: [PATCH 21/25] merged with release, should fix problems --- .../HistoricalContextControllerTests.cs | 26 +++++++++---------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/Streetcode/Streetcode.XIntegrationTest/ControllerTests/Timeline/HistoricalContextControllerTests.cs b/Streetcode/Streetcode.XIntegrationTest/ControllerTests/Timeline/HistoricalContextControllerTests.cs index 1468fa5b0..db3a2326f 100644 --- a/Streetcode/Streetcode.XIntegrationTest/ControllerTests/Timeline/HistoricalContextControllerTests.cs +++ b/Streetcode/Streetcode.XIntegrationTest/ControllerTests/Timeline/HistoricalContextControllerTests.cs @@ -96,7 +96,7 @@ public async Task Create_ReturnsSuccessStatusCode() var historicalContextCreateDto = ExtractCreateTestHistoricalContext.HistoricalContextForTest; // Act - var response = await client.CreateAsync(historicalContextCreateDto, _tokenStorage.AdminToken); + var response = await client.CreateAsync(historicalContextCreateDto, _tokenStorage.AdminAccessToken); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -124,7 +124,7 @@ public async Task Create_NotAdminTokenPassed_ReturnsForbidden() var historicalContextCreateDto = ExtractCreateTestHistoricalContext.HistoricalContextForTest; // Act - var response = await client.CreateAsync(historicalContextCreateDto, _tokenStorage.UserToken); + var response = await client.CreateAsync(historicalContextCreateDto, _tokenStorage.UserAccessToken); // Assert Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); @@ -139,7 +139,7 @@ public async Task Create_CreatesNewHistoricalContext() var historicalContextCreateDto = ExtractCreateTestHistoricalContext.HistoricalContextForTest; // Act - var response = await client.CreateAsync(historicalContextCreateDto, _tokenStorage.AdminToken); + var response = await client.CreateAsync(historicalContextCreateDto, _tokenStorage.AdminAccessToken); var getResponse = await client.GetByTitle(historicalContextCreateDto.Title); var fetchedStreetcode = CaseIsensitiveJsonDeserializer.Deserialize(getResponse.Content); @@ -156,7 +156,7 @@ public async Task Create_WithInvalidData_ReturnsBadRequest() historicalContextCreateDto.Title = null; // Invalid data // Act - var response = await client.CreateAsync(historicalContextCreateDto, this._tokenStorage.AdminToken); + var response = await client.CreateAsync(historicalContextCreateDto, this._tokenStorage.AdminAccessToken); // Assert Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); @@ -171,7 +171,7 @@ public async Task Create_WithExistingTag_ReturnsConflict() historicalContextCreateDto.Title = _testCreateContext.Title; // Act - var response = await client.CreateAsync(historicalContextCreateDto, this._tokenStorage.AdminToken); + var response = await client.CreateAsync(historicalContextCreateDto, this._tokenStorage.AdminAccessToken); // Assert Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); @@ -186,7 +186,7 @@ public async Task Update_ReturnSuccessStatusCode() historicalContextCreateDto.Id = this._testCreateContext.Id; // Act - var response = await client.UpdateAsync(historicalContextCreateDto, this._tokenStorage.AdminToken); + var response = await client.UpdateAsync(historicalContextCreateDto, this._tokenStorage.AdminAccessToken); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -200,7 +200,7 @@ public async Task Update_Incorect_ReturnBadRequest() var historicalContextCreateDto = ExtractUpdateTestHistoricalContext.HistoricalContextForTest; // Act - var response = await client.UpdateAsync(historicalContextCreateDto, this._tokenStorage.AdminToken); + var response = await client.UpdateAsync(historicalContextCreateDto, this._tokenStorage.AdminAccessToken); // Assert Assert.Multiple( @@ -230,7 +230,7 @@ public async Task Update_NotAdminTokenPassed_ReturnsForbidden() var historicalContextCreateDto = ExtractUpdateTestHistoricalContext.HistoricalContextForTest; // Act - var response = await client.UpdateAsync(historicalContextCreateDto, this._tokenStorage.UserToken); + var response = await client.UpdateAsync(historicalContextCreateDto, this._tokenStorage.UserAccessToken); // Assert Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); @@ -245,7 +245,7 @@ public async Task Update_WithInvalidData_ReturnsBadRequest() historicalContextCreateDto.Title = null; // Invalid data // Act - var response = await client.UpdateAsync(historicalContextCreateDto, this._tokenStorage.AdminToken); + var response = await client.UpdateAsync(historicalContextCreateDto, this._tokenStorage.AdminAccessToken); // Assert Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); @@ -261,7 +261,7 @@ public async Task Update_WithExistingTitle_ReturnsBadRequest() historicalContextCreateDto.Title = this._testUpdateContext.Title; // Act - var response = await client.UpdateAsync(historicalContextCreateDto, this._tokenStorage.AdminToken); + var response = await client.UpdateAsync(historicalContextCreateDto, this._tokenStorage.AdminAccessToken); // Assert Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); @@ -312,7 +312,7 @@ public async Task Delete_ReturnsSuccessStatusCode() int id = this._testCreateContext.Id; // Act - var response = await this.client.Delete(id, this._tokenStorage.AdminToken); + var response = await this.client.Delete(id, this._tokenStorage.AdminAccessToken); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -338,7 +338,7 @@ public async Task Delete_NotAdminTokenPassed_ReturnsForbidden() int id = this._testCreateContext.Id; // Act - var response = await this.client.Delete(id, this._tokenStorage.UserToken); + var response = await this.client.Delete(id, this._tokenStorage.UserAccessToken); // Assert Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); @@ -351,7 +351,7 @@ public async Task Delete_WithInvalidData_ReturnsBadRequest() int id = -100; // Act - var response = await this.client.Delete(id, this._tokenStorage.AdminToken); + var response = await this.client.Delete(id, this._tokenStorage.AdminAccessToken); // Assert Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); From 44db69a0d56161ffd489037784b07fa4e837b358 Mon Sep 17 00:00:00 2001 From: Dmytro Date: Thu, 2 May 2024 11:57:46 +0300 Subject: [PATCH 22/25] returned connectionString --- Streetcode/Streetcode.WebApi/appsettings.IntegrationTests.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Streetcode/Streetcode.WebApi/appsettings.IntegrationTests.json b/Streetcode/Streetcode.WebApi/appsettings.IntegrationTests.json index 738bd773b..600620bd4 100644 --- a/Streetcode/Streetcode.WebApi/appsettings.IntegrationTests.json +++ b/Streetcode/Streetcode.WebApi/appsettings.IntegrationTests.json @@ -1,6 +1,6 @@ { "ConnectionStrings": { - "DefaultConnection": "Server=localhost;Database=Streetcode_IntegrationTests_Db;User Id=sa;Password=sdlLKMCD234!@#lkcmds;MultipleActiveResultSets=True;TrustServerCertificate=true" + "DefaultConnection": "Server=localhost,1455;Database=Streetcode_IntegrationTests_Db;User Id=sa;Password=sdlLKMCD234!@#lkcmds;MultipleActiveResultSets=True;TrustServerCertificate=true" }, "Blob": { "BlobStoreKey": "BigThirtyTwoBiteCoolTestKeyCrypt", From 4c28b426ba816f1fa32679ecfecd4e60fc06ea05 Mon Sep 17 00:00:00 2001 From: VladyslavPavlysko Date: Wed, 8 May 2024 18:43:44 +0300 Subject: [PATCH 23/25] default string --- Streetcode/Streetcode.WebApi/appsettings.Local.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Streetcode/Streetcode.WebApi/appsettings.Local.json b/Streetcode/Streetcode.WebApi/appsettings.Local.json index 7a665d789..14b44479d 100644 --- a/Streetcode/Streetcode.WebApi/appsettings.Local.json +++ b/Streetcode/Streetcode.WebApi/appsettings.Local.json @@ -1,6 +1,6 @@ { "ConnectionStrings": { - "DefaultConnection": "Server=PC;Database=Streetcode1;MultipleActiveResultSets=True;TrustServerCertificate=true;Trusted_Connection=true" + "DefaultConnection": "Server=127.0.0.1;Database=StreetcodeDb;User Id=sa;Password=Admin@1234;MultipleActiveResultSets=true" }, "CORS": { "AllowedOrigins": [ "http://localhost:3000" ], From bd9116c6a25b808df61e3b85a8dc669e41b8d03f Mon Sep 17 00:00:00 2001 From: VladyslavPavlysko Date: Wed, 8 May 2024 21:57:47 +0300 Subject: [PATCH 24/25] fix tag tests --- .../AdditionalContent/TagControllerTests.cs | 34 +++++++++---------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/Streetcode/Streetcode.XIntegrationTest/ControllerTests/AdditionalContent/TagControllerTests.cs b/Streetcode/Streetcode.XIntegrationTest/ControllerTests/AdditionalContent/TagControllerTests.cs index 315bc6a00..c61d09c16 100644 --- a/Streetcode/Streetcode.XIntegrationTest/ControllerTests/AdditionalContent/TagControllerTests.cs +++ b/Streetcode/Streetcode.XIntegrationTest/ControllerTests/AdditionalContent/TagControllerTests.cs @@ -40,7 +40,7 @@ public class TagControllerTests : BaseAuthorizationControllerTests, I public TagControllerTests(CustomWebApplicationFactory factory, TokenStorage tokenStorage) : base(factory, "/api/Tag", tokenStorage) { - int uniqueId = UniqueNumberGenerator.Generate(); + int uniqueId = UniqueNumberGenerator.GenerateInt(); this._testCreateTag = TagExtracter.Extract(uniqueId, Guid.NewGuid().ToString()); this._testUpdateTag = TagExtracter.Extract(uniqueId, Guid.NewGuid().ToString()); this._testStreetcodeContent = StreetcodeContentExtracter @@ -186,7 +186,7 @@ public async Task Create_ReturnsSuccessStatusCode() var tagCreateDTO = ExtractCreateTestTag.TagForTest; // Act - var response = await client.CreateAsync(tagCreateDTO, _tokenStorage.AdminToken); + var response = await client.CreateAsync(tagCreateDTO, _tokenStorage.AdminAccessToken); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -237,13 +237,13 @@ public async Task Create_TokenNotPassed_ReturnsUnauthorized() [Fact] [ExtractCreateTestTag] - public async Task Create_NotAdminTokenPassed_ReturnsForbidden() + public async Task Create_NotAdminAccessTokenPassed_ReturnsForbidden() { // Arrange var tagCreateDTO = ExtractCreateTestTag.TagForTest; // Act - var response = await client.CreateAsync(tagCreateDTO, _tokenStorage.UserToken); + var response = await client.CreateAsync(tagCreateDTO, _tokenStorage.UserAccessToken); // Assert Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); @@ -258,7 +258,7 @@ public async Task Create_CreatesNewTag() var tagCreateDTO = ExtractCreateTestTag.TagForTest; // Act - var response = await client.CreateAsync(tagCreateDTO, _tokenStorage.AdminToken); + var response = await client.CreateAsync(tagCreateDTO, _tokenStorage.AdminAccessToken); var getResponse = await client.GetTagByTitle(tagCreateDTO.Title); var fetchedStreetcode = CaseIsensitiveJsonDeserializer.Deserialize(getResponse.Content); @@ -275,7 +275,7 @@ public async Task Create_WithInvalidData_ReturnsBadRequest() tagCreateDTO.Title = null; // Invalid data // Act - var response = await client.CreateAsync(tagCreateDTO, _tokenStorage.AdminToken); + var response = await client.CreateAsync(tagCreateDTO, _tokenStorage.AdminAccessToken); // Assert Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); @@ -290,7 +290,7 @@ public async Task Create_WithExistingTag_ReturnsConflict() tagCreateDTO.Title = _testCreateTag.Title; // Act - var response = await client.CreateAsync(tagCreateDTO, _tokenStorage.AdminToken); + var response = await client.CreateAsync(tagCreateDTO, _tokenStorage.AdminAccessToken); // Assert Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); @@ -305,7 +305,7 @@ public async Task Update_ReturnSuccessStatusCode() tagUpdateDTO.Id = this._testCreateTag.Id; // Act - var response = await client.UpdateAsync(tagUpdateDTO, _tokenStorage.AdminToken); + var response = await client.UpdateAsync(tagUpdateDTO, _tokenStorage.AdminAccessToken); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -319,7 +319,7 @@ public async Task Update_Incorect_ReturnBadRequest() var tagUpdateDTO = ExtractUpdateTestTag.TagForTest; // Act - var response = await client.UpdateAsync(tagUpdateDTO, _tokenStorage.AdminToken); + var response = await client.UpdateAsync(tagUpdateDTO, _tokenStorage.AdminAccessToken); // Assert Assert.Multiple( @@ -343,13 +343,13 @@ public async Task Update_TokenNotPassed_ReturnsUnauthorized() [Fact] [ExtractUpdateTestTag] - public async Task Update_NotAdminTokenPassed_ReturnsForbidden() + public async Task Update_NotAdminAccessTokenPassed_ReturnsForbidden() { // Arrange var tagUpdateDTO = ExtractUpdateTestTag.TagForTest; // Act - var response = await client.UpdateAsync(tagUpdateDTO, _tokenStorage.UserToken); + var response = await client.UpdateAsync(tagUpdateDTO, _tokenStorage.UserAccessToken); // Assert Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); @@ -364,7 +364,7 @@ public async Task Update_WithInvalidData_ReturnsBadRequest() tagUpdateDTO.Title = null; // Invalid data // Act - var response = await client.UpdateAsync(tagUpdateDTO, _tokenStorage.AdminToken); + var response = await client.UpdateAsync(tagUpdateDTO, _tokenStorage.AdminAccessToken); // Assert Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); @@ -380,7 +380,7 @@ public async Task Update_WithExistingTitle_ReturnsBadRequest() tagUpdateDTO.Title = this._testUpdateTag.Title; // Act - var response = await client.UpdateAsync(tagUpdateDTO, _tokenStorage.AdminToken); + var response = await client.UpdateAsync(tagUpdateDTO, _tokenStorage.AdminAccessToken); // Assert Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); @@ -431,7 +431,7 @@ public async Task Delete_ReturnsSuccessStatusCode() int id = this._testCreateTag.Id; // Act - var response = await this.client.Delete(id, this._tokenStorage.AdminToken); + var response = await this.client.Delete(id, this._tokenStorage.AdminAccessToken); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -451,13 +451,13 @@ public async Task Delete_TokenNotPassed_ReturnsUnathorized() } [Fact] - public async Task Delete_NotAdminTokenPassed_ReturnsForbidden() + public async Task Delete_NotAdminAccessTokenPassed_ReturnsForbidden() { // Arrange int id = this._testCreateTag.Id; // Act - var response = await this.client.Delete(id, this._tokenStorage.UserToken); + var response = await this.client.Delete(id, this._tokenStorage.UserAccessToken); // Assert Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); @@ -470,7 +470,7 @@ public async Task Delete_WithInvalidData_ReturnsBadRequest() int id = -100; // Act - var response = await this.client.Delete(id, this._tokenStorage.AdminToken); + var response = await this.client.Delete(id, this._tokenStorage.AdminAccessToken); // Assert Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); From 3be0093b8431dc5ee978a3fe97b48faf4e2cacd4 Mon Sep 17 00:00:00 2001 From: Dmytro Date: Sun, 12 May 2024 11:25:39 +0300 Subject: [PATCH 25/25] removed unnecessary coma that caused problems with launching local project --- Streetcode/Streetcode.WebApi/Properties/launchSettings.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Streetcode/Streetcode.WebApi/Properties/launchSettings.json b/Streetcode/Streetcode.WebApi/Properties/launchSettings.json index 027b0cda4..94ac9719a 100644 --- a/Streetcode/Streetcode.WebApi/Properties/launchSettings.json +++ b/Streetcode/Streetcode.WebApi/Properties/launchSettings.json @@ -5,7 +5,7 @@ "launchBrowser": false, "environmentVariables": { "STREETCODE_ENVIRONMENT": "Local", - "ASPNETCORE_ENVIRONMENT": "Local", + "ASPNETCORE_ENVIRONMENT": "Local" }, "dotnetRunMessages": true, "applicationUrl": "http://localhost:5000;https://localhost:5001"