Add friendship feature with models, repository, and tests

Introduces Friendship and PrivateChat models, repository interfaces, and implementations for managing friendships. Adds validators and comprehensive unit and integration tests for friendship logic. Updates InviteUserController with new endpoints and restricts access to admin role. Removes unnecessary project references from Govor.API.csproj and registers new DbSets in GovorDbContext.
This commit is contained in:
Artemy
2025-06-27 15:09:28 +07:00
parent 4f3f4ec066
commit 9b9cd73a96
15 changed files with 565 additions and 20 deletions
@@ -96,7 +96,7 @@ public class AdminsRepositoryTests
var repository = new AdminsRepository(context, _validator);
// Act & Assert
Assert.ThrowsAsync<NotFoundByKeyException<Guid>>(async () => await repository.GetByIdAsync(Guid.Empty));
Assert.ThrowsAsync<NotFoundByKeyException<Guid>>(async () => await repository.GetByIdAsync(_fixture.Create<Guid>()));
}
[Test]
@@ -0,0 +1,191 @@
using AutoFixture;
using Govor.Core.Infrastructure.Validators;
using Govor.Core.Models;
using Govor.Data;
using Govor.Data.Repositories;
using Govor.Data.Repositories.Exceptions;
using Microsoft.EntityFrameworkCore;
namespace Govor.API.Tests.IntegrationTests.EF.Repositories;
[TestFixture]
public class FriendshipsRepositoryTests
{
private Fixture _fixture;
private DbContextOptions<GovorDbContext> _options;
private IObjectValidator<Friendship> _validator = new FriendshipValidator();
private int _testIteration = 0;
[SetUp]
public void Setup()
{
_fixture = new Fixture();
_fixture.Behaviors
.OfType<ThrowingRecursionBehavior>()
.ToList()
.ForEach(b => _fixture.Behaviors.Remove(b));
_fixture.Behaviors.Add(new OmitOnRecursionBehavior());
_options = new DbContextOptionsBuilder<GovorDbContext>()
.UseInMemoryDatabase(databaseName: $"DbGovor_{nameof(FriendshipsRepositoryTests)}_{_testIteration}")
.Options;
_testIteration += 1;
}
[Test]
public async Task Given_NotEmptyDbSet_When_GetAllAsync_Then_Friendships_Are_Returned()
{
// Arrange
var random = new Random();
var friendships = _fixture.CreateMany<Friendship>(random.Next(3, 10)).ToList();
await using var context = new GovorDbContext(_options);
var repository = new FriendshipsRepository(context, _validator);
context.AddRange(friendships);
await context.SaveChangesAsync();
// Act
var result = await repository.GetAllAsync();
// Assert
Assert.That(result, Is.Not.Null);
Assert.That(result.Count(), Is.EqualTo(friendships.Count()));
Assert.That(result.Select(r => r.Id), Is.EquivalentTo(friendships.Select(r => r.Id)));
}
[Test]
public async Task Given_EmptyDbSet_When_GetAllAsync_Should_Throw_NotFoundException()
{
// Arrange
await using var context = new GovorDbContext(_options);
var repository = new FriendshipsRepository(context, _validator);
// Act & Assert
Assert.ThrowsAsync<NotFoundException>(async () => await repository.GetAllAsync());
}
[Test]
public async Task Given_ValidFriendshipId_When_GetByIdAsync_Then_Friendships_Are_Returned()
{
// Arrange
var random = new Random();
var friendships = _fixture.CreateMany<Friendship>(random.Next(3, 10)).ToList();
await using var context = new GovorDbContext(_options);
var repository = new FriendshipsRepository(context, _validator);
context.AddRange(friendships);
await context.SaveChangesAsync();
// Act
var result = await repository.GetByIdAsync(friendships.First().Id);
// Assert
Assert.That(result, Is.Not.Null);
Assert.That(result.Id, Is.EqualTo(friendships.First().Id));
}
[Test]
public async Task Given_InvalidFriendshipId_When_GetByIdAsync_Should_Throw_NotFoundByKeyException()
{
// Arrange
await using var context = new GovorDbContext(_options);
var repository = new FriendshipsRepository(context, _validator);
// Act & Assert
Assert.ThrowsAsync<NotFoundByKeyException<Guid>>(async () => await repository.GetByIdAsync(_fixture.Create<Guid>()));
}
[Test]
public async Task Given_ValidUserId_When_GetByIdAsync_Then_Friendships_Are_Returned()
{
// Arrange
var random = new Random();
var friendships = _fixture.CreateMany<Friendship>(random.Next(3, 10)).ToList();
await using var context = new GovorDbContext(_options);
var repository = new FriendshipsRepository(context, _validator);
context.AddRange(friendships);
await context.SaveChangesAsync();
// Act
var result = await repository.FindByUserIdAsync(friendships.First().RequesterId);
// Assert
Assert.That(result, Is.Not.Null);
Assert.That(result.First().Id, Is.EqualTo(friendships.First().Id));
}
[Test]
public async Task Given_InvalidUserId_When_GetByIdAsync_Should_Throw_NotFoundByKeyException()
{
// Arrange
await using var context = new GovorDbContext(_options);
var repository = new FriendshipsRepository(context, _validator);
// Act & Assert
Assert.ThrowsAsync<NotFoundByKeyException<Guid>>(async () => await repository.FindByUserIdAsync(_fixture.Create<Guid>()));
}
[Test]
public async Task Given_ValidFriendship_When_AddAsync_Then_Added()
{
// Arrange
var friendship = _fixture.Create<Friendship>();
await using var context = new GovorDbContext(_options);
var repository = new FriendshipsRepository(context, _validator);
// Act
await repository.AddAsync(friendship);
// Assert
Assert.That(context.Friendships.Count, Is.EqualTo(1));
Assert.That(context.Friendships.First().Id, Is.EqualTo(friendship.Id));
}
[Test]
public async Task Given_InvalidFriendship_When_AddAsync_Should_Throw_AdditionException()
{
// Arrange
await using var context = new GovorDbContext(_options);
var repository = new FriendshipsRepository(context, _validator);
// Act & Assert
Assert.ThrowsAsync<AdditionException>(async () => await repository.AddAsync(default));
}
[Test]
public async Task Given_ExistFriendship_When_Exist_Then_True()
{
// Arrange
var friendship = _fixture.Create<Friendship>();
await using var context = new GovorDbContext(_options);
var repository = new FriendshipsRepository(context, _validator);
context.Friendships.Add(friendship);
await context.SaveChangesAsync();
// Act
var result = repository.Exist(friendship.RequesterId, friendship.AddresseeId);
// Assert
Assert.That(result, Is.True);
}
[Test]
public async Task Given_NotExistFriendship_When_Exist_Then_False()
{
// Arrange
await using var context = new GovorDbContext(_options);
var repository = new FriendshipsRepository(context, _validator);
// Act & Assert
Assert.That(repository.Exist(_fixture.Create<Guid>(), _fixture.Create<Guid>()), Is.False);
}
}
@@ -0,0 +1,70 @@
using AutoFixture;
using Govor.Core.Infrastructure.Validators;
using Govor.Core.Models;
namespace Govor.API.Tests.UnitTests.Infrastructure.Validators;
[TestFixture]
public class FriendshipValidatorTests
{
private IObjectValidator<Friendship> _friendshipValidator;
private Fixture _fixture;
public FriendshipValidatorTests()
{
_friendshipValidator = new FriendshipValidator();
_fixture = new Fixture();
_fixture.Behaviors
.OfType<ThrowingRecursionBehavior>()
.ToList()
.ForEach(b => _fixture.Behaviors.Remove(b));
_fixture.Behaviors.Add(new OmitOnRecursionBehavior());
}
[Test]
public void Given_ValidFriendship_When_Validate_Then_Returns_True()
{
var friendship = _fixture.Create<Friendship>();
// Act & Assert
Assert.DoesNotThrow( () => _friendshipValidator.Validate(friendship));
Assert.That(_friendshipValidator.TryValidate(friendship), Is.True);
}
[Test]
public void Given_EmptyFriendshipId_When_Validate_Then_Returns_False()
{
var friendship = _fixture.Create<Friendship>();
friendship.Id = Guid.Empty;
// Act & Assert
Assert.Throws<InvalidObjectException<Friendship>>( () => _friendshipValidator.Validate(friendship));
Assert.That(_friendshipValidator.TryValidate(friendship), Is.False);
}
[Test]
public void Given_EmptyRequesterId_When_Validate_Then_Returns_False()
{
var friendship = _fixture.Create<Friendship>();
friendship.RequesterId = Guid.Empty;
// Act & Assert
Assert.Throws<InvalidObjectException<Friendship>>( () => _friendshipValidator.Validate(friendship));
Assert.That(_friendshipValidator.TryValidate(friendship), Is.False);
}
[Test]
public void Given_AddresseeId_When_Validate_Then_Returns_False()
{
var friendship = _fixture.Create<Friendship>();
friendship.AddresseeId = Guid.Empty;
// Act & Assert
Assert.Throws<InvalidObjectException<Friendship>>( () => _friendshipValidator.Validate(friendship));
Assert.That(_friendshipValidator.TryValidate(friendship), Is.False);
}
}
@@ -25,7 +25,7 @@ public class InvitationValidatorTests
}
[Test]
public void Given_ValidInvitation_When_Exist_Then_Returns_True()
public void Given_ValidInvitation_When_Validate_Then_Returns_True()
{
var invitation = _fixture.Create<Invitation>();
@@ -35,7 +35,7 @@ public class InvitationValidatorTests
}
[Test]
public void Given_NullInvitation_When_Exist_Then_Returns_False()
public void Given_NullInvitation_When_Validate_Then_Returns_False()
{
// Act & Assert
Assert.Throws<InvalidObjectException<Invitation>>( () => _messageValidator.Validate(default));
@@ -43,7 +43,7 @@ public class InvitationValidatorTests
}
[Test]
public void Given_EmptyInvitationId_When_Exist_Then_Returns_False()
public void Given_EmptyInvitationId_When_Validate_Then_Returns_False()
{
// Arrange
var invitation = _fixture.Create<Invitation>();
@@ -55,7 +55,7 @@ public class InvitationValidatorTests
}
[Test]
public void Given_EmptyInvitationCreationDate_When_Exist_Then_Returns_False()
public void Given_EmptyInvitationCreationDate_When_Validate_Then_Returns_False()
{
// Arrange
var invitation = _fixture.Create<Invitation>();
@@ -67,7 +67,7 @@ public class InvitationValidatorTests
}
[Test]
public void Given_InvalidEndDatesAndIsActive_When_Exist_Then_Returns_False()
public void Given_InvalidEndDatesAndIsActive_When_Validate_Then_Returns_False()
{
// Arrange
var invitation = _fixture.Create<Invitation>();
@@ -79,7 +79,7 @@ public class InvitationValidatorTests
}
[Test]
public void Given_InvalidMaxParticipantsAndIsActive_When_Exist_Then_Returns_False()
public void Given_InvalidMaxParticipantsAndIsActive_When_Validate_Then_Returns_False()
{
// Arrange
var invitation = _fixture.Create<Invitation>();
@@ -92,7 +92,7 @@ public class InvitationValidatorTests
}
[Test]
public void Given_InvalidCode_When_Exist_Then_Returns_False()
public void Given_InvalidCode_When_Validate_Then_Returns_False()
{
// Arrange
var invitation = _fixture.Create<Invitation>();
@@ -9,7 +9,7 @@ namespace Govor.API.Controllers.AdminStuff;
[Route("api/[controller]")]
[ApiController]
[Authorize]
[Authorize(Roles = "Admin")]
public class InviteUserController : Controller
{
private readonly IInvitesRepository _repository;
@@ -44,19 +44,21 @@ public class InviteUserController : Controller
}
}
[HttpGet]
public async Task<IActionResult> GetAllInvitations()
[HttpGet("[action]")]
public async Task<IActionResult> GetAllActiveInvitations()
{
try
{
_logger.LogInformation("Getting all invitations by administrator");
_logger.LogInformation("Getting all active invitations by administrator");
var read = await _repository.GetAllAsync();
var result = read.Where(x => x.IsActive == true).ToList();
List<InvitationDto> dto = new List<InvitationDto>();
List<InvitationDto> dtos = new List<InvitationDto>();
foreach (var inv in read)
foreach (var inv in result)
{
dto.Add(new InvitationDto(){
dtos.Add(new InvitationDto(){
Id = inv.Id,
Description = inv.Description,
IsAdmin = inv.IsAdmin,
@@ -68,7 +70,69 @@ public class InviteUserController : Controller
});
}
return Ok(dto);
return Ok(dtos);
}
catch (Exception e)
{
_logger.LogError(e, e.Message);
return BadRequest($"An error occured: {e.Message}");
}
}
[HttpGet]
public async Task<IActionResult> GetAllInvitations()
{
try
{
_logger.LogInformation("Getting all invitations by administrator");
var read = await _repository.GetAllAsync();
List<InvitationDto> dtos = new List<InvitationDto>();
foreach (var inv in read)
{
dtos.Add(new InvitationDto(){
Id = inv.Id,
Description = inv.Description,
IsAdmin = inv.IsAdmin,
MaxParticipants = inv.MaxParticipants,
Code = inv.Code,
CreatedAt = inv.DateCreated,
EndAt = inv.EndDate,
IsActive = inv.IsActive,
});
}
return Ok(dtos);
}
catch (Exception e)
{
_logger.LogError(e, e.Message);
return BadRequest($"An error occured: {e.Message}");
}
}
[HttpGet("{id:guid}")]
public async Task<IActionResult> GetInvitationById(Guid id)
{
try
{
_logger.LogInformation("Getting invitations {id} by administrator");
var read = await _repository.FindByIdAsync(id);
var response = new InvitationDto(){
Id = read.Id,
Description = read.Description,
IsAdmin = read.IsAdmin,
MaxParticipants = read.MaxParticipants,
Code = read.Code,
CreatedAt = read.DateCreated,
EndAt = read.EndDate,
IsActive = read.IsActive,
};
return Ok(response);
}
catch (Exception e)
{
-2
View File
@@ -24,8 +24,6 @@
<ItemGroup>
<ProjectReference Include="..\Govor.Application\Govor.Application.csproj" />
<ProjectReference Include="..\Govor.Contracts\Govor.Contracts.csproj" />
<ProjectReference Include="..\Govor.Core\Govor.Core.csproj" />
<ProjectReference Include="..\Govor.Data\Govor.Data.csproj" />
</ItemGroup>
</Project>
@@ -0,0 +1,38 @@
using Govor.Core.Models;
namespace Govor.Core.Infrastructure.Validators;
public class FriendshipValidator : IObjectValidator<Friendship>
{
public void Validate(Friendship friendship)
{
try
{
if(friendship is null)
throw new ArgumentNullException(nameof(friendship));
if(friendship.Id == Guid.Empty)
throw new ArgumentException("Id cannot be empty", nameof(friendship.Id));
if(friendship.AddresseeId == Guid.Empty)
throw new ArgumentException("Addresses cannot be empty", nameof(friendship.AddresseeId));
if(friendship.RequesterId == Guid.Empty)
throw new ArgumentException("Requester cannot be empty", nameof(friendship.RequesterId));
}
catch (Exception e)
{
throw new InvalidObjectException<Friendship>(e);
}
}
public bool TryValidate(Friendship friendship)
{
try
{
Validate(friendship);
return true;
}
catch
{
return false;
}
}
}
+20
View File
@@ -0,0 +1,20 @@
namespace Govor.Core.Models;
public class Friendship
{
public Guid Id { get; set; }
public Guid RequesterId { get; set; }
public Guid AddresseeId { get; set; }
public FriendshipStatus Status { get; set; }
public User Requester { get; set; }
public User Addressee { get; set; }
}
public enum FriendshipStatus
{
Pending,
Accepted,
Rejected,
Blocked
}
+11
View File
@@ -0,0 +1,11 @@
namespace Govor.Core.Models;
public class PrivateChat
{
public Guid Id { get; set; }
public Guid UserAId { get; set; }
public Guid UserBId { get; set; }
public User UserA { get; set; }
public User UserB { get; set; }
public List<Message> Messages { get; set; } = new List<Message>();
}
@@ -0,0 +1,6 @@
namespace Govor.Core.Repositories.Friendships;
public interface IFriendshipsExist
{
bool Exist(Guid requesterId, Guid addresseeId);
}
@@ -0,0 +1,10 @@
using Govor.Core.Models;
namespace Govor.Core.Repositories.Friendships;
public interface IFriendshipsReader
{
Task<List<Friendship>> GetAllAsync();
Task<Friendship> GetByIdAsync(Guid id);
Task<List<Friendship>> FindByUserIdAsync(Guid userId);
}
@@ -0,0 +1,6 @@
namespace Govor.Core.Repositories.Friendships;
public interface IFriendshipsRepository : IFriendshipsReader, IFriendshipsWriter, IFriendshipsExist
{
}
@@ -0,0 +1,10 @@
using Govor.Core.Models;
namespace Govor.Core.Repositories.Friendships;
public interface IFriendshipsWriter
{
Task AddAsync(Friendship friendship);
Task UpdateAsync(Friendship friendship);
Task RemoveAsync(Friendship friendship);
}
+2
View File
@@ -8,6 +8,8 @@ namespace Govor.Data;
public class GovorDbContext(DbContextOptions<GovorDbContext> options) : DbContext(options)
{
public virtual DbSet<User> Users { get; set; }
public virtual DbSet<Friendship> Friendships { get; set; }
public virtual DbSet<PrivateChat> PrivateChats { get; set; }
public virtual DbSet<Admin> Admins { get; set; }
public virtual DbSet<Invitation> Invitations { get; set; }
@@ -0,0 +1,119 @@
using Govor.Core.Infrastructure.Extensions;
using Govor.Core.Infrastructure.Validators;
using Govor.Core.Models;
using Govor.Core.Repositories.Friendships;
using Govor.Data.Repositories.Exceptions;
using Microsoft.EntityFrameworkCore;
namespace Govor.Data.Repositories;
public class FriendshipsRepository : IFriendshipsRepository
{
private GovorDbContext _context;
private IObjectValidator<Friendship> _validator;
public FriendshipsRepository(GovorDbContext context, IObjectValidator<Friendship> validator)
{
_context = context;
_validator = validator;
}
public async Task<List<Friendship>> GetAllAsync()
{
return await _context.Friendships
.AsNoTracking()
.Include(x => x.Requester)
.Include(x => x.Addressee)
.ToListOrThrowIfEmpty(new NotFoundException("Database is empty"));
}
public async Task<Friendship> GetByIdAsync(Guid id)
{
return await _context.Friendships
.AsNoTracking()
.Include(x => x.Requester)
.Include(x => x.Addressee)
.FirstOrDefaultAsync(x => x.Id == id)
?? throw new NotFoundByKeyException<Guid>(id, "Friendship with given id was not found");
}
public async Task<List<Friendship>> FindByUserIdAsync(Guid userId)
{
return await _context.Friendships
.AsNoTracking()
.Include(x => x.Requester)
.Include(x => x.Addressee)
.Where(x => x.RequesterId == userId)
.ToListOrThrowIfEmpty(new NotFoundByKeyException<Guid>(userId, "Friendship with given user id was not found"));
}
public async Task AddAsync(Friendship friendship)
{
try
{
_validator.Validate(friendship);
_context.Friendships.Add(friendship);
await _context.SaveChangesAsync();
}
catch (InvalidObjectException<Admin> ex)
{
throw new AdditionException("Admin with given data invalid", ex);
}
catch (Exception ex)
{
throw new AdditionException("Cannot add admin", ex);
}
}
public async Task UpdateAsync(Friendship friendship)
{
try
{
_validator.Validate(friendship);
var rowsAffected = await _context.Friendships
.Where(a => a.Id == friendship.Id)
.ExecuteUpdateAsync(u => u
.SetProperty(a => a.RequesterId, friendship.RequesterId)
.SetProperty(a => a.AddresseeId, friendship.AddresseeId)
.SetProperty(a => a.Status, friendship.Status)
);
if (rowsAffected == 0)
throw new NotFoundByKeyException<Guid>(friendship.Id);
}
catch (NotFoundByKeyException<Guid> ex)
{
throw new UpdateException($"Not found friendship by given id {friendship.Id}", ex);
}
catch (Exception ex)
{
throw new UpdateException($"Error when updating the friendship {friendship.Id}", ex);
}
}
public async Task RemoveAsync(Friendship friendship)
{
try
{
var result = await GetByIdAsync(friendship.Id);
_context.Friendships.Remove(result);
await _context.SaveChangesAsync();
}
catch (NotFoundByKeyException<Guid> ex)
{
throw new RemoveException($"Not found friendship by given id {friendship.Id}", ex);
}
catch (Exception ex)
{
throw new RemoveException("Error when removing the friendship", ex);
}
}
public bool Exist(Guid requesterId, Guid addresseeId)
{
return _context.Friendships.AsNoTracking().Any(x => (x.RequesterId == requesterId && x.AddresseeId == addresseeId));
}
}