Files
PnvPanel/backend/tests/PnvPanel.Application.Tests/Admin/Maintenance/FactoryResetCommandHandlerTests.cs
T
Leonid Pershin fad03c2834
CI / Backend (build + test) (push) Failing after 1m23s
CI / Frontend (lint + typecheck + build) (push) Successful in 34s
Enhance user plan management and update related endpoints
- Added new configuration options for user plans in `.env.example`, including `Plans__MaxCustomConfigCount` and `Plans__MinCustomConfigCount`.
- Introduced `MapPlanEndpoints` in `Program.cs` to handle plan-related API routes.
- Implemented `SetUserPlan` endpoint in `RoleEndpoints` to allow admins to assign plans to users.
- Removed deprecated role request approval endpoints from `AdminSupportEndpoints`.
- Updated `ITelegramNotifier` and related classes to reflect changes in role request handling and payment notifications.
- Refactored role management commands to remove `MaxConfigs` and focus on `MaxIpLimit` and billing settings.
- Enhanced billing request handling to accommodate plan changes instead of role changes.
- Updated various interfaces and command handlers to support new plan management features.
2026-07-23 22:52:20 +03:00

153 lines
6.1 KiB
C#

using NSubstitute;
using PnvPanel.Application.Admin.Maintenance;
using PnvPanel.Application.Common.Interfaces;
using PnvPanel.Application.Common.Models;
using PnvPanel.Application.Tests.TestSupport;
using PnvPanel.Domain.Audit;
using PnvPanel.Domain.Configs;
using PnvPanel.Domain.Inbounds;
using PnvPanel.Domain.News;
using PnvPanel.Domain.Nodes;
using PnvPanel.Domain.Support;
using Xunit;
namespace PnvPanel.Application.Tests.Admin.Maintenance;
public class FactoryResetCommandHandlerTests
{
private readonly IIdentityService _identityService = Substitute.For<IIdentityService>();
private readonly IRoleService _roleService = Substitute.For<IRoleService>();
private readonly IXuiPanelGateway _gateway = Substitute.For<IXuiPanelGateway>();
private readonly IFileStorage _fileStorage = Substitute.For<IFileStorage>();
private readonly IClientAppCatalogSeeder _catalogSeeder =
Substitute.For<IClientAppCatalogSeeder>();
private readonly IInstructionIntroSeeder _instructionIntroSeeder =
Substitute.For<IInstructionIntroSeeder>();
private readonly IPricingSettingsSeeder _pricingSettingsSeeder =
Substitute.For<IPricingSettingsSeeder>();
[Fact]
public async Task Handle_WipesEverythingExceptCurrentAdminAndSystemRoles()
{
using var dbContext = InMemoryDbContextFactory.Create();
var adminId = Guid.NewGuid();
var otherUserId = Guid.NewGuid();
var node = Node.Register(
"node-1",
new Uri("https://node.example.com"),
new NodeCredentials("u", "p"),
null
);
var inbound = Inbound.FromRemote(node.Id, "1", VpnProtocol.Vless, "remark", 443);
var config = VpnConfig.Create(otherUserId, inbound.Id, VpnProtocol.Vless, "label");
dbContext.Nodes.Add(node);
dbContext.Inbounds.Add(inbound);
dbContext.VpnConfigs.Add(config);
var ticket = SupportTicket.CreateBugReport(otherUserId);
dbContext.SupportTickets.Add(ticket);
var comment = TicketComment.Create(ticket.Id, otherUserId, "текст");
dbContext.TicketComments.Add(comment);
var attachment = TicketAttachment.Create(
comment.Id,
"shot.png",
"stored-name",
"image/png",
10
);
dbContext.TicketAttachments.Add(attachment);
dbContext.NewsPosts.Add(NewsPost.Create("Заголовок", "Текст"));
dbContext.AuditLogs.Add(
AuditLog.Create(adminId, "SomeOldAction", "Test", "1", null, AuditSource.Web)
);
await dbContext.SaveChangesAsync(CancellationToken.None);
var adminRoleId = Guid.NewGuid();
var customRoleId = Guid.NewGuid();
_roleService
.ListRolesAsync(Arg.Any<CancellationToken>())
.Returns(
new List<RoleDto>
{
new(adminRoleId, "admin", -1, IsSystem: true, BillingEnabled: false),
new(customRoleId, "premium", 5, IsSystem: false, BillingEnabled: false),
}
);
_roleService
.DeleteRoleAsync(customRoleId, Arg.Any<CancellationToken>())
.Returns(Result.Success());
_identityService
.ListAllUserIdsExceptAsync(adminId, Arg.Any<CancellationToken>())
.Returns(new List<Guid> { otherUserId });
_identityService
.DeleteUserAsync(otherUserId, Arg.Any<CancellationToken>())
.Returns(Result.Success());
_gateway
.RemoveClientAsync(
Arg.Any<Node>(),
Arg.Any<string>(),
Arg.Any<string>(),
Arg.Any<VpnProtocol>(),
Arg.Any<CancellationToken>()
)
.Returns(Result.Success());
var currentUser = FakeCurrentUser.Authenticated(adminId, "admin");
var handler = new FactoryResetCommandHandler(
dbContext,
_identityService,
_roleService,
_gateway,
_fileStorage,
_catalogSeeder,
_instructionIntroSeeder,
_pricingSettingsSeeder,
currentUser
);
var result = await handler.Handle(new FactoryResetCommand(), CancellationToken.None);
// Хендлер сам коммитит несколько раз (в проде это делает он же, а не диспетчер) — фиксируем финально.
await dbContext.SaveChangesAsync(CancellationToken.None);
Assert.True(result.IsSuccess);
Assert.False(dbContext.VpnConfigs.Any());
Assert.False(dbContext.Inbounds.Any());
Assert.False(dbContext.Nodes.Any());
Assert.False(dbContext.SupportTickets.Any());
Assert.False(dbContext.TicketComments.Any());
Assert.False(dbContext.TicketAttachments.Any());
Assert.False(dbContext.NewsPosts.Any());
// Аудит очищен, но остаётся ровно одна собственная запись о факте сброса.
var auditLog = Assert.Single(dbContext.AuditLogs);
Assert.Equal("FactoryReset", auditLog.Action);
await _identityService
.Received(1)
.DeleteUserAsync(otherUserId, Arg.Any<CancellationToken>());
await _roleService.Received(1).DeleteRoleAsync(customRoleId, Arg.Any<CancellationToken>());
await _roleService
.DidNotReceive()
.DeleteRoleAsync(adminRoleId, Arg.Any<CancellationToken>());
await _gateway
.Received(1)
.RemoveClientAsync(
Arg.Any<Node>(),
inbound.RemoteInboundId,
config.ClientExternalId,
config.Protocol,
Arg.Any<CancellationToken>()
);
await _fileStorage.Received(1).DeleteAsync("stored-name", Arg.Any<CancellationToken>());
await _catalogSeeder.Received(1).SeedIfEmptyAsync(Arg.Any<CancellationToken>());
await _instructionIntroSeeder.Received(1).SeedIfEmptyAsync(Arg.Any<CancellationToken>());
await _pricingSettingsSeeder.Received(1).SeedIfEmptyAsync(Arg.Any<CancellationToken>());
}
}