feat: domain tests

This commit is contained in:
2026-10-07 03:14:37 +04:00
parent 5b694cf25d
commit 9885e570b9
8 changed files with 696 additions and 21 deletions
@@ -0,0 +1,179 @@
using MemeVault.Application.Commands.CloneCollection;
using MemeVault.Application.Common;
using MemeVault.Domain.Aggregates.BotUser;
using MemeVault.Domain.Aggregates.Collection;
using MemeVault.Domain.Aggregates.MediaItem;
using MemeVault.Domain.Enums;
using MemeVault.Domain.Exceptions;
using MemeVault.Domain.Repositories;
using MemeVault.Domain.ValueObjects;
using NSubstitute;
using Xunit;
namespace MemeVault.Tests.Unit.Handlers;
public sealed class CloneCollectionCommandHandlerTests
{
private readonly ICollectionRepository _collections = Substitute.For<ICollectionRepository>();
private readonly IMediaItemRepository _mediaItems = Substitute.For<IMediaItemRepository>();
private readonly IBotUserRepository _users = Substitute.For<IBotUserRepository>();
private readonly IUnitOfWork _uow = Substitute.For<IUnitOfWork>();
private readonly CloneCollectionCommandHandler _handler;
private const long OwnerId = 100L;
private const long UserId = 42L;
public CloneCollectionCommandHandlerTests()
{
_handler = new CloneCollectionCommandHandler(_collections, _mediaItems, _users, _uow);
}
private BotUser MakeUser(Guid? inboxId = null)
{
var user = BotUser.Create(UserId, "cloner", null);
if (inboxId.HasValue)
user.SetInboxCollection(inboxId.Value);
return user;
}
[Fact]
public async Task Handle_SourceNotFound_ReturnsNull()
{
_collections.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns((Collection?)null);
var result = await _handler.Handle(
new CloneCollectionCommand(Guid.NewGuid(), UserId), default);
Assert.Null(result);
await _uow.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task Handle_SourceNotViewable_ReturnsNull()
{
var privateSource = Collection.Create(OwnerId, "Private"); // UserId=42 not a member
_collections.GetByIdAsync(privateSource.Id, Arg.Any<CancellationToken>()).Returns(privateSource);
var result = await _handler.Handle(
new CloneCollectionCommand(privateSource.Id, UserId), default);
Assert.Null(result);
await _uow.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task Handle_QuotaExceeded_ThrowsCollectionQuotaExceededException()
{
var source = Collection.Create(OwnerId, "Source");
source.SetVisibility(CollectionVisibility.Public, OwnerId); // viewable by anyone
_collections.GetByIdAsync(source.Id, Arg.Any<CancellationToken>()).Returns(source);
// User already owns 5 non-inbox collections
var inboxId = Guid.NewGuid();
var owned = Enumerable.Range(0, 5)
.Select(_ => Collection.Create(UserId, "Col"))
.ToList<Collection>();
_collections.GetByOwnerAsync(UserId, Arg.Any<CancellationToken>())
.Returns((IReadOnlyList<Collection>)owned);
var user = MakeUser(inboxId); // inboxId not in owned list → all 5 count toward quota
_users.GetByTelegramIdAsync(UserId, Arg.Any<CancellationToken>()).Returns(user);
await Assert.ThrowsAsync<CollectionQuotaExceededException>(() =>
_handler.Handle(new CloneCollectionCommand(source.Id, UserId), default));
}
[Fact]
public async Task Handle_InboxExcludedFromQuota_DoesNotCountAgainstLimit()
{
var source = Collection.Create(OwnerId, "Source");
source.SetVisibility(CollectionVisibility.Public, OwnerId);
_collections.GetByIdAsync(source.Id, Arg.Any<CancellationToken>()).Returns(source);
// User owns 5 collections, but one of them is the inbox → only 4 count
var owned = Enumerable.Range(0, 5)
.Select(_ => Collection.Create(UserId, "Col"))
.ToList<Collection>();
_collections.GetByOwnerAsync(UserId, Arg.Any<CancellationToken>())
.Returns((IReadOnlyList<Collection>)owned);
var user = MakeUser(owned[0].Id); // first collection is inbox → excluded from count
_users.GetByTelegramIdAsync(UserId, Arg.Any<CancellationToken>()).Returns(user);
_mediaItems.GetByCollectionAsync(source.Id, Arg.Any<CancellationToken>())
.Returns((IReadOnlyList<MediaItem>)[]);
var result = await _handler.Handle(
new CloneCollectionCommand(source.Id, UserId), default);
Assert.NotNull(result); // Should succeed (4 non-inbox < 5 limit)
}
[Fact]
public async Task Handle_ValidClone_CreatesCopyAndReturnsId()
{
var source = Collection.Create(OwnerId, "Meme Pack", "Best memes");
source.SetVisibility(CollectionVisibility.Public, OwnerId);
_collections.GetByIdAsync(source.Id, Arg.Any<CancellationToken>()).Returns(source);
_collections.GetByOwnerAsync(UserId, Arg.Any<CancellationToken>())
.Returns((IReadOnlyList<Collection>)[]);
_users.GetByTelegramIdAsync(UserId, Arg.Any<CancellationToken>())
.Returns(MakeUser());
var photo = MediaItem.Create(OwnerId, source.Id,
MediaSource.FromTelegram("file1"), MediaType.Photo, "funny", "grp1",
[new Tag("meme")]);
_mediaItems.GetByCollectionAsync(source.Id, Arg.Any<CancellationToken>())
.Returns((IReadOnlyList<MediaItem>)[photo]);
var result = await _handler.Handle(
new CloneCollectionCommand(source.Id, UserId), default);
Assert.NotNull(result);
// New collection was added
await _collections.Received(1).AddAsync(
Arg.Is<Collection>(c =>
c.Name == source.Name &&
c.Description == source.Description &&
c.OwnerTelegramId == UserId),
Arg.Any<CancellationToken>());
// One media item was copied with no media group ID
await _mediaItems.Received(1).AddAsync(
Arg.Is<MediaItem>(i =>
i.OwnerTelegramId == UserId &&
i.MediaGroupId == null &&
i.Caption == photo.Caption),
Arg.Any<CancellationToken>());
await _uow.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task Handle_ValidClone_CopiesMultipleItems()
{
var source = Collection.Create(UserId, "My Collection"); // owner clones own collection
_collections.GetByIdAsync(source.Id, Arg.Any<CancellationToken>()).Returns(source);
_collections.GetByOwnerAsync(UserId, Arg.Any<CancellationToken>())
.Returns((IReadOnlyList<Collection>)[]);
_users.GetByTelegramIdAsync(UserId, Arg.Any<CancellationToken>())
.Returns(MakeUser());
var items = new[]
{
MediaItem.Create(UserId, source.Id, MediaSource.FromTelegram("f1"), MediaType.Photo, null),
MediaItem.Create(UserId, source.Id, MediaSource.FromTelegram("f2"), MediaType.Video, "cat"),
MediaItem.Create(UserId, source.Id, MediaSource.FromTelegram("f3"), MediaType.Sticker, null),
};
_mediaItems.GetByCollectionAsync(source.Id, Arg.Any<CancellationToken>())
.Returns((IReadOnlyList<MediaItem>)items);
await _handler.Handle(new CloneCollectionCommand(source.Id, UserId), default);
await _mediaItems.Received(3).AddAsync(Arg.Any<MediaItem>(), Arg.Any<CancellationToken>());
}
}
@@ -26,8 +26,8 @@ public sealed class CopyMediaCommandHandlerTests
_handler = new CopyMediaToCollectionCommandHandler(_mediaItems, _collections, _uow);
}
private static MediaItem MakePhoto() =>
MediaItem.Create(UserId, SrcCollectionId, MediaSource.FromTelegram("f1"), MediaType.Photo, "funny");
private static MediaItem MakePhoto(long ownerId = UserId) =>
MediaItem.Create(ownerId, SrcCollectionId, MediaSource.FromTelegram("f1"), MediaType.Photo, "funny");
[Fact]
public async Task Handle_SourceNotFound_ReturnsNull()
@@ -43,24 +43,49 @@ public sealed class CopyMediaCommandHandlerTests
}
[Fact]
public async Task Handle_SourceWrongOwner_ReturnsNull()
public async Task Handle_SourceCollectionNotViewable_ReturnsNull()
{
var item = MediaItem.Create(999L, SrcCollectionId,
MediaSource.FromTelegram("f1"), MediaType.Photo, null);
// Item belongs to a private collection owned by someone else
var item = MakePhoto(ownerId: 999L);
var privateSourceCol = Collection.Create(999L, "Private"); // UserId=42 is not a member
_mediaItems.GetByIdAsync(item.Id, Arg.Any<CancellationToken>()).Returns(item);
_collections.GetByIdAsync(SrcCollectionId, Arg.Any<CancellationToken>()).Returns(privateSourceCol);
var result = await _handler.Handle(
new CopyMediaToCollectionCommand(item.Id, Guid.NewGuid(), UserId), default);
Assert.Null(result);
await _uow.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task Handle_SourceCollectionInPublicCollection_ReturnsId()
{
// Even a non-owner can copy from a public collection
var item = MakePhoto(ownerId: 999L);
var publicSourceCol = Collection.Create(999L, "Public Memes");
publicSourceCol.SetVisibility(CollectionVisibility.Public, 999L);
var targetCol = Collection.Create(UserId, "Saved");
_mediaItems.GetByIdAsync(item.Id, Arg.Any<CancellationToken>()).Returns(item);
_collections.GetByIdAsync(SrcCollectionId, Arg.Any<CancellationToken>()).Returns(publicSourceCol);
_collections.GetByIdAsync(targetCol.Id, Arg.Any<CancellationToken>()).Returns(targetCol);
var newId = await _handler.Handle(
new CopyMediaToCollectionCommand(item.Id, targetCol.Id, UserId), default);
Assert.NotNull(newId);
}
[Fact]
public async Task Handle_TargetCollectionNotFound_ThrowsDomainException()
{
var item = MakePhoto();
var sourceCol = Collection.Create(UserId, "Source"); // UserId can view own collection
_mediaItems.GetByIdAsync(item.Id, Arg.Any<CancellationToken>()).Returns(item);
_collections.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
_collections.GetByIdAsync(SrcCollectionId, Arg.Any<CancellationToken>()).Returns(sourceCol);
_collections.GetByIdAsync(Arg.Is<Guid>(id => id != SrcCollectionId), Arg.Any<CancellationToken>())
.Returns((Collection?)null);
await Assert.ThrowsAsync<DomainException>(() =>
@@ -72,13 +97,15 @@ public sealed class CopyMediaCommandHandlerTests
public async Task Handle_TargetCollectionWrongOwner_ThrowsDomainException()
{
var item = MakePhoto();
var alienCol = Collection.Create(999L, "Alien");
var sourceCol = Collection.Create(UserId, "Source");
var alienTargetCol = Collection.Create(999L, "Alien");
_mediaItems.GetByIdAsync(item.Id, Arg.Any<CancellationToken>()).Returns(item);
_collections.GetByIdAsync(alienCol.Id, Arg.Any<CancellationToken>()).Returns(alienCol);
_collections.GetByIdAsync(SrcCollectionId, Arg.Any<CancellationToken>()).Returns(sourceCol);
_collections.GetByIdAsync(alienTargetCol.Id, Arg.Any<CancellationToken>()).Returns(alienTargetCol);
await Assert.ThrowsAsync<DomainException>(() =>
_handler.Handle(
new CopyMediaToCollectionCommand(item.Id, alienCol.Id, UserId), default));
new CopyMediaToCollectionCommand(item.Id, alienTargetCol.Id, UserId), default));
}
[Fact]
@@ -86,8 +113,10 @@ public sealed class CopyMediaCommandHandlerTests
{
var item = MakePhoto();
item.AddTag(new Tag("meme"));
var sourceCol = Collection.Create(UserId, "Source");
var targetCol = Collection.Create(UserId, "Saved");
_mediaItems.GetByIdAsync(item.Id, Arg.Any<CancellationToken>()).Returns(item);
_collections.GetByIdAsync(SrcCollectionId, Arg.Any<CancellationToken>()).Returns(sourceCol);
_collections.GetByIdAsync(targetCol.Id, Arg.Any<CancellationToken>()).Returns(targetCol);
var newId = await _handler.Handle(
@@ -99,8 +128,7 @@ public sealed class CopyMediaCommandHandlerTests
await _mediaItems.Received(1).AddAsync(
Arg.Is<MediaItem>(i =>
i.CollectionId == targetCol.Id &&
i.Caption == item.Caption &&
i.OwnerTelegramId == UserId),
i.Caption == item.Caption),
Arg.Any<CancellationToken>());
await _uow.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
@@ -49,7 +49,7 @@ public sealed class DeleteCollectionCommandHandlerTests
}
[Fact]
public async Task Handle_InboxCollection_ThrowsDomainException()
public async Task Handle_InboxCollection_ThrowsInboxProtectionException()
{
var col = Collection.Create(UserId, "Inbox");
_collections.GetByIdAsync(col.Id, Arg.Any<CancellationToken>()).Returns(col);
@@ -58,7 +58,7 @@ public sealed class DeleteCollectionCommandHandlerTests
user.SetInboxCollection(col.Id);
_users.GetByTelegramIdAsync(UserId, Arg.Any<CancellationToken>()).Returns(user);
await Assert.ThrowsAsync<DomainException>(() =>
await Assert.ThrowsAsync<InboxProtectionException>(() =>
_handler.Handle(new DeleteCollectionCommand(col.Id, UserId), default));
}
@@ -0,0 +1,115 @@
using MemeVault.Application.Commands.DeleteMedia;
using MemeVault.Application.Common;
using MemeVault.Domain.Aggregates.Collection;
using MemeVault.Domain.Aggregates.MediaItem;
using MemeVault.Domain.Enums;
using MemeVault.Domain.Exceptions;
using MemeVault.Domain.Repositories;
using MemeVault.Domain.ValueObjects;
using NSubstitute;
using Xunit;
namespace MemeVault.Tests.Unit.Handlers;
public sealed class DeleteMediaCommandHandlerTests
{
private readonly IMediaItemRepository _mediaItems = Substitute.For<IMediaItemRepository>();
private readonly ICollectionRepository _collections = Substitute.For<ICollectionRepository>();
private readonly IUnitOfWork _uow = Substitute.For<IUnitOfWork>();
private readonly DeleteMediaCommandHandler _handler;
private const long UserId = 42L;
private static readonly Guid CollectionId = Guid.NewGuid();
public DeleteMediaCommandHandlerTests()
{
_handler = new DeleteMediaCommandHandler(_mediaItems, _collections, _uow);
}
private static MediaItem MakePhoto() =>
MediaItem.Create(UserId, CollectionId, MediaSource.FromTelegram("file1"), MediaType.Photo, null);
[Fact]
public async Task Handle_ItemNotFound_CompletesWithoutRemove()
{
_mediaItems.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns((MediaItem?)null);
// Should not throw
await _handler.Handle(new DeleteMediaCommand(Guid.NewGuid(), UserId), default);
await _mediaItems.DidNotReceive().RemoveAsync(Arg.Any<MediaItem>(), Arg.Any<CancellationToken>());
await _uow.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task Handle_NoWriteAccess_ThrowsDomainException()
{
var item = MakePhoto();
// Collection is owned by someone else — UserId=42 has no write access
var alienCol = Collection.Create(999L, "Alien");
_mediaItems.GetByIdAsync(item.Id, Arg.Any<CancellationToken>()).Returns(item);
_collections.GetByIdAsync(CollectionId, Arg.Any<CancellationToken>()).Returns(alienCol);
await Assert.ThrowsAsync<DomainException>(() =>
_handler.Handle(new DeleteMediaCommand(item.Id, UserId), default));
await _mediaItems.DidNotReceive().RemoveAsync(Arg.Any<MediaItem>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task Handle_CollectionNotFound_ThrowsDomainException()
{
var item = MakePhoto();
_mediaItems.GetByIdAsync(item.Id, Arg.Any<CancellationToken>()).Returns(item);
_collections.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns((Collection?)null);
await Assert.ThrowsAsync<DomainException>(() =>
_handler.Handle(new DeleteMediaCommand(item.Id, UserId), default));
}
[Fact]
public async Task Handle_ValidRequest_RemovesItemAndSaves()
{
var item = MakePhoto();
var ownedCol = Collection.Create(UserId, "My Memes");
_mediaItems.GetByIdAsync(item.Id, Arg.Any<CancellationToken>()).Returns(item);
_collections.GetByIdAsync(CollectionId, Arg.Any<CancellationToken>()).Returns(ownedCol);
await _handler.Handle(new DeleteMediaCommand(item.Id, UserId), default);
await _mediaItems.Received(1).RemoveAsync(item, Arg.Any<CancellationToken>());
await _uow.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task Handle_ManagerCanDelete_RemovesItemAndSaves()
{
var item = MakePhoto();
// Collection owned by someone else, but UserId=42 is a Manager
var col = Collection.Create(999L, "Shared");
col.AddMember(UserId, CollectionRole.Manager, 999L);
_mediaItems.GetByIdAsync(item.Id, Arg.Any<CancellationToken>()).Returns(item);
_collections.GetByIdAsync(CollectionId, Arg.Any<CancellationToken>()).Returns(col);
await _handler.Handle(new DeleteMediaCommand(item.Id, UserId), default);
await _mediaItems.Received(1).RemoveAsync(item, Arg.Any<CancellationToken>());
await _uow.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task Handle_ViewerCannotDelete_ThrowsDomainException()
{
var item = MakePhoto();
// UserId=42 is only a Viewer — not enough to write
var col = Collection.Create(999L, "Shared");
col.AddMember(UserId, CollectionRole.Viewer, 999L);
_mediaItems.GetByIdAsync(item.Id, Arg.Any<CancellationToken>()).Returns(item);
_collections.GetByIdAsync(CollectionId, Arg.Any<CancellationToken>()).Returns(col);
await Assert.ThrowsAsync<DomainException>(() =>
_handler.Handle(new DeleteMediaCommand(item.Id, UserId), default));
}
}
@@ -0,0 +1,109 @@
using MemeVault.Application.Commands.JoinPublicCollection;
using MemeVault.Application.Common;
using MemeVault.Domain.Aggregates.Collection;
using MemeVault.Domain.Enums;
using MemeVault.Domain.Exceptions;
using MemeVault.Domain.Repositories;
using NSubstitute;
using Xunit;
namespace MemeVault.Tests.Unit.Handlers;
public sealed class JoinPublicCollectionCommandHandlerTests
{
private readonly ICollectionRepository _collections = Substitute.For<ICollectionRepository>();
private readonly IUnitOfWork _uow = Substitute.For<IUnitOfWork>();
private readonly JoinPublicCollectionCommandHandler _handler;
private const long OwnerId = 100L;
private const long UserId = 42L;
public JoinPublicCollectionCommandHandlerTests()
{
_handler = new JoinPublicCollectionCommandHandler(_collections, _uow);
}
[Fact]
public async Task Handle_CollectionNotFound_ReturnsFalse()
{
_collections.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns((Collection?)null);
var result = await _handler.Handle(
new JoinPublicCollectionCommand(Guid.NewGuid(), UserId), default);
Assert.False(result);
await _uow.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task Handle_PrivateCollection_ThrowsDomainException()
{
var col = Collection.Create(OwnerId, "Private"); // Visibility = Private by default
_collections.GetByIdAsync(col.Id, Arg.Any<CancellationToken>()).Returns(col);
await Assert.ThrowsAsync<DomainException>(() =>
_handler.Handle(new JoinPublicCollectionCommand(col.Id, UserId), default));
}
[Fact]
public async Task Handle_LinkOnlyCollection_ThrowsDomainException()
{
var col = Collection.Create(OwnerId, "LinkOnly");
col.SetVisibility(CollectionVisibility.LinkOnly, OwnerId);
_collections.GetByIdAsync(col.Id, Arg.Any<CancellationToken>()).Returns(col);
await Assert.ThrowsAsync<DomainException>(() =>
_handler.Handle(new JoinPublicCollectionCommand(col.Id, UserId), default));
}
[Fact]
public async Task Handle_PublicCollection_NewUser_ReturnsTrue_UpdatesCalled()
{
var col = Collection.Create(OwnerId, "Public Memes");
col.SetVisibility(CollectionVisibility.Public, OwnerId);
_collections.GetByIdAsync(col.Id, Arg.Any<CancellationToken>()).Returns(col);
var result = await _handler.Handle(
new JoinPublicCollectionCommand(col.Id, UserId), default);
Assert.True(result);
Assert.NotNull(col.GetRole(UserId)); // user was added
Assert.Equal(CollectionRole.Viewer, col.GetRole(UserId));
await _collections.Received(1).UpdateAsync(col, Arg.Any<CancellationToken>());
await _uow.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task Handle_PublicCollection_AlreadyMember_ReturnsTrueNoUpdate()
{
var col = Collection.Create(OwnerId, "Public Memes");
col.SetVisibility(CollectionVisibility.Public, OwnerId);
col.TryAcceptInvite(UserId, CollectionRole.Viewer); // already a member
_collections.GetByIdAsync(col.Id, Arg.Any<CancellationToken>()).Returns(col);
var result = await _handler.Handle(
new JoinPublicCollectionCommand(col.Id, UserId), default);
// Handler returns true (joined is "success", idempotent)
Assert.True(result);
// No update since user was already a member
await _collections.DidNotReceive().UpdateAsync(Arg.Any<Collection>(), Arg.Any<CancellationToken>());
await _uow.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task Handle_Owner_JoinsOwnPublicCollection_ReturnsTrueNoUpdate()
{
// Owner is already a member — TryJoinPublic should be idempotent
var col = Collection.Create(OwnerId, "Public Memes");
col.SetVisibility(CollectionVisibility.Public, OwnerId);
_collections.GetByIdAsync(col.Id, Arg.Any<CancellationToken>()).Returns(col);
var result = await _handler.Handle(
new JoinPublicCollectionCommand(col.Id, OwnerId), default);
Assert.True(result);
await _collections.DidNotReceive().UpdateAsync(Arg.Any<Collection>(), Arg.Any<CancellationToken>());
}
}
@@ -0,0 +1,125 @@
using MemeVault.Application.Commands.RegenerateShareLink;
using MemeVault.Application.Common;
using MemeVault.Domain.Aggregates.Collection;
using MemeVault.Domain.Enums;
using MemeVault.Domain.Exceptions;
using MemeVault.Domain.Repositories;
using NSubstitute;
using Xunit;
namespace MemeVault.Tests.Unit.Handlers;
public sealed class RegenerateShareLinkCommandHandlerTests
{
private readonly ICollectionRepository _collections = Substitute.For<ICollectionRepository>();
private readonly IUnitOfWork _uow = Substitute.For<IUnitOfWork>();
private readonly RegenerateShareLinkCommandHandler _handler;
private const long OwnerId = 100L;
private const long ManagerId = 42L;
private const long ViewerId = 7L;
public RegenerateShareLinkCommandHandlerTests()
{
_handler = new RegenerateShareLinkCommandHandler(_collections, _uow);
}
private Collection MakeLinkOnlyCollection()
{
var col = Collection.Create(OwnerId, "Shared");
col.SetVisibility(CollectionVisibility.LinkOnly, OwnerId);
return col;
}
[Fact]
public async Task Handle_CollectionNotFound_ReturnsNull()
{
_collections.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns((Collection?)null);
var result = await _handler.Handle(
new RegenerateShareLinkCommand(Guid.NewGuid(), OwnerId), default);
Assert.Null(result);
await _uow.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task Handle_PrivateCollection_ThrowsDomainException()
{
var col = Collection.Create(OwnerId, "Private"); // Visibility = Private
_collections.GetByIdAsync(col.Id, Arg.Any<CancellationToken>()).Returns(col);
await Assert.ThrowsAsync<DomainException>(() =>
_handler.Handle(new RegenerateShareLinkCommand(col.Id, OwnerId), default));
}
[Fact]
public async Task Handle_InsufficientRole_ThrowsInsufficientPermissionException()
{
var col = MakeLinkOnlyCollection();
col.AddMember(ViewerId, CollectionRole.Viewer, OwnerId);
_collections.GetByIdAsync(col.Id, Arg.Any<CancellationToken>()).Returns(col);
await Assert.ThrowsAsync<InsufficientPermissionException>(() =>
_handler.Handle(new RegenerateShareLinkCommand(col.Id, ViewerId), default));
}
[Fact]
public async Task Handle_NotMember_ThrowsInsufficientPermissionException()
{
var col = MakeLinkOnlyCollection();
_collections.GetByIdAsync(col.Id, Arg.Any<CancellationToken>()).Returns(col);
await Assert.ThrowsAsync<InsufficientPermissionException>(() =>
_handler.Handle(new RegenerateShareLinkCommand(col.Id, ViewerId), default));
}
[Fact]
public async Task Handle_OwnerOnLinkOnlyCollection_ReturnsNewToken()
{
var col = MakeLinkOnlyCollection();
var oldToken = col.ShareToken;
_collections.GetByIdAsync(col.Id, Arg.Any<CancellationToken>()).Returns(col);
var result = await _handler.Handle(
new RegenerateShareLinkCommand(col.Id, OwnerId), default);
Assert.NotNull(result);
Assert.NotEqual(oldToken, result); // token regenerated
Assert.Equal(col.ShareToken, result);
await _collections.Received(1).UpdateAsync(col, Arg.Any<CancellationToken>());
await _uow.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task Handle_ManagerOnPublicCollection_ReturnsNewToken()
{
var col = Collection.Create(OwnerId, "Public");
col.SetVisibility(CollectionVisibility.Public, OwnerId);
col.AddMember(ManagerId, CollectionRole.Manager, OwnerId);
var oldToken = col.ShareToken;
_collections.GetByIdAsync(col.Id, Arg.Any<CancellationToken>()).Returns(col);
var result = await _handler.Handle(
new RegenerateShareLinkCommand(col.Id, ManagerId), default);
Assert.NotNull(result);
Assert.NotEqual(oldToken, result);
await _uow.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task Handle_TokenIsUnique_EachCallProducesDifferentToken()
{
var col = MakeLinkOnlyCollection();
_collections.GetByIdAsync(col.Id, Arg.Any<CancellationToken>()).Returns(col);
var token1 = await _handler.Handle(
new RegenerateShareLinkCommand(col.Id, OwnerId), default);
var token2 = await _handler.Handle(
new RegenerateShareLinkCommand(col.Id, OwnerId), default);
Assert.NotEqual(token1, token2);
}
}
@@ -0,0 +1,98 @@
using MemeVault.Application.Commands.SetCollectionInbox;
using MemeVault.Application.Common;
using MemeVault.Domain.Aggregates.BotUser;
using MemeVault.Domain.Aggregates.Collection;
using MemeVault.Domain.Exceptions;
using MemeVault.Domain.Repositories;
using NSubstitute;
using Xunit;
namespace MemeVault.Tests.Unit.Handlers;
public sealed class SetCollectionInboxCommandHandlerTests
{
private readonly ICollectionRepository _collections = Substitute.For<ICollectionRepository>();
private readonly IBotUserRepository _users = Substitute.For<IBotUserRepository>();
private readonly IUnitOfWork _uow = Substitute.For<IUnitOfWork>();
private readonly SetCollectionInboxCommandHandler _handler;
private const long UserId = 42L;
public SetCollectionInboxCommandHandlerTests()
{
_handler = new SetCollectionInboxCommandHandler(_collections, _users, _uow);
}
[Fact]
public async Task Handle_CollectionNotFound_ReturnsFalse()
{
_collections.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns((Collection?)null);
var result = await _handler.Handle(
new SetCollectionInboxCommand(Guid.NewGuid(), UserId), default);
Assert.False(result);
await _uow.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task Handle_NotOwner_ReturnsFalse()
{
var col = Collection.Create(999L, "Alien Collection"); // owned by 999, not UserId
_collections.GetByIdAsync(col.Id, Arg.Any<CancellationToken>()).Returns(col);
var result = await _handler.Handle(
new SetCollectionInboxCommand(col.Id, UserId), default);
Assert.False(result);
await _uow.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task Handle_UserNotFound_ReturnsFalse()
{
var col = Collection.Create(UserId, "My Collection");
_collections.GetByIdAsync(col.Id, Arg.Any<CancellationToken>()).Returns(col);
_users.GetByTelegramIdAsync(UserId, Arg.Any<CancellationToken>()).Returns((BotUser?)null);
var result = await _handler.Handle(
new SetCollectionInboxCommand(col.Id, UserId), default);
Assert.False(result);
}
[Fact]
public async Task Handle_AlreadyInbox_ThrowsInboxProtectionException()
{
var col = Collection.Create(UserId, "Inbox");
_collections.GetByIdAsync(col.Id, Arg.Any<CancellationToken>()).Returns(col);
var user = BotUser.Create(UserId, "testuser", null);
user.SetInboxCollection(col.Id); // уже является Inbox
_users.GetByTelegramIdAsync(UserId, Arg.Any<CancellationToken>()).Returns(user);
await Assert.ThrowsAsync<InboxProtectionException>(() =>
_handler.Handle(new SetCollectionInboxCommand(col.Id, UserId), default));
}
[Fact]
public async Task Handle_ValidRequest_SetsInboxAndSaves()
{
var oldInbox = Guid.NewGuid();
var newCol = Collection.Create(UserId, "New Inbox");
_collections.GetByIdAsync(newCol.Id, Arg.Any<CancellationToken>()).Returns(newCol);
var user = BotUser.Create(UserId, "testuser", null);
user.SetInboxCollection(oldInbox);
_users.GetByTelegramIdAsync(UserId, Arg.Any<CancellationToken>()).Returns(user);
var result = await _handler.Handle(
new SetCollectionInboxCommand(newCol.Id, UserId), default);
Assert.True(result);
Assert.Equal(newCol.Id, user.InboxCollectionId);
await _users.Received(1).UpdateAsync(user, Arg.Any<CancellationToken>());
await _uow.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
}
@@ -29,6 +29,14 @@ public sealed class UpdateMediaCommandHandlerTests
private static MediaItem MakePhoto() =>
MediaItem.Create(UserId, CollectionId, MediaSource.FromTelegram("f1"), MediaType.Photo, null);
private Collection MakeOwnedCollection()
{
var col = Collection.Create(UserId, "My Collection");
// Use the actual CollectionId field from MakePhoto's output
// The collection returned here has a generated ID; mocking matches by CollectionId
return col;
}
[Fact]
public async Task Handle_ItemNotFound_ReturnsFalse()
{
@@ -43,15 +51,19 @@ public sealed class UpdateMediaCommandHandlerTests
}
[Fact]
public async Task Handle_WrongOwner_ReturnsFalse()
public async Task Handle_NoWriteAccessOnSourceCollection_ReturnsFalse()
{
var item = MakePhoto();
// Source collection is owned by someone else, user 42 has no write access
var alienSourceCol = Collection.Create(999L, "Alien");
_mediaItems.GetByIdAsync(item.Id, Arg.Any<CancellationToken>()).Returns(item);
_collections.GetByIdAsync(CollectionId, Arg.Any<CancellationToken>()).Returns(alienSourceCol);
var result = await _handler.Handle(
new UpdateMediaCommand(item.Id, RequestingTelegramId: 999L, null, []), default);
new UpdateMediaCommand(item.Id, UserId, null, []), default);
Assert.False(result);
await _uow.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
@@ -59,7 +71,9 @@ public sealed class UpdateMediaCommandHandlerTests
{
var item = MakePhoto();
item.AddTag(new Tag("old"));
var sourceCol = Collection.Create(UserId, "My Collection");
_mediaItems.GetByIdAsync(item.Id, Arg.Any<CancellationToken>()).Returns(item);
_collections.GetByIdAsync(CollectionId, Arg.Any<CancellationToken>()).Returns(sourceCol);
var result = await _handler.Handle(
new UpdateMediaCommand(item.Id, UserId, "new caption", ["funny", "cats"]), default);
@@ -75,8 +89,10 @@ public sealed class UpdateMediaCommandHandlerTests
public async Task Handle_WithNewCollectionId_MovesItem()
{
var item = MakePhoto();
var sourceCol = Collection.Create(UserId, "Source");
var newCol = Collection.Create(UserId, "Cats");
_mediaItems.GetByIdAsync(item.Id, Arg.Any<CancellationToken>()).Returns(item);
_collections.GetByIdAsync(CollectionId, Arg.Any<CancellationToken>()).Returns(sourceCol);
_collections.GetByIdAsync(newCol.Id, Arg.Any<CancellationToken>()).Returns(newCol);
var result = await _handler.Handle(
@@ -87,29 +103,34 @@ public sealed class UpdateMediaCommandHandlerTests
}
[Fact]
public async Task Handle_WithSameCollectionId_DoesNotMove()
public async Task Handle_WithSameCollectionId_DoesNotQueryTargetCollection()
{
var item = MakePhoto();
var sourceCol = Collection.Create(UserId, "Source");
_mediaItems.GetByIdAsync(item.Id, Arg.Any<CancellationToken>()).Returns(item);
_collections.GetByIdAsync(CollectionId, Arg.Any<CancellationToken>()).Returns(sourceCol);
// Передаём тот же collectionId — перемещения не должно быть
// Передаём тот же collectionId — запроса за target-коллекцией быть не должно
var result = await _handler.Handle(
new UpdateMediaCommand(item.Id, UserId, null, [], CollectionId: CollectionId), default);
Assert.True(result);
await _collections.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
// Source collection was fetched once; no second lookup for target (same ID)
await _collections.Received(1).GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task Handle_TargetCollectionWrongOwner_ThrowsDomainException()
{
var item = MakePhoto();
var alienCol = Collection.Create(999L, "Alien");
var sourceCol = Collection.Create(UserId, "Source");
var alienTargetCol = Collection.Create(999L, "Alien");
_mediaItems.GetByIdAsync(item.Id, Arg.Any<CancellationToken>()).Returns(item);
_collections.GetByIdAsync(alienCol.Id, Arg.Any<CancellationToken>()).Returns(alienCol);
_collections.GetByIdAsync(CollectionId, Arg.Any<CancellationToken>()).Returns(sourceCol);
_collections.GetByIdAsync(alienTargetCol.Id, Arg.Any<CancellationToken>()).Returns(alienTargetCol);
await Assert.ThrowsAsync<DomainException>(() =>
_handler.Handle(
new UpdateMediaCommand(item.Id, UserId, null, [], CollectionId: alienCol.Id), default));
new UpdateMediaCommand(item.Id, UserId, null, [], CollectionId: alienTargetCol.Id), default));
}
}