more tests for user rep

This commit is contained in:
Artemy
2025-06-17 17:37:10 +07:00
parent b4b6d33432
commit 70e46e7648
6 changed files with 204 additions and 19 deletions
@@ -125,4 +125,114 @@ public class UsersRepositoryTests
// Act & Assert // Act & Assert
Assert.ThrowsAsync<NotFoundByKeyException<IEnumerable<Guid>>>(async () => await userRepository.FindByRangeId(ids)); Assert.ThrowsAsync<NotFoundByKeyException<IEnumerable<Guid>>>(async () => await userRepository.FindByRangeId(ids));
} }
[Test]
public async Task Given_ValidUsername_When_FindByUsername_Then_Returns_User()
{
// Arrange
var user = _fixture.Create<User>();
await using var context = new GovorDbContext(_options);
var userRepository = new UsersRepository(context, _userValidator);
context.Users.Add(user);
await context.SaveChangesAsync();
// Act
var result = await userRepository.FindByUsername(user.Username);
// Assert
Assert.That(result, Is.Not.Null);
Assert.That(result.Username, Is.EqualTo(user.Username));
Assert.That(result.Id, Is.EqualTo(user.Id));
}
[Test]
public async Task Given_InvalidUsername_When_FindByUsername_Should_Throw_NotFoundByKeyException()
{
// Arrange
string username = _fixture.Create<string>();
await using var context = new GovorDbContext(_options);
var userRepository = new UsersRepository(context, _userValidator);
// Act & Assert
Assert.ThrowsAsync<NotFoundByKeyException<string>>(async () => await userRepository.FindByUsername(username));
}
[Test]
public async Task Given_ValidUsernames_When_FindByRangeUsernames_Then_Returns_Users()
{
// Arrange
var random = new Random();
var users = _fixture.CreateMany<User>(random.Next(3, 10)).ToList();
await using var context = new GovorDbContext(_options);
var userRepository = new UsersRepository(context, _userValidator);
context.Users.AddRange(users);
await context.SaveChangesAsync();
// Act
var result = await userRepository.FindByRangeUsernames(users.Select(u => u.Username));
// Assert
Assert.That(result, Is.Not.Null);
Assert.That(result.Select(u => u.Username), Is.EquivalentTo(users.Select(u => u.Username)));
Assert.That(result.Select(u => u.Id), Is.EquivalentTo(users.Select(u => u.Id)));
}
[Test]
public async Task Given_InvalidUsernames_When_FindByRangeUsernames_Should_Throw_NotFoundByKeyException()
{
// Arrange
var random = new Random();
var usernames = _fixture.CreateMany<string>(random.Next(3, 10)).ToList();
await using var context = new GovorDbContext(_options);
var userRepository = new UsersRepository(context, _userValidator);
// Act & Assert
Assert.ThrowsAsync<NotFoundByKeyException<IEnumerable<string>>>(async () => await userRepository.FindByRangeUsernames(usernames));
}
[Test]
public async Task Given_ValidDateOnly_When_FindByCreatedDate_Then_Returns_Users()
{
// Arrange
var random = new Random();
var users = _fixture.CreateMany<User>(random.Next(3, 10)).ToList();
var selectedDate = users[random.Next(users.Count)].CreatedOn;
await using var context = new GovorDbContext(_options);
var userRepository = new UsersRepository(context, _userValidator);
context.Users.AddRange(users);
await context.SaveChangesAsync();
// Act
var result = await userRepository.FindUsersByCreatedDate(selectedDate);
// Assert
var expectedUsers = users
.Where(u => u.CreatedOn == selectedDate)
.ToList();
Assert.That(result, Is.Not.Null);
Assert.That(result.Count, Is.EqualTo(expectedUsers.Count));
Assert.That(result.Select(u => u.Id), Is.EquivalentTo(expectedUsers.Select(u => u.Id)));
}
[Test]
public async Task Given_InvalidDateOnly_When_FindByCreatedDate_Should_Throw_NotFoundByKeyException()
{
// Arrange
var date = _fixture.Create<DateOnly>();
await using var context = new GovorDbContext(_options);
var userRepository = new UsersRepository(context, _userValidator);
// Act & Assert
Assert.ThrowsAsync<NotFoundByKeyException<DateOnly>>(async () => await userRepository.FindUsersByCreatedDate(date));
}
} }
@@ -6,4 +6,4 @@ public interface IObjectValidator<T>
bool TryValidate(T objectToValidate); bool TryValidate(T objectToValidate);
} }
class InvalidObjectException<T>(Exception ex) : GovorCoreException($"The object {typeof(T).FullName} is invalid.", ex); public class InvalidObjectException<T>(Exception ex) : GovorCoreException($"The object {typeof(T).FullName} is invalid.", ex);
@@ -5,6 +5,8 @@ namespace Govor.Core.Infrastructure.Validators;
public class UserValidator : IObjectValidator<User> public class UserValidator : IObjectValidator<User>
{ {
public const int MIN_LENGHT_OF_NAME = 4;
public const int MAX_LENGHT_OF_NAME = 100;
public void Validate(User user) public void Validate(User user)
{ {
try try
@@ -13,9 +15,13 @@ public class UserValidator : IObjectValidator<User>
throw new ArgumentNullException(nameof(user)); throw new ArgumentNullException(nameof(user));
if(user.Id == Guid.Empty) if(user.Id == Guid.Empty)
throw new ArgumentException("User ID cannot be empty", nameof(user.Id)); throw new ArgumentException("User ID cannot be empty", nameof(user.Id));
if(user.Username is null
|| user.Username.Length < MIN_LENGHT_OF_NAME
|| user.Username.Length > MAX_LENGHT_OF_NAME)
throw new ArgumentException($"Username cannot be empty or less then {MIN_LENGHT_OF_NAME} chars or more then {MAX_LENGHT_OF_NAME}", nameof(user.Username));
if(user.HashPassword is null || user.HashPassword == string.Empty) if(user.HashPassword is null || user.HashPassword == string.Empty)
throw new ArgumentException("Password cannot be empty", nameof(user.HashPassword)); throw new ArgumentException("Password cannot be empty", nameof(user.HashPassword));
if(user.CreatedOn == DateTime.MinValue) if(user.CreatedOn == DateOnly.MinValue)
throw new ArgumentException("Time of creation account cannot be empty", nameof(user.CreatedOn)); throw new ArgumentException("Time of creation account cannot be empty", nameof(user.CreatedOn));
} }
catch(Exception ex) catch(Exception ex)
+3 -1
View File
@@ -1,3 +1,5 @@
using System.ComponentModel.DataAnnotations;
namespace Govor.Core.Models; namespace Govor.Core.Models;
public class User public class User
@@ -7,6 +9,6 @@ public class User
public string Description {get; set;} public string Description {get; set;}
public string HashPassword {get; set;} public string HashPassword {get; set;}
public Guid IconId {get; set;} public Guid IconId {get; set;}
public DateTime CreatedOn {get; set;} public DateOnly CreatedOn {get; set;}
public DateTime WasOnline {get; set;} public DateTime WasOnline {get; set;}
} }
+2 -2
View File
@@ -7,7 +7,7 @@ public interface IUsersReader
public Task<IEnumerable<User>> GetAll(); public Task<IEnumerable<User>> GetAll();
public Task<User> FindById(Guid id); public Task<User> FindById(Guid id);
public Task<List<User>> FindByRangeId(IEnumerable<Guid> ids); public Task<List<User>> FindByRangeId(IEnumerable<Guid> ids);
public Task<List<User>> FindUsersByName(string username); public Task<User> FindByUsername(string username);
public Task<List<User>> FindByRangeUsername(IEnumerable<string> usernames); public Task<List<User>> FindByRangeUsernames(IEnumerable<string> usernames);
public Task<List<User>> FindUsersByCreatedDate(DateOnly createdDate); public Task<List<User>> FindUsersByCreatedDate(DateOnly createdDate);
} }
+78 -11
View File
@@ -22,11 +22,14 @@ public class UsersRepository : IUsersRepository
return await _context.Users return await _context.Users
.AsNoTracking() .AsNoTracking()
.Where(x => true) .Where(x => true)
.ToListAsync(); .ToListOrThrowIfEmpty(new NotFoundException("Users in Database not exists"));
} }
public async Task<User> FindById(Guid id) public async Task<User> FindById(Guid id)
{ {
if(id == Guid.Empty)
throw new ArgumentException("Id must not be empty", nameof(id));
return await _context.Users return await _context.Users
.AsNoTracking() .AsNoTracking()
.FirstOrDefaultAsync(x => x.Id == id) .FirstOrDefaultAsync(x => x.Id == id)
@@ -35,45 +38,101 @@ public class UsersRepository : IUsersRepository
public async Task<List<User>> FindByRangeId(IEnumerable<Guid> ids) public async Task<List<User>> FindByRangeId(IEnumerable<Guid> ids)
{ {
if (ids is null || !ids.Any())
throw new ArgumentException("Ids must not be empty", nameof(ids));
return await _context.Users return await _context.Users
.AsNoTracking() .AsNoTracking()
.Where(x => ids.Contains(x.Id)) .Where(x => ids.Contains(x.Id))
.ToListOrThrowIfEmpty(new NotFoundByKeyException<IEnumerable<Guid>>(ids,"Users with given ids not found")); .ToListOrThrowIfEmpty(new NotFoundByKeyException<IEnumerable<Guid>>(ids,"Users with given ids not found"));
} }
public async Task<List<User>> FindUsersByName(string username) public async Task<User> FindByUsername(string username)
{ {
if(username is null || username == string.Empty)
throw new ArgumentNullException(username, "Username cannot be empty");
return await _context.Users return await _context.Users
.AsNoTracking() .AsNoTracking()
.Where(x => x.Username == username) .FirstOrDefaultAsync(x => x.Username == username)
.ToListOrThrowIfEmpty(new NotFoundByKeyException<string>(username, "Users with given username not found")); ?? throw new NotFoundByKeyException<string>(username, "User with given username does not exist");
} }
public async Task<List<User>> FindByRangeUsername(IEnumerable<string> usernames) public async Task<List<User>> FindByRangeUsernames(IEnumerable<string> usernames)
{ {
if (usernames is null || !usernames.Any())
throw new ArgumentException("Usernames must not be empty", nameof(usernames));
return await _context.Users return await _context.Users
.AsNoTracking() .AsNoTracking()
.Where(x => usernames.Contains(x.Username)) .Where(x => usernames.Contains(x.Username))
.ToListOrThrowIfEmpty(new NotFoundByKeyException<IEnumerable<string>>(usernames, "Users with given usernames not found")); .ToListOrThrowIfEmpty(new NotFoundByKeyException<IEnumerable<string>>(usernames, "Users with given usernames not found"));
} }
public Task<List<User>> FindUsersByCreatedDate(DateOnly createdDate) public async Task<List<User>> FindUsersByCreatedDate(DateOnly createdDate)
{ {
throw new NotImplementedException(); if(createdDate == DateOnly.MinValue)
throw new ArgumentException("Created date cannot be earlier than MinValue", nameof(createdDate));
return await _context.Users
.AsNoTracking()
.Where(u => createdDate == u.CreatedOn)
.ToListOrThrowIfEmpty(new NotFoundByKeyException<DateOnly>(createdDate, "Users with given created date do not exist"));
} }
public Task Add(User user) public async Task Add(User user)
{ {
throw new NotImplementedException(); try
{
_validator.Validate(user);
_context.Users.Add(user);
await _context.SaveChangesAsync();
}
catch (InvalidObjectException<User> ex)
{
throw new AdditionUserException("User with given data invalid", ex);
}
catch (Exception ex)
{
throw new AdditionUserException("Cannot add user", ex);
}
} }
public Task Update(User user) public async Task Update(User user)
{ {
throw new NotImplementedException(); try
{
_validator.Validate(user);
var rowsAffected = await _context.Users
.Where(u => u.Id == user.Id)
.ExecuteUpdateAsync(u => u
.SetProperty(a => a.Username, user.Username)
.SetProperty(u => u.IconId, user.IconId)
.SetProperty(u => u.Description, user.Description)
.SetProperty(u => u.CreatedOn, user.CreatedOn)
.SetProperty(u => u.HashPassword, user.HashPassword)
.SetProperty(u => u.WasOnline, user.WasOnline)
);
if (rowsAffected == 0)
throw new NotFoundByKeyException<Guid>(user.Id);
}
catch (NotFoundByKeyException<Guid> ex)
{
throw new UserUpdateException($"Not found user by given id {user.Id}", ex);
}
catch (Exception ex)
{
throw new UserUpdateException($"Error when updating the user {user.Id}", ex);
}
} }
public Task Remove(User user) public Task Remove(User user)
{ {
_validator.Validate(user);
throw new NotImplementedException(); throw new NotImplementedException();
} }
@@ -84,6 +143,7 @@ public class UsersRepository : IUsersRepository
public Task<bool> Exists(User user) public Task<bool> Exists(User user)
{ {
_validator.Validate(user);
throw new NotImplementedException(); throw new NotImplementedException();
} }
@@ -97,3 +157,10 @@ public class UsersRepository : IUsersRepository
throw new NotImplementedException(); throw new NotImplementedException();
} }
} }
public class AdditionUserException(string s, Exception ex)
: Exception(s, ex);
public class UserUpdateException(string s, Exception ex)
: Exception(s, ex);