Переписаны модули, тесты, обработка ошибок

This commit is contained in:
Халимов Рустам
2026-03-10 21:08:03 +03:00
parent 5c9c6ab975
commit 4e06e48657
126 changed files with 6549 additions and 803 deletions
@@ -0,0 +1,93 @@
using System.Text.Json;
using FluentAssertions;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using NSubstitute;
using Nashel.BuildingBlocks.Application.Exceptions;
using Nashel.Host.Infrastructure.Exceptions;
using Xunit;
namespace Nashel.Host.Tests;
public class GlobalExceptionHandlerTests
{
private readonly ILogger<GlobalExceptionHandler> _logger;
private readonly GlobalExceptionHandler _handler;
public GlobalExceptionHandlerTests()
{
_logger = Substitute.For<ILogger<GlobalExceptionHandler>>();
_handler = new GlobalExceptionHandler(_logger);
}
[Fact]
public async Task TryHandleAsync_Should_Return404_When_NotFoundException()
{
// Arrange (Подготовка)
var context = new DefaultHttpContext();
context.Response.Body = new MemoryStream();
var exception = new NotFoundException("User", "123");
// Act (Действие)
var result = await _handler.TryHandleAsync(context, exception, CancellationToken.None);
// Assert (Проверка)
result.Should().BeTrue();
context.Response.StatusCode.Should().Be(StatusCodes.Status404NotFound);
context.Response.Body.Seek(0, SeekOrigin.Begin);
var responseBody = await new StreamReader(context.Response.Body).ReadToEndAsync();
var problemDetails = JsonSerializer.Deserialize<ProblemDetails>(responseBody, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
problemDetails.Should().NotBeNull();
problemDetails!.Title.Should().Be("Ресурс не найден");
problemDetails.Detail.Should().Contain("User");
problemDetails.Detail.Should().Contain("123");
}
[Fact]
public async Task TryHandleAsync_Should_Return403_When_ForbiddenAccessException()
{
// Arrange (Подготовка)
var context = new DefaultHttpContext();
context.Response.Body = new MemoryStream();
var exception = new ForbiddenAccessException();
// Act (Действие)
var result = await _handler.TryHandleAsync(context, exception, CancellationToken.None);
// Assert (Проверка)
result.Should().BeTrue();
context.Response.StatusCode.Should().Be(StatusCodes.Status403Forbidden);
context.Response.Body.Seek(0, SeekOrigin.Begin);
var responseBody = await new StreamReader(context.Response.Body).ReadToEndAsync();
var problemDetails = JsonSerializer.Deserialize<ProblemDetails>(responseBody, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
problemDetails!.Title.Should().Be("Доступ запрещен");
}
[Fact]
public async Task TryHandleAsync_Should_Return500_When_UnhandledException()
{
// Arrange (Подготовка)
var context = new DefaultHttpContext();
context.Response.Body = new MemoryStream();
var exception = new Exception("Unknown error");
// Act (Действие)
var result = await _handler.TryHandleAsync(context, exception, CancellationToken.None);
// Assert (Проверка)
result.Should().BeTrue();
context.Response.StatusCode.Should().Be(StatusCodes.Status500InternalServerError);
context.Response.Body.Seek(0, SeekOrigin.Begin);
var responseBody = await new StreamReader(context.Response.Body).ReadToEndAsync();
var problemDetails = JsonSerializer.Deserialize<ProblemDetails>(responseBody, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
problemDetails!.Title.Should().Be("Внутренняя ошибка сервера");
problemDetails.Detail.Should().Be("Произошла непредвиденная ошибка на сервере. Пожалуйста, попробуйте позже.");
}
}
@@ -0,0 +1,27 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="FluentAssertions" Version="8.8.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.0.1" />
<PackageReference Include="NSubstitute" Version="5.3.0" />
<PackageReference Include="xunit" Version="2.9.3" />
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.5">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Microsoft.AspNetCore.Http" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.Diagnostics.Abstractions" Version="2.2.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\Host\Nashel.Host.csproj" />
</ItemGroup>
</Project>