From 0c7f3bce90a8326d6183fa55c872ad24c7ec09a9 Mon Sep 17 00:00:00 2001 From: Sergey Gut Date: Mon, 28 Sep 2026 09:38:31 +0400 Subject: [PATCH] chore: tests --- README.md | 53 +++++++- .../Domain/CollectionInviteTests.cs | 88 +++++++++++++ ...ceptCollectionInviteCommandHandlerTests.cs | 121 ++++++++++++++++++ ...eateCollectionInviteCommandHandlerTests.cs | 72 +++++++++++ ...vokeCollectionInviteCommandHandlerTests.cs | 92 +++++++++++++ 5 files changed, 425 insertions(+), 1 deletion(-) create mode 100644 src/MemeVault.Tests.Unit/Domain/CollectionInviteTests.cs create mode 100644 src/MemeVault.Tests.Unit/Handlers/AcceptCollectionInviteCommandHandlerTests.cs create mode 100644 src/MemeVault.Tests.Unit/Handlers/CreateCollectionInviteCommandHandlerTests.cs create mode 100644 src/MemeVault.Tests.Unit/Handlers/RevokeCollectionInviteCommandHandlerTests.cs diff --git a/README.md b/README.md index da60cb2..08ecb58 100644 --- a/README.md +++ b/README.md @@ -34,7 +34,7 @@ Telegram.Bot 22, MediatR 12, prometheus-net. cp .env.example .env # Заполни: POSTGRES_PASSWORD, TELEGRAM_BOT_TOKEN, JWT_SECRET_KEY -# 3. Запусти всё +# 2. Запусти всё docker compose up -d ``` @@ -48,6 +48,57 @@ docker compose up -d | `TELEGRAM_MODE` | bot | `Polling` (по умолчанию) или `Webhook` | | `Bot__ApiBaseUrl` | bot | URL локального Bot API-сервера (опционально) | +### Генерация секретов + +**JWT_SECRET_KEY** — случайная строка ≥ 32 байт. API использует HMAC-SHA256, +поэтому длина ключа напрямую влияет на стойкость подписи токенов. + +```bash +# Вариант 1 — openssl (рекомендуется, 32 байта → 43 символа base64url) +openssl rand -base64 32 + +# Вариант 2 — PowerShell +[Convert]::ToBase64String((1..32 | % { Get-Random -Max 256 })) + +# Вариант 3 — Python +python3 -c "import secrets; print(secrets.token_urlsafe(32))" +``` + +Результат вставь в `appsettings.json` → `Jwt.SecretKey` или в `.env`: +``` +JWT_SECRET_KEY=сюда_вставь_сгенерированный_ключ +``` + +**POSTGRES_PASSWORD** — любая надёжная строка, например: +```bash +openssl rand -base64 24 +``` + +### Применение миграций (локальная разработка) + +```bash +# Только инфраструктура +docker compose up postgres redis -d + +# Применить все pending-миграции +dotnet ef database update \ + --project src/MemeVault.Infrastructure \ + --startup-project src/MemeVault.Migrator + +# Проверить, что применилось +dotnet ef migrations list \ + --project src/MemeVault.Infrastructure \ + --startup-project src/MemeVault.Migrator +``` + +В production миграции применяет `MemeVault.Migrator` автоматически при старте +через `db.Database.MigrateAsync()`. + +> **Текущие миграции:** +> 1. `Initial` — базовые таблицы: `bot_users`, `collections`, `collection_members`, `media_items` +> 2. `AddCollectionInvites` — убирает `owner_telegram_id` из `collections` (теперь в `collection_members`), +> добавляет `is_inbox`, создаёт таблицу `collection_invites` + ### Пересборка после изменений кода ```bash diff --git a/src/MemeVault.Tests.Unit/Domain/CollectionInviteTests.cs b/src/MemeVault.Tests.Unit/Domain/CollectionInviteTests.cs new file mode 100644 index 0000000..0da8b23 --- /dev/null +++ b/src/MemeVault.Tests.Unit/Domain/CollectionInviteTests.cs @@ -0,0 +1,88 @@ +using MemeVault.Domain.Aggregates.CollectionInvite; +using MemeVault.Domain.Enums; +using MemeVault.Domain.Exceptions; +using Xunit; + +namespace MemeVault.Tests.Unit.Domain; + +public sealed class CollectionInviteTests +{ + private static readonly Guid CollectionId = Guid.NewGuid(); + private const long CreatorId = 42L; + + // ── Create ──────────────────────────────────────────────────────────────── + + [Theory] + [InlineData(CollectionRole.Viewer)] + [InlineData(CollectionRole.Manager)] + public void Create_WithAllowedRole_Succeeds(CollectionRole role) + { + var invite = CollectionInvite.Create(CollectionId, CreatorId, role); + + Assert.Equal(CollectionId, invite.CollectionId); + Assert.Equal(CreatorId, invite.CreatedByTelegramId); + Assert.Equal(role, invite.Role); + Assert.False(invite.IsRevoked); + Assert.Null(invite.RevokedAt); + Assert.NotEqual(Guid.Empty, invite.Id); + } + + [Fact] + public void Create_WithOwnerRole_ThrowsDomainException() + { + Assert.Throws(() => + CollectionInvite.Create(CollectionId, CreatorId, CollectionRole.Owner)); + } + + [Fact] + public void Create_Token_IsNotEmpty() + { + var invite = CollectionInvite.Create(CollectionId, CreatorId, CollectionRole.Viewer); + + Assert.NotEmpty(invite.Token); + } + + [Fact] + public void Create_Token_ContainsNoUnsafeBase64Chars() + { + // Токен используется в URL (deep link), не должен содержать / + = + var invite = CollectionInvite.Create(CollectionId, CreatorId, CollectionRole.Viewer); + + Assert.DoesNotContain("/", invite.Token); + Assert.DoesNotContain("+", invite.Token); + Assert.DoesNotContain("=", invite.Token); + } + + [Fact] + public void Create_TwoInvites_HaveDifferentTokens() + { + var a = CollectionInvite.Create(CollectionId, CreatorId, CollectionRole.Viewer); + var b = CollectionInvite.Create(CollectionId, CreatorId, CollectionRole.Viewer); + + Assert.NotEqual(a.Token, b.Token); + } + + // ── Revoke ──────────────────────────────────────────────────────────────── + + [Fact] + public void Revoke_ActiveInvite_SetsIsRevokedAndRevokedAt() + { + var invite = CollectionInvite.Create(CollectionId, CreatorId, CollectionRole.Viewer); + var before = DateTimeOffset.UtcNow; + + invite.Revoke(); + + Assert.True(invite.IsRevoked); + Assert.NotNull(invite.RevokedAt); + Assert.True(invite.RevokedAt >= before); + } + + [Fact] + public void Revoke_AlreadyRevoked_ThrowsDomainException() + { + var invite = CollectionInvite.Create(CollectionId, CreatorId, CollectionRole.Viewer); + invite.Revoke(); + + Assert.Throws(() => invite.Revoke()); + } +} diff --git a/src/MemeVault.Tests.Unit/Handlers/AcceptCollectionInviteCommandHandlerTests.cs b/src/MemeVault.Tests.Unit/Handlers/AcceptCollectionInviteCommandHandlerTests.cs new file mode 100644 index 0000000..9beeafa --- /dev/null +++ b/src/MemeVault.Tests.Unit/Handlers/AcceptCollectionInviteCommandHandlerTests.cs @@ -0,0 +1,121 @@ +using MemeVault.Application.Commands.AcceptCollectionInvite; +using MemeVault.Application.Common; +using MemeVault.Domain.Aggregates.Collection; +using MemeVault.Domain.Aggregates.CollectionInvite; +using MemeVault.Domain.Enums; +using MemeVault.Domain.Repositories; +using NSubstitute; +using Xunit; + +namespace MemeVault.Tests.Unit.Handlers; + +public sealed class AcceptCollectionInviteCommandHandlerTests +{ + private readonly ICollectionInviteRepository _invites = Substitute.For(); + private readonly ICollectionRepository _collections = Substitute.For(); + private readonly IUnitOfWork _uow = Substitute.For(); + private readonly AcceptCollectionInviteCommandHandler _handler; + + private const long OwnerId = 10L; + private const long GuestId = 30L; + private const long MemberId = 20L; + + public AcceptCollectionInviteCommandHandlerTests() + { + _handler = new AcceptCollectionInviteCommandHandler(_invites, _collections, _uow); + } + + private static CollectionInvite MakeInvite(Collection col, CollectionRole role = CollectionRole.Viewer) + => CollectionInvite.Create(col.Id, OwnerId, role); + + // ── Невалидные токены ───────────────────────────────────────────────────── + + [Fact] + public async Task Handle_TokenNotFound_ReturnsNull() + { + _invites.GetByTokenAsync(Arg.Any(), Arg.Any()) + .Returns((CollectionInvite?)null); + + var result = await _handler.Handle( + new AcceptCollectionInviteCommand("bad-token", GuestId), default); + + Assert.Null(result); + await _collections.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task Handle_RevokedInvite_ReturnsNull() + { + var col = Collection.Create(OwnerId, "Memes"); + var invite = MakeInvite(col); + invite.Revoke(); + + _invites.GetByTokenAsync(invite.Token, Arg.Any()).Returns(invite); + + var result = await _handler.Handle( + new AcceptCollectionInviteCommand(invite.Token, GuestId), default); + + Assert.Null(result); + await _collections.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + } + + // ── Идемпотентность ─────────────────────────────────────────────────────── + + [Fact] + public async Task Handle_AcceptorIsOwner_ReturnsCollectionIdWithoutAddingMember() + { + var col = Collection.Create(OwnerId, "Memes"); + var invite = MakeInvite(col); + + _invites.GetByTokenAsync(invite.Token, Arg.Any()).Returns(invite); + _collections.GetByIdAsync(col.Id, Arg.Any()).Returns(col); + + var result = await _handler.Handle( + new AcceptCollectionInviteCommand(invite.Token, OwnerId), default); + + Assert.Equal(col.Id, result); + // Число участников не изменилось (только owner) + Assert.Single(col.Members); + await _uow.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task Handle_AlreadyMember_ReturnsCollectionIdWithoutDuplicate() + { + var col = Collection.Create(OwnerId, "Memes"); + col.AddMember(MemberId, CollectionRole.Viewer, OwnerId); + var invite = MakeInvite(col); + + _invites.GetByTokenAsync(invite.Token, Arg.Any()).Returns(invite); + _collections.GetByIdAsync(col.Id, Arg.Any()).Returns(col); + + var result = await _handler.Handle( + new AcceptCollectionInviteCommand(invite.Token, MemberId), default); + + Assert.Equal(col.Id, result); + Assert.Equal(2, col.Members.Count); // owner + member, без дублей + await _uow.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + // ── Успешное принятие ───────────────────────────────────────────────────── + + [Theory] + [InlineData(CollectionRole.Viewer)] + [InlineData(CollectionRole.Manager)] + public async Task Handle_ValidAccept_AddsMemberWithCorrectRole(CollectionRole role) + { + var col = Collection.Create(OwnerId, "Memes"); + var invite = MakeInvite(col, role); + + _invites.GetByTokenAsync(invite.Token, Arg.Any()).Returns(invite); + _collections.GetByIdAsync(col.Id, Arg.Any()).Returns(col); + + var result = await _handler.Handle( + new AcceptCollectionInviteCommand(invite.Token, GuestId), default); + + Assert.Equal(col.Id, result); + var newMember = col.Members.Single(m => m.TelegramId == GuestId); + Assert.Equal(role, newMember.Role); + await _uow.Received(1).SaveChangesAsync(Arg.Any()); + } +} diff --git a/src/MemeVault.Tests.Unit/Handlers/CreateCollectionInviteCommandHandlerTests.cs b/src/MemeVault.Tests.Unit/Handlers/CreateCollectionInviteCommandHandlerTests.cs new file mode 100644 index 0000000..400555e --- /dev/null +++ b/src/MemeVault.Tests.Unit/Handlers/CreateCollectionInviteCommandHandlerTests.cs @@ -0,0 +1,72 @@ +using MemeVault.Application.Commands.CreateCollectionInvite; +using MemeVault.Application.Common; +using MemeVault.Domain.Aggregates.Collection; +using MemeVault.Domain.Aggregates.CollectionInvite; +using MemeVault.Domain.Enums; +using MemeVault.Domain.Repositories; +using NSubstitute; +using Xunit; + +namespace MemeVault.Tests.Unit.Handlers; + +public sealed class CreateCollectionInviteCommandHandlerTests +{ + private readonly ICollectionRepository _collections = Substitute.For(); + private readonly ICollectionInviteRepository _invites = Substitute.For(); + private readonly IUnitOfWork _uow = Substitute.For(); + private readonly CreateCollectionInviteCommandHandler _handler; + + private const long OwnerId = 10L; + private const long MemberId = 20L; + + public CreateCollectionInviteCommandHandlerTests() + { + _handler = new CreateCollectionInviteCommandHandler(_collections, _invites, _uow); + } + + [Fact] + public async Task Handle_CollectionNotFound_ReturnsNull() + { + _collections.GetByIdAsync(Arg.Any(), Arg.Any()) + .Returns((Collection?)null); + + var result = await _handler.Handle( + new CreateCollectionInviteCommand(Guid.NewGuid(), OwnerId, CollectionRole.Viewer), default); + + Assert.Null(result); + await _invites.DidNotReceive().AddAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task Handle_RequestedByNonOwner_ReturnsNull() + { + var col = Collection.Create(OwnerId, "Memes"); + col.AddMember(MemberId, CollectionRole.Manager, OwnerId); + _collections.GetByIdAsync(col.Id, Arg.Any()).Returns(col); + + var result = await _handler.Handle( + new CreateCollectionInviteCommand(col.Id, MemberId, CollectionRole.Viewer), default); + + Assert.Null(result); + await _invites.DidNotReceive().AddAsync(Arg.Any(), Arg.Any()); + } + + [Theory] + [InlineData(CollectionRole.Viewer)] + [InlineData(CollectionRole.Manager)] + public async Task Handle_OwnerRequest_CreatesInviteAndReturnsToken(CollectionRole role) + { + var col = Collection.Create(OwnerId, "Memes"); + _collections.GetByIdAsync(col.Id, Arg.Any()).Returns(col); + + var result = await _handler.Handle( + new CreateCollectionInviteCommand(col.Id, OwnerId, role), default); + + Assert.NotNull(result); + Assert.NotEmpty(result); + await _invites.Received(1).AddAsync( + Arg.Is(i => i.CollectionId == col.Id && i.Role == role), + Arg.Any()); + await _uow.Received(1).SaveChangesAsync(Arg.Any()); + } +} diff --git a/src/MemeVault.Tests.Unit/Handlers/RevokeCollectionInviteCommandHandlerTests.cs b/src/MemeVault.Tests.Unit/Handlers/RevokeCollectionInviteCommandHandlerTests.cs new file mode 100644 index 0000000..a885390 --- /dev/null +++ b/src/MemeVault.Tests.Unit/Handlers/RevokeCollectionInviteCommandHandlerTests.cs @@ -0,0 +1,92 @@ +using MemeVault.Application.Commands.RevokeCollectionInvite; +using MemeVault.Application.Common; +using MemeVault.Domain.Aggregates.Collection; +using MemeVault.Domain.Aggregates.CollectionInvite; +using MemeVault.Domain.Enums; +using MemeVault.Domain.Repositories; +using NSubstitute; +using Xunit; + +namespace MemeVault.Tests.Unit.Handlers; + +public sealed class RevokeCollectionInviteCommandHandlerTests +{ + private readonly ICollectionInviteRepository _invites = Substitute.For(); + private readonly ICollectionRepository _collections = Substitute.For(); + private readonly IUnitOfWork _uow = Substitute.For(); + private readonly RevokeCollectionInviteCommandHandler _handler; + + private const long OwnerId = 10L; + private const long MemberId = 20L; + + public RevokeCollectionInviteCommandHandlerTests() + { + _handler = new RevokeCollectionInviteCommandHandler(_invites, _collections, _uow); + } + + [Fact] + public async Task Handle_InviteNotFound_ReturnsFalse() + { + _invites.GetByIdAsync(Arg.Any(), Arg.Any()) + .Returns((CollectionInvite?)null); + + var result = await _handler.Handle( + new RevokeCollectionInviteCommand(Guid.NewGuid(), OwnerId), default); + + Assert.False(result); + await _collections.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task Handle_CollectionNotFound_ReturnsFalse() + { + var col = Collection.Create(OwnerId, "Memes"); + var invite = CollectionInvite.Create(col.Id, OwnerId, CollectionRole.Viewer); + + _invites.GetByIdAsync(invite.Id, Arg.Any()).Returns(invite); + _collections.GetByIdAsync(col.Id, Arg.Any()).Returns((Collection?)null); + + var result = await _handler.Handle( + new RevokeCollectionInviteCommand(invite.Id, OwnerId), default); + + Assert.False(result); + await _uow.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task Handle_RequestedByNonOwner_ReturnsFalse() + { + var col = Collection.Create(OwnerId, "Memes"); + col.AddMember(MemberId, CollectionRole.Manager, OwnerId); + var invite = CollectionInvite.Create(col.Id, OwnerId, CollectionRole.Viewer); + + _invites.GetByIdAsync(invite.Id, Arg.Any()).Returns(invite); + _collections.GetByIdAsync(col.Id, Arg.Any()).Returns(col); + + var result = await _handler.Handle( + new RevokeCollectionInviteCommand(invite.Id, MemberId), default); + + Assert.False(result); + Assert.False(invite.IsRevoked); + await _uow.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task Handle_ValidRevoke_RevokesInviteAndReturnsTrue() + { + var col = Collection.Create(OwnerId, "Memes"); + var invite = CollectionInvite.Create(col.Id, OwnerId, CollectionRole.Viewer); + + _invites.GetByIdAsync(invite.Id, Arg.Any()).Returns(invite); + _collections.GetByIdAsync(col.Id, Arg.Any()).Returns(col); + + var result = await _handler.Handle( + new RevokeCollectionInviteCommand(invite.Id, OwnerId), default); + + Assert.True(result); + Assert.True(invite.IsRevoked); + Assert.NotNull(invite.RevokedAt); + await _invites.Received(1).UpdateAsync(invite, Arg.Any()); + await _uow.Received(1).SaveChangesAsync(Arg.Any()); + } +}