Expand server tests and enforce coverage

Consolidate server tests under tests/, upgrade them to .NET 10, and add CI coverage thresholds and reports. Expand API and application boundary coverage while fixing related issues in media handling, friend blocking, session crypto, presence, username validation, and local storage.
This commit is contained in:
Artemy
2026-10-24 15:30:32 +07:00
parent 33550d4fc9
commit 2d99c57a3b
161 changed files with 5515 additions and 8419 deletions
@@ -0,0 +1,153 @@
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using AutoFixture;
using Govor.Domain.Models.Users;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using Moq;
namespace Govor.Application.Tests.Services.Authentication;
[TestFixture]
public class JwtServiceTests
{
private Fixture _fixture = null!;
private Mock<IOptions<JwtAccessOption>> _jwtOptionsMock = null!;
private Mock<IOptions<JwtRefreshOption>> _jwtRefreshOptionsMock = null!;
private Mock<IInvitesService> _invitesServiceMock = null!;
private IJwtService _jwtService = null!;
private JwtAccessOption _testJwtAccessOptions = null!;
private JwtRefreshOption _testJwtRefreshOptions = null!;
[SetUp]
public void SetUp()
{
_fixture = new Fixture();
_fixture.Behaviors.OfType<ThrowingRecursionBehavior>().ToList().ForEach(b => _fixture.Behaviors.Remove(b));
_fixture.Behaviors.Add(new OmitOnRecursionBehavior());
_testJwtAccessOptions = new JwtAccessOption
{
SecretKey = "THIS_IS_A_TEST_SECRET_KEY_THAT_IS_LONG_ENOUGH_1234", // Ensure key size is sufficient for HMACSHA256
Minutes = 5
};
_testJwtRefreshOptions = new JwtRefreshOption()
{
RefreshTokenLifetimeDays = 30
};
_jwtOptionsMock = new Mock<IOptions<JwtAccessOption>>();
_jwtOptionsMock.Setup(o => o.Value).Returns(_testJwtAccessOptions);
_jwtRefreshOptionsMock = new Mock<IOptions<JwtRefreshOption>>();
_jwtRefreshOptionsMock.Setup(o => o.Value).Returns(_testJwtRefreshOptions);
_invitesServiceMock = new Mock<IInvitesService>();
_jwtService = new JwtService(
_jwtOptionsMock.Object,
_jwtRefreshOptionsMock.Object,
_invitesServiceMock.Object);
}
[Test]
public async Task GenerateJwtToken_ShouldReturnValidJwtString_WithCorrectClaims()
{
// Arrange
var user = _fixture.Create<User>();
var sessionId = Guid.NewGuid();
var expectedRole = "User";
_invitesServiceMock.Setup(s => s.GetRoleNameAsync(user)).ReturnsAsync(expectedRole);
// Act
var tokenString = await _jwtService.GenerateAccessTokenAsync(user, sessionId);
// Assert
var handler = new JwtSecurityTokenHandler();
var jwt = handler.ReadJwtToken(tokenString);
var claims = jwt.Claims.ToDictionary(c => c.Type, c => c.Value);
Assert.That(claims["userId"], Is.EqualTo(user.Id.ToString()));
Assert.That(claims["sid"], Is.EqualTo(sessionId.ToString()));
Assert.That(claims[ClaimTypes.Role], Is.EqualTo(expectedRole));
Assert.That(jwt.ValidTo, Is.GreaterThan(DateTime.UtcNow));
}
[Test]
public async Task GenerateAccessTokenAsync_ShouldIncludeSessionIdAndRole()
{
// Arrange
var user = new User { Id = Guid.NewGuid(), Username = "TestUser" };
var sessionId = Guid.NewGuid();
var role = "Admin";
_invitesServiceMock.Setup(s => s.GetRoleNameAsync(user)).ReturnsAsync(role);
// Act
var token = await _jwtService.GenerateAccessTokenAsync(user, sessionId);
var handler = new JwtSecurityTokenHandler();
var jwt = handler.ReadJwtToken(token);
// Assert
var sidClaim = jwt.Claims.FirstOrDefault(c => c.Type == "sid");
var roleClaim = jwt.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Role);
Assert.That(sidClaim?.Value, Is.EqualTo(sessionId.ToString()));
Assert.That(roleClaim?.Value, Is.EqualTo(role));
}
[Test]
public async Task GenerateRefreshTokenAsync_ReturnsValidRefreshToken()
{
// Arrange
var user = new User { Id = Guid.NewGuid() };
// Act
var token = await _jwtService.GenerateRefreshTokenAsync(user);
// Assert
Assert.That(token, Is.Not.Null);
var handler = new JwtSecurityTokenHandler();
var jwt = handler.ReadJwtToken(token);
Assert.That(user.Id.ToString(), Is.EqualTo(jwt.Claims.First(c => c.Type == "userId").Value));
Assert.That("refresh",Is.EqualTo(jwt.Claims.First(c => c.Type == "tokenType").Value));
}
[Test]
public async Task GetPrincipalFromExpiredToken_ReturnsValidClaimsPrincipal()
{
// Arrange
var userId = Guid.NewGuid();
var handler = new JwtSecurityTokenHandler();
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_testJwtAccessOptions.SecretKey));
var now = DateTime.UtcNow;
var token = handler.CreateToken(new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new[]
{
new Claim("userId", userId.ToString())
}),
NotBefore = now.AddSeconds(-10),
IssuedAt = now.AddSeconds(-10),
Expires = now.AddSeconds(-5),
SigningCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256)
});
var expiredToken = handler.WriteToken(token);
// Act
var principal = _jwtService.GetPrincipalFromExpiredToken(expiredToken);
// Assert
Assert.That(principal, Is.Not.Null);
var claim = principal.FindFirst("userId");
Assert.That(claim, Is.Not.Null);
Assert.That(userId.ToString(), Is.EqualTo(claim.Value));
}
}
@@ -0,0 +1,93 @@
using AutoFixture;
using Microsoft.Extensions.Configuration;
[TestFixture]
public class JwtTokenHasherTests
{
private IJwtTokenHasher _jwtTokenHasher = null!;
private Fixture _fixture = null!;
private const string TestSecret = "SuperSecretPepper123!";
[SetUp]
public void StartUp()
{
_fixture = new Fixture();
var config = new ConfigurationBuilder()
.AddInMemoryCollection(new Dictionary<string, string?>
{
{ "EncryptionOption:Secret", TestSecret }
})
.Build();
_jwtTokenHasher = new JwtTokenHasher(config);
}
[Test]
public void Given_Token_When_Hash_Then_Verify_Should_Return_True()
{
// Arrange
string token = _fixture.Create<string>();
// Act
string hash = _jwtTokenHasher.HashToken(token);
var result = _jwtTokenHasher.VerifyToken(token, hash);
// Assert
Assert.That(hash, Is.Not.EqualTo(token));
Assert.That(result, Is.True);
}
[Test]
public void Given_Invalid_Token_When_Verify_Should_Return_False()
{
// Arrange
string token = _fixture.Create<string>();
string notToken = _fixture.Create<string>();
// Act
string hash = _jwtTokenHasher.HashToken(token);
var result = _jwtTokenHasher.VerifyToken(notToken, hash);
// Assert
Assert.That(result, Is.False);
}
[Test]
public void Given_Same_Token_When_Hash_Multiple_Times_Should_Be_Equal()
{
// Arrange
string token = _fixture.Create<string>();
// Act
string hash1 = _jwtTokenHasher.HashToken(token);
string hash2 = _jwtTokenHasher.HashToken(token);
// Assert
Assert.That(hash1, Is.EqualTo(hash2));
}
[Test]
public void Given_Different_Tokens_When_Hash_Should_Be_Different()
{
// Arrange
string token1 = _fixture.Create<string>();
string token2 = _fixture.Create<string>();
// Act
string hash1 = _jwtTokenHasher.HashToken(token1);
string hash2 = _jwtTokenHasher.HashToken(token2);
// Assert
Assert.That(hash1, Is.Not.EqualTo(hash2));
}
[Test]
public void Given_Null_Secret_In_Config_Should_Use_Default_Secret()
{
// Arrange
var emptyConfig = new ConfigurationBuilder().Build();
// Act & Assert
Assert.Throws<InvalidOperationException>(() => new JwtTokenHasher(emptyConfig));
}
}
@@ -0,0 +1,48 @@
using AutoFixture;
namespace Govor.Application.Tests.Services;
[TestFixture]
public class PasswordHasherTests
{
private IPasswordHasher _passwordHasher = null!;
private Fixture _fixture = null!;
[SetUp]
public void StarUp()
{
_fixture = new Fixture();
_passwordHasher = new PasswordHasher();
}
[Test]
public void Given_Password_When_Hash_Then_Hash_And_Verify_Then_Result_Should_Be_True()
{
// Arrange
string password = _fixture.Create<string>();
// Act
string hash = _passwordHasher.Hash(password);
var result = _passwordHasher.Verify(password, hash);
// Assert
Assert.That(hash, Is.Not.EqualTo(password));
Assert.That(result, Is.True);
}
[Test]
public void Given_Password_NotPassword_When_Hash_Should_Not_Be_True_Then_Result_Should_Be_False()
{
// Arrange
string password = _fixture.Create<string>();
string notPassword = _fixture.Create<string>();
// Act
string hash = _passwordHasher.Hash(password);
var result = _passwordHasher.Verify(notPassword, hash);
// Assert
Assert.That(result, Is.False);
}
}
@@ -0,0 +1,105 @@
using System.Security.Claims;
using Govor.Application.Infrastructure.Extensions;
using Microsoft.AspNetCore.Http;
using Moq;
namespace Govor.Application.Tests.Infrastructure.Extensions;
[TestFixture]
public class CurrentUserServiceTests
{
private Mock<IHttpContextAccessor> _httpContextAccessorMock = null!;
private ICurrentUserService _currentUserService = null!;
[SetUp]
public void SetUp()
{
_httpContextAccessorMock = new Mock<IHttpContextAccessor>();
_currentUserService = new CurrentUserService(_httpContextAccessorMock.Object);
}
[Test]
public void GetCurrentUserId_ValidUserIdClaim_ReturnsGuid()
{
// Arrange
var userId = Guid.NewGuid();
var claims = new[] { new Claim("userId", userId.ToString()) };
var identity = new ClaimsIdentity(claims);
var principal = new ClaimsPrincipal(identity);
var httpContextMock = new Mock<HttpContext>();
httpContextMock.Setup(x => x.User).Returns(principal);
_httpContextAccessorMock.Setup(x => x.HttpContext).Returns(httpContextMock.Object);
// Act
var result = _currentUserService.GetCurrentUserId();
// Assert
Assert.That(result, Is.EqualTo(userId));
}
[Test]
public void GetCurrentUserId_NoHttpContext_ThrowsUnauthorizedAccessException()
{
// Arrange
_httpContextAccessorMock.Setup(x => x.HttpContext).Returns((HttpContext)null);
// Act & Assert
var ex = Assert.Throws<UnauthorizedAccessException>(() => _currentUserService.GetCurrentUserId());
Assert.That(ex.Message, Is.EqualTo("userID claim is missing or invalid"));
}
[Test]
public void GetCurrentUserId_NoUserIdClaim_ThrowsUnauthorizedAccessException()
{
// Arrange
var claims = new[] { new Claim("otherClaim", "value") };
var identity = new ClaimsIdentity(claims);
var principal = new ClaimsPrincipal(identity);
var httpContextMock = new Mock<HttpContext>();
httpContextMock.Setup(x => x.User).Returns(principal);
_httpContextAccessorMock.Setup(x => x.HttpContext).Returns(httpContextMock.Object);
// Act & Assert
var ex = Assert.Throws<UnauthorizedAccessException>(() => _currentUserService.GetCurrentUserId());
Assert.That(ex.Message, Is.EqualTo("userID claim is missing or invalid"));
}
[Test]
public void GetCurrentUserId_InvalidUserIdClaim_ThrowsUnauthorizedAccessException()
{
// Arrange
var claims = new[] { new Claim("userId", "invalid-guid") };
var identity = new ClaimsIdentity(claims);
var principal = new ClaimsPrincipal(identity);
var httpContextMock = new Mock<HttpContext>();
httpContextMock.Setup(x => x.User).Returns(principal);
_httpContextAccessorMock.Setup(x => x.HttpContext).Returns(httpContextMock.Object);
// Act & Assert
var ex = Assert.Throws<UnauthorizedAccessException>(() => _currentUserService.GetCurrentUserId());
Assert.That(ex.Message, Is.EqualTo("userID claim is missing or invalid"));
}
[Test]
public void GetCurrentUserId_EmptyUserIdClaim_ThrowsUnauthorizedAccessException()
{
// Arrange
var claims = new[] { new Claim("userId", "") };
var identity = new ClaimsIdentity(claims);
var principal = new ClaimsPrincipal(identity);
var httpContextMock = new Mock<HttpContext>();
httpContextMock.Setup(x => x.User).Returns(principal);
_httpContextAccessorMock.Setup(x => x.HttpContext).Returns(httpContextMock.Object);
// Act & Assert
var ex = Assert.Throws<UnauthorizedAccessException>(() => _currentUserService.GetCurrentUserId());
Assert.That(ex.Message, Is.EqualTo("userID claim is missing or invalid"));
}
}
@@ -0,0 +1,107 @@
using System.Security.Claims;
using Govor.Application.Infrastructure.Extensions;
using Microsoft.AspNetCore.Http;
using Moq;
namespace Govor.Application.Tests.Infrastructure.Extensions;
[TestFixture]
[TestOf(typeof(CurrentUserSessionService))]
public class CurrentUserSessionServiceTests
{
private Mock<IHttpContextAccessor> _httpContextAccessorMock = null!;
private ICurrentUserSessionService _sessionService = null!;
[SetUp]
public void SetUp()
{
_httpContextAccessorMock = new Mock<IHttpContextAccessor>();
_sessionService = new CurrentUserSessionService(_httpContextAccessorMock.Object);
}
[Test]
public void GetCurrentSessionId_ValidSidClaim_ReturnsGuid()
{
// Arrange
var sid = Guid.NewGuid();
var claims = new[] { new Claim("sid", sid.ToString()) };
var identity = new ClaimsIdentity(claims);
var principal = new ClaimsPrincipal(identity);
var httpContextMock = new Mock<HttpContext>();
httpContextMock.Setup(x => x.User).Returns(principal);
_httpContextAccessorMock.Setup(x => x.HttpContext).Returns(httpContextMock.Object);
// Act
var result = _sessionService.GetUserSessionId();
// Assert
Assert.That(result, Is.EqualTo(sid));
}
[Test]
public void GetCurrentSessionId_NoHttpContext_ThrowsUnauthorizedAccessException()
{
// Arrange
_httpContextAccessorMock.Setup(x => x.HttpContext).Returns((HttpContext)null);
// Act & Assert
var ex = Assert.Throws<UnauthorizedAccessException>(() => _sessionService.GetUserSessionId());
Assert.That(ex.Message, Is.EqualTo("Session id (sid) claim is missing or invalid"));
}
[Test]
public void GetCurrentSessionId_NoSidlaim_ThrowsUnauthorizedAccessException()
{
// Arrange
var claims = new[] { new Claim("otherClaim", "value") };
var identity = new ClaimsIdentity(claims);
var principal = new ClaimsPrincipal(identity);
var httpContextMock = new Mock<HttpContext>();
httpContextMock.Setup(x => x.User).Returns(principal);
_httpContextAccessorMock.Setup(x => x.HttpContext).Returns(httpContextMock.Object);
// Act & Assert
var ex = Assert.Throws<UnauthorizedAccessException>(() => _sessionService.GetUserSessionId());
Assert.That(ex.Message, Is.EqualTo("Session id (sid) claim is missing or invalid"));
}
[Test]
public void GetUserSessionId_InvalidSidValueClaim_ThrowsUnauthorizedAccessException()
{
// Arrange
var claims = new[] { new Claim("sid", "invalid-guid") };
var identity = new ClaimsIdentity(claims);
var principal = new ClaimsPrincipal(identity);
var httpContextMock = new Mock<HttpContext>();
httpContextMock.Setup(x => x.User).Returns(principal);
_httpContextAccessorMock.Setup(x => x.HttpContext).Returns(httpContextMock.Object);
// Act & Assert
var ex = Assert.Throws<UnauthorizedAccessException>(() => _sessionService.GetUserSessionId());
Assert.That(ex.Message, Is.EqualTo("Session id (sid) claim is missing or invalid"));
}
[Test]
public void GetUserSessionId_EmptySidValueClaim_ThrowsUnauthorizedAccessException()
{
// Arrange
var claims = new[] { new Claim("sid", "") };
var identity = new ClaimsIdentity(claims);
var principal = new ClaimsPrincipal(identity);
var httpContextMock = new Mock<HttpContext>();
httpContextMock.Setup(x => x.User).Returns(principal);
_httpContextAccessorMock.Setup(x => x.HttpContext).Returns(httpContextMock.Object);
// Act & Assert
var ex = Assert.Throws<UnauthorizedAccessException>(() => _sessionService.GetUserSessionId());
Assert.That(ex.Message, Is.EqualTo("Session id (sid) claim is missing or invalid"));
}
}
@@ -0,0 +1,52 @@
using Govor.Domain.Common;
using Microsoft.Extensions.Configuration;
namespace Govor.Application.Tests.Unit.Infrastructure.Validators;
[TestFixture]
public class UsernameBoundaryTests
{
private static Dictionary<string, string?> Settings() => new()
{
["UsernameModeration:BlockedExact:0"] = "админ",
["UsernameModeration:BlockedContains:0"] = "запрет",
["UsernameModeration:Reserved:0"] = "логин"
};
private static UsernameValidator Validator() => new(new ConfigurationBuilder().AddInMemoryCollection(Settings()).Build());
[Test]
public void NameLengthBoundariesAndNullReturnValidationResults()
{
var validator = Validator();
var longest = string.Concat(Enumerable.Repeat("Иван", 11));
Assert.That(validator.Validate("Иван").IsSuccess, Is.True);
Assert.That(validator.Validate(longest).IsSuccess, Is.True);
foreach (var invalid in new[] { null, "", " ", "Ива", longest + "а" })
{
var result = validator.Validate(invalid!);
Assert.That(result.IsFailure, Is.True);
Assert.That(result.Error.Type, Is.EqualTo(ErrorType.Validation));
Assert.That(validator.TryValidate(invalid!), Is.False);
}
}
[TestCase("Абббб", true)]
[TestCase("Аббббб", false)]
[TestCase("Иван0", true)]
[TestCase("Админ", false)]
[TestCase("ЛОГИН", false)]
[TestCase("Запрет123", false)]
public void SyntaxRepetitionAndModerationAreApplied(string name, bool valid) =>
Assert.That(Validator().Validate(name).IsSuccess, Is.EqualTo(valid));
[TestCase("BlockedExact")]
[TestCase("BlockedContains")]
[TestCase("Reserved")]
public void MissingModerationSectionFailsConfiguration(string section)
{
var settings = Settings();
settings.Remove("UsernameModeration:" + section + ":0");
Assert.Throws<InvalidOperationException>(() => new UsernameValidator(new ConfigurationBuilder().AddInMemoryCollection(settings).Build()));
}
}
@@ -0,0 +1,107 @@
using Govor.Application.Authentication.Exceptions;
using Govor.Application.Infrastructure.Validators;
using Microsoft.Extensions.Configuration;
namespace Govor.Application.Tests.Infrastructure.Validators;
[TestFixture]
public class UsernameValidatorTests
{
private UsernameValidator _validator = null!;
[SetUp]
public void SetUp()
{
var configData = new Dictionary<string, string?>
{
["UsernameModeration:BlockedExact:0"] = "админ",
["UsernameModeration:BlockedExact:1"] = "модератор",
["UsernameModeration:BlockedContains:0"] = "гитлер",
["UsernameModeration:BlockedContains:1"] = "наци",
["UsernameModeration:Reserved:0"] = "логин",
["UsernameModeration:Reserved:1"] = "регистрация"
};
var config = new ConfigurationBuilder()
.AddInMemoryCollection(configData)
.Build();
_validator = new UsernameValidator(config);
}
[TestCase("Иван")]
[TestCase("Алексей")]
[TestCase("Ёжик")]
[TestCase("Иван123")] // содержит цифры
public void Validate_ValidUsernames_ReturnsSuccess(string username)
{
Assert.That(_validator.Validate(username).IsSuccess, Is.True);
}
[TestCase("Ivan")] // не кириллица
[TestCase("123Иван")] // начинается не с буквы
[TestCase("!@#$")] // спецсимволы
[TestCase("")] // пусто
[TestCase("И")] // меньше минимума
[TestCase("ИванИванИванИванИванИванИванИванИванИванИванИванИван")] // больше максимума (44 символа)
public void Validate_InvalidUsernames_ReturnsFailure(string username)
{
var result = _validator.Validate(username);
Assert.That(result.IsFailure, Is.True);
Assert.That(result.Error.Type, Is.EqualTo(Govor.Domain.Common.ErrorType.Validation));
}
[TestCase("Ааааааа")]
[TestCase("Бbbbb")]
public void Validate_RepeatingCharacters_ReturnsFailure(string username)
{
var result = _validator.Validate(username);
Assert.That(result.IsFailure, Is.True);
Assert.That(result.Error.Type, Is.EqualTo(Govor.Domain.Common.ErrorType.Validation));
}
[TestCase("Админ")]
[TestCase("Модератор")]
public void Validate_BlockedExact_ReturnsFailure(string username)
{
var result = _validator.Validate(username);
Assert.That(result.IsFailure, Is.True);
Assert.That(result.Error.Type, Is.EqualTo(Govor.Domain.Common.ErrorType.Validation));
}
[TestCase("Гитлер123")]
[TestCase("Нацист")]
public void Validate_BlockedContains_ReturnsFailure(string username)
{
var result = _validator.Validate(username);
Assert.That(result.IsFailure, Is.True);
Assert.That(result.Error.Type, Is.EqualTo(Govor.Domain.Common.ErrorType.Validation));
}
[TestCase("Логин")]
[TestCase("Регистрация")]
public void Validate_ReservedNames_ReturnsFailure(string username)
{
var result = _validator.Validate(username);
Assert.That(result.IsFailure, Is.True);
Assert.That(result.Error.Type, Is.EqualTo(Govor.Domain.Common.ErrorType.Validation));
}
[TestCase("Г1тлер")]
public void Validate_Normalization_ShouldDetectBlockedWord(string username)
{
var result = _validator.Validate(username);
Assert.That(result.IsFailure, Is.True);
Assert.That(result.Error.Type, Is.EqualTo(Govor.Domain.Common.ErrorType.Validation));
}
[TestCase("Иван", ExpectedResult = true)]
[TestCase("1234", ExpectedResult = false)]
[TestCase("Админ", ExpectedResult = false)]
[TestCase("Гитлер123", ExpectedResult = false)]
public bool TryValidate_ShouldReturnExpectedResult(string username)
{
return _validator.TryValidate(username);
}
}
@@ -0,0 +1,147 @@
using Govor.Application.PushNotifications;
using Govor.Application.PushNotifications.Providers;
using Govor.Application.Interfaces.PushNotifications.Models;
using Govor.Domain.Common;
using Microsoft.Extensions.Logging.Abstractions;
using Moq;
namespace Govor.Application.Tests.Unit.PushNotifications;
[TestFixture]
public class PushNotificationServiceTests
{
private Mock<IPushNotificationProvider> _provider = null!;
private Mock<IPushTokenService> _tokens = null!;
private PushNotificationService _service = null!;
private readonly Guid _recipient = Guid.NewGuid();
private static readonly Error Failure = Error.ServerError("Test.Failure", "unavailable");
[SetUp]
public void SetUp()
{
_provider = new Mock<IPushNotificationProvider>(MockBehavior.Strict);
_tokens = new Mock<IPushTokenService>(MockBehavior.Strict);
_service = new(_provider.Object, _tokens.Object, NullLogger<PushNotificationService>.Instance);
}
[Test]
public async Task TokenLookupErrorsAreReturnedWithoutSending()
{
_tokens.Setup(t => t.GetStringsActiveTokensAsync(_recipient)).ReturnsAsync(Result.Failure<List<string>>(Failure));
_tokens.Setup(t => t.GetUsersStringsActiveTokensAsync(It.IsAny<IEnumerable<Guid>>())).ReturnsAsync(Result.Failure<List<string>>(Failure));
_tokens.Setup(t => t.GetActiveTokenBySessionAsync(_recipient)).ReturnsAsync(Result.Failure<string?>(Failure));
Assert.That((await _service.SendToUserAsync(_recipient, "t", "b", "c")).Error, Is.SameAs(Failure));
Assert.That((await _service.SendToUsersAsync(new[] { _recipient }, "t", "b", "c")).Error, Is.SameAs(Failure));
Assert.That((await _service.SendToSessionAsync(_recipient, "t", "b", "c")).Error, Is.SameAs(Failure));
_provider.VerifyNoOtherCalls();
}
[Test]
public async Task MissingTokensAreSuccessfulNoOpsForEveryDeliveryMode()
{
_tokens.Setup(t => t.GetStringsActiveTokensAsync(_recipient)).ReturnsAsync(new List<string>());
_tokens.Setup(t => t.GetUsersStringsActiveTokensAsync(It.IsAny<IEnumerable<Guid>>())).ReturnsAsync(new List<string>());
_tokens.Setup(t => t.GetActiveTokenBySessionAsync(_recipient)).ReturnsAsync((string?)null);
Assert.That((await _service.SendToUserAsync(_recipient, "t", "b", "c")).IsSuccess, Is.True);
Assert.That((await _service.SendToUsersAsync(new[] { _recipient }, "t", "b", "c")).IsSuccess, Is.True);
Assert.That((await _service.SendToSessionAsync(_recipient, "t", "b", "c")).IsSuccess, Is.True);
_provider.VerifyNoOtherCalls();
}
[Test]
public async Task EmptyOrNullBulkRecipientsAreRejectedBeforeTokenLookup()
{
Assert.That((await _service.SendToUsersAsync(Array.Empty<Guid>(), "t", "b", "c")).Error.Code, Is.EqualTo("Push.InvalidArgs"));
Assert.That((await _service.SendToUsersAsync(null!, "t", "b", "c")).IsFailure, Is.True);
_tokens.VerifyNoOtherCalls();
_provider.VerifyNoOtherCalls();
}
[Test]
public async Task SessionDeliveryPreservesPayload()
{
var data = new Dictionary<string, string> { ["id"] = "message" };
_tokens.Setup(t => t.GetActiveTokenBySessionAsync(_recipient)).ReturnsAsync("device");
_provider.Setup(p => p.SendToTokenAsync("device", It.Is<PushMessage>(m => m.Title == "title" &&
m.Body == "body" && m.ChannelId == "channel" && m.Tag == "tag" && m.Data == data)))
.ReturnsAsync(new SendPushResult(1, 0, Array.Empty<string>()));
Assert.That((await _service.SendToSessionAsync(_recipient, "title", "body", "channel", "tag", data)).IsSuccess, Is.True);
_provider.VerifyAll();
}
[Test]
public async Task SessionProviderExceptionBecomesFailureAndKeepsToken()
{
_tokens.Setup(t => t.GetActiveTokenBySessionAsync(_recipient)).ReturnsAsync("device");
_provider.Setup(p => p.SendToTokenAsync("device", It.IsAny<PushMessage>())).ThrowsAsync(new IOException("provider offline"));
Assert.That((await _service.SendToSessionAsync(_recipient, "t", "b", "c")).IsFailure, Is.True);
_tokens.Verify(t => t.RemoveTokensAsync(It.IsAny<IEnumerable<string>>()), Times.Never);
}
[Test]
public async Task BulkRecipientsAndTokensAreDeduplicatedAndBatchingContinuesAfterFailure()
{
var tokens = Enumerable.Range(0, 501).Select(i => "device-" + i).ToList();
tokens.Add(tokens[0]);
_tokens.Setup(t => t.GetUsersStringsActiveTokensAsync(It.Is<IEnumerable<Guid>>(ids => ids.SequenceEqual(new[] { _recipient }))))
.ReturnsAsync(tokens);
var batches = new List<int>();
_provider.Setup(p => p.SendMulticastAsync(It.IsAny<IReadOnlyList<string>>(), It.IsAny<PushMessage>()))
.Returns((IReadOnlyList<string> batch, PushMessage message) =>
{
batches.Add(batch.Count);
Assert.That(message.Data, Is.Empty);
return batches.Count == 1 ? Task.FromException<SendPushResult>(new IOException("offline")) :
Task.FromResult(new SendPushResult(batch.Count, 0, Array.Empty<string>()));
});
var result = await _service.SendToUsersAsync(new[] { _recipient, _recipient }, "t", "b", "c");
Assert.That(result.Error.Code, Is.EqualTo("Push.DeliveryFailed"));
Assert.That(batches, Is.EqualTo(new[] { 500, 1 }));
_tokens.Verify(t => t.RemoveTokensAsync(It.IsAny<IEnumerable<string>>()), Times.Never);
}
[Test]
public async Task OnlyUnregisteredTokensFromThisBatchCanBeRemoved()
{
_tokens.Setup(t => t.GetStringsActiveTokensAsync(_recipient)).ReturnsAsync(new List<string> { "valid", "gone" });
_provider.Setup(p => p.SendMulticastAsync(It.IsAny<IReadOnlyList<string>>(), It.IsAny<PushMessage>()))
.ReturnsAsync(new SendPushResult(1, 1, new[] { "gone", "gone", "unrelated" }));
_tokens.Setup(t => t.RemoveTokensAsync(It.Is<IEnumerable<string>>(ts => ts.SequenceEqual(new[] { "gone" }))))
.ReturnsAsync(Result.Success());
Assert.That((await _service.SendToUserAsync(_recipient, "t", "b", "c")).IsSuccess, Is.True);
_tokens.VerifyAll();
}
[Test]
public async Task TokenRemovalFailureIsPropagated()
{
_tokens.Setup(t => t.GetActiveTokenBySessionAsync(_recipient)).ReturnsAsync("gone");
_provider.Setup(p => p.SendToTokenAsync("gone", It.IsAny<PushMessage>())).ReturnsAsync(new SendPushResult(0, 1, new[] { "gone" }));
_tokens.Setup(t => t.RemoveTokensAsync(It.IsAny<IEnumerable<string>>())).ReturnsAsync(Result.Failure(Failure));
Assert.That((await _service.SendToSessionAsync(_recipient, "t", "b", "c")).Error, Is.SameAs(Failure));
}
[TestCase(0, 0)]
[TestCase(0, 1)]
[TestCase(2, 0)]
public async Task IncompleteOrInconsistentProviderCountsAreFailures(int success, int failed)
{
_tokens.Setup(t => t.GetActiveTokenBySessionAsync(_recipient)).ReturnsAsync("device");
_provider.Setup(p => p.SendToTokenAsync("device", It.IsAny<PushMessage>()))
.ReturnsAsync(new SendPushResult(success, failed, Array.Empty<string>()));
Assert.That((await _service.SendToSessionAsync(_recipient, "t", "b", "c")).Error.Code, Is.EqualTo("Push.DeliveryFailed"));
}
[Test]
public async Task NullProviderAcceptsSingleAndMulticastWithoutNetwork()
{
var provider = new NullPushProvider();
Assert.That(provider.Name, Is.EqualTo("NULL"));
Assert.That((await provider.SendToTokenAsync("device", new PushMessage())).SuccessCount, Is.EqualTo(1));
var result = await provider.SendMulticastAsync(new[] { "a", "b" }, new PushMessage());
Assert.That(result.SuccessCount, Is.EqualTo(2));
Assert.That(result.FailureCount, Is.Zero);
Assert.That(result.FailedTokens, Is.Empty);
}
}
@@ -0,0 +1,187 @@
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using Govor.Application.E2ee;
using Jose;
namespace Govor.Application.Tests.Unit.Security;
[TestFixture]
public class E2eeProtocolBoundaryTests
{
private DevicePrivateKeys _keys = null!;
private DeviceKey _device = null!;
private ConversationKeys _conversation = null!;
private Guid _message;
[OneTimeSetUp]
public void SetUp()
{
_keys = E2eeProtocol.GenerateKeys();
_device = E2eeProtocol.PublicKey(_keys, Guid.NewGuid(), Guid.NewGuid());
_conversation = new(Guid.NewGuid(), 0, new[] { _device.UserId }, new[] { _device });
_message = Guid.NewGuid();
}
private string Encrypt() => E2eeProtocol.Encrypt(new("secret", []), _keys, _device, _conversation, _message);
private string Sign(EncryptedMessage envelope)
{
using var signing = ECDsa.Create();
signing.ImportPkcs8PrivateKey(Convert.FromBase64String(_keys.IdentityKey), out _);
return E2eeProtocol.Prefix + JWT.Encode(JsonSerializer.Serialize(envelope), signing, JwsAlgorithm.ES256);
}
[TestCase("plaintext")]
[TestCase("too-large")]
[TestCase("segments")]
[TestCase("null-json")]
public void InspectRejectsInvalidEnvelopeBeforeTrustingPayload(string reason)
{
var input = reason switch {
"plaintext" => "secret",
"too-large" => E2eeProtocol.Prefix + new string('x', E2eeProtocol.MaxEnvelopeLength),
"segments" => E2eeProtocol.Prefix + "only.two",
_ => E2eeProtocol.Prefix + "header." + Base64Url.Encode("null"u8.ToArray()) + ".signature"
};
Assert.Throws<CryptographicException>(() => E2eeProtocol.Inspect(input));
}
[TestCase("version")]
[TestCase("sender")]
[TestCase("message")]
[TestCase("conversation")]
[TestCase("type")]
[TestCase("recipients")]
[TestCase("media")]
[TestCase("ciphertext")]
public void InspectRejectsInvalidRoutingFields(string field)
{
var envelope = E2eeProtocol.Inspect(Encrypt());
envelope = field switch {
"version" => envelope with { Version = 2 },
"sender" => envelope with { Sender = null! },
"message" => envelope with { MessageId = Guid.Empty },
"conversation" => envelope with { ConversationId = Guid.Empty },
"type" => envelope with { RecipientType = 2 },
"recipients" => envelope with { Recipients = [] },
"media" => envelope with { MediaIds = null! },
_ => envelope with { Ciphertext = "" }
};
Assert.Throws<CryptographicException>(() => E2eeProtocol.Inspect(Sign(envelope)));
}
[TestCase("empty-message")]
[TestCase("empty-content")]
[TestCase("long-text")]
[TestCase("null-attachments")]
[TestCase("many-attachments")]
[TestCase("no-devices")]
[TestCase("many-devices")]
public void EncryptEnforcesContentAndRecipientLimits(string reason)
{
var plaintext = reason switch {
"empty-content" => new MessagePlaintext(" ", []),
"long-text" => new MessagePlaintext(new string('x', 20_001), []),
"null-attachments" => new MessagePlaintext("secret", null!),
"many-attachments" => new MessagePlaintext("secret", Enumerable.Range(0, 101)
.Select(_ => new AttachmentSecret(Guid.NewGuid(), "key", "file", "type")).ToArray()),
_ => new MessagePlaintext("secret", [])
};
var directory = reason == "no-devices" ? _conversation with { Devices = [] } :
reason == "many-devices" ? _conversation with { Devices = Enumerable.Repeat(_device, 501).ToArray() } : _conversation;
Assert.Throws<CryptographicException>(() => E2eeProtocol.Encrypt(plaintext, _keys, _device, directory,
reason == "empty-message" ? Guid.Empty : _message));
}
[TestCase("unprotected")]
[TestCase("aad")]
[TestCase("compression")]
[TestCase("encryption")]
[TestCase("manifest")]
[TestCase("algorithm")]
public void ValidSignatureDoesNotAuthorizeUnsupportedEncryptionHeaders(string reason)
{
var envelope = E2eeProtocol.Inspect(Encrypt());
var jwe = JsonNode.Parse(envelope.Ciphertext)!;
if (reason is "unprotected" or "aad") jwe[reason] = reason == "aad" ? JsonValue.Create("value") : new JsonObject();
if (reason is "compression" or "encryption")
{
var header = JsonNode.Parse(Base64Url.Decode(jwe["protected"]!.GetValue<string>()))!;
if (reason == "compression") header["zip"] = "DEF"; else header["enc"] = "A128GCM";
jwe["protected"] = Base64Url.Encode(Encoding.UTF8.GetBytes(header.ToJsonString()));
}
if (reason == "algorithm")
{
var recipient = jwe["recipients"] is JsonArray recipients ? recipients[0]! : jwe;
recipient["header"]!["alg"] = "RSA1_5";
}
if (reason == "manifest") envelope = envelope with { Recipients = new[] { "wrong-fingerprint" } };
var signed = Sign(envelope with { Ciphertext = jwe.ToJsonString() });
Assert.Throws<CryptographicException>(() => E2eeProtocol.Verify(signed));
}
[Test]
public void RecipientTypeAndEditContextAreAuthenticated()
{
var encrypted = Encrypt();
Assert.Throws<CryptographicException>(() => E2eeProtocol.Decrypt(encrypted, _keys, _message,
_conversation.ConversationId, 1, _device.UserId));
Assert.Throws<CryptographicException>(() => E2eeProtocol.Decrypt(encrypted, _keys, _message,
_conversation.ConversationId, 0, _device.UserId, expectedEdit: true));
}
[TestCase("identity")]
[TestCase("encryption")]
[TestCase("trailing-identity")]
[TestCase("trailing-encryption")]
[TestCase("empty-user")]
[TestCase("empty-session")]
public void InvalidDevicePublicKeysAreRejected(string reason)
{
var bad = reason switch {
"identity" => _device with { IdentityKey = "AAAA" },
"encryption" => _device with { EncryptionKey = "AAAA" },
"trailing-identity" => _device with { IdentityKey = Convert.ToBase64String(Convert.FromBase64String(_device.IdentityKey).Concat(new byte[] { 1 }).ToArray()) },
"trailing-encryption" => _device with { EncryptionKey = Convert.ToBase64String(Convert.FromBase64String(_device.EncryptionKey).Concat(new byte[] { 1 }).ToArray()) },
"empty-user" => _device with { UserId = Guid.Empty },
_ => _device with { SessionId = Guid.Empty }
};
Assert.Throws<CryptographicException>(() => E2eeProtocol.ValidatePublicKey(bad));
}
[Test]
public void InvalidPrivateKeysDoNotProducePublicKeys()
{
Assert.Throws<CryptographicException>(() => E2eeProtocol.PublicKey(_keys with { IdentityKey = "AAAA" }, _device.UserId, _device.SessionId));
Assert.Throws<CryptographicException>(() => E2eeProtocol.PublicKey(_keys with { EncryptionKey = "AAAA" }, _device.UserId, _device.SessionId));
}
[TestCase("short")]
[TestCase("large")]
[TestCase("key")]
public void AttachmentsEnforceCiphertextSizeAndKeyLength(string reason)
{
if (reason == "large") Assert.Throws<CryptographicException>(() => E2eeProtocol.EncryptAttachment(new byte[19_000_001]));
else if (reason == "short") Assert.Throws<CryptographicException>(() => E2eeProtocol.DecryptAttachment(new byte[27], Convert.ToBase64String(new byte[32])));
else
{
var (encrypted, _) = E2eeProtocol.EncryptAttachment(new byte[] { 1 });
Assert.Throws<CryptographicException>(() => E2eeProtocol.DecryptAttachment(encrypted, Convert.ToBase64String(new byte[16])));
}
}
[TestCase("null")]
[TestCase("{\"Text\":null,\"Attachments\":[]}")]
[TestCase("{\"Text\":\"secret\",\"Attachments\":[{\"MediaId\":\"11111111-1111-1111-1111-111111111111\"}]}")]
public void DecryptionRejectsMalformedPlaintextOrAttachmentManifest(string plaintext)
{
using var rsa = RSA.Create();
rsa.ImportSubjectPublicKeyInfo(Convert.FromBase64String(_device.EncryptionKey), out _);
var ciphertext = JWE.Encrypt(plaintext, new[] { new JweRecipient(JweAlgorithm.RSA_OAEP_256, rsa,
new Dictionary<string, object> { ["kid"] = _device.Fingerprint }) }, JweEncryption.A256GCM);
var envelope = E2eeProtocol.Inspect(Encrypt()) with { Ciphertext = ciphertext };
Assert.Throws<CryptographicException>(() => E2eeProtocol.Decrypt(Sign(envelope), _keys, _message,
_conversation.ConversationId, 0, _device.UserId));
}
}
@@ -0,0 +1,78 @@
namespace Govor.Application.Tests.Unit.Storage;
[TestFixture]
public class LocalStorageBoundaryTests
{
private string _root = null!;
private LocalStorageService _service = null!;
[SetUp]
public void SetUp()
{
_root = Path.Combine(Path.GetTempPath(), "govor-storage-tests-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(_root);
_service = new(_root);
}
[TearDown]
public void TearDown()
{
var resolved = Path.GetFullPath(_root);
if (!resolved.StartsWith(Path.GetFullPath(Path.GetTempPath()), StringComparison.OrdinalIgnoreCase) ||
!Path.GetFileName(resolved).StartsWith("govor-storage-tests-", StringComparison.Ordinal))
throw new InvalidOperationException("Unexpected temporary storage path.");
Directory.Delete(resolved, recursive: true);
}
[TestCase("../uploads-sibling/secret.bin")]
[TestCase("../outside.bin")]
public async Task TraversalCannotReadOrDeleteFilesOutsideUploadRoot(string relative)
{
var target = Path.GetFullPath(Path.Combine(_root, "uploads", relative));
Directory.CreateDirectory(Path.GetDirectoryName(target)!);
await File.WriteAllTextAsync(target, "secret");
Assert.ThrowsAsync<UnauthorizedAccessException>(() => _service.LoadAsync(relative));
Assert.ThrowsAsync<UnauthorizedAccessException>(() => _service.RemoveAsync(relative));
Assert.That(await File.ReadAllTextAsync(target), Is.EqualTo("secret"));
}
[Test]
public async Task AbsolutePathsAreRejectedEvenInsideStorage()
{
var absolute = Path.Combine(_root, "uploads", "absolute.bin");
await File.WriteAllTextAsync(absolute, "secret");
Assert.ThrowsAsync<UnauthorizedAccessException>(() => _service.LoadAsync(absolute));
Assert.ThrowsAsync<UnauthorizedAccessException>(() => _service.RemoveAsync(absolute));
Assert.That(File.Exists(absolute), Is.True);
}
[Test]
public async Task ReadOnlyFileCanBeDeletedAndRepeatedDeleteIsANoOp()
{
var path = await _service.SaveAsync(new byte[] { 1, 2 }, "../file.bin");
var fullPath = Path.Combine(_root, "uploads", path);
File.SetAttributes(fullPath, File.GetAttributes(fullPath) | FileAttributes.ReadOnly);
await _service.RemoveAsync(path);
await _service.RemoveAsync(path);
Assert.That(File.Exists(fullPath), Is.False);
}
[TestCase("")]
[TestCase(" ")]
[TestCase(null)]
public void InvalidPathsAreRejected(string? path)
{
Assert.ThrowsAsync<ArgumentException>(() => _service.LoadAsync(path!));
Assert.ThrowsAsync<ArgumentException>(() => _service.RemoveAsync(path!));
}
[Test]
public async Task ReusingExistingRootIsSafeAndMissingLoadIsReported()
{
_service = new(_root);
Assert.ThrowsAsync<FileNotFoundException>(() => _service.LoadAsync("missing.bin"));
var relative = await _service.SaveAsync(new byte[] { 3, 4 }, "same.bin");
await using var stream = await _service.LoadAsync(relative);
Assert.That(stream.CanRead, Is.True);
Assert.That(stream.Length, Is.EqualTo(2));
}
}
@@ -0,0 +1,137 @@
using AutoFixture;
using Microsoft.AspNetCore.Hosting;
using Moq;
namespace Govor.Application.Tests.Services;
[TestFixture]
public class LocalStorageServiceTests
{
private Fixture _fixture = null!;
private IStorageService _service = null!;
private Mock<IWebHostEnvironment> _webHostEnvironmentMock = null!;
private string _tempDirectory = null!;
[SetUp]
public void SetUp()
{
_fixture = new Fixture();
_webHostEnvironmentMock = new Mock<IWebHostEnvironment>();
_tempDirectory = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
Directory.CreateDirectory(_tempDirectory);
_webHostEnvironmentMock.Setup(w => w.ContentRootPath).Returns(_tempDirectory);
_service = new LocalStorageService(_webHostEnvironmentMock.Object.ContentRootPath);
}
[TearDown]
public void TearDown()
{
if (Directory.Exists(_tempDirectory))
{
Directory.Delete(_tempDirectory, true);
}
}
[Test]
public async Task Given_ValidDataAndFileName_When_SaveAsync_Then_FileIsSaved()
{
// Arrange
var data = _fixture.CreateMany<byte>(1000).ToArray();
var fileName = _fixture.Create<string>() + ".txt";
var saveDate = DateTime.UtcNow;
// Act
var url = await _service.SaveAsync(data, fileName);
// Assert
Assert.That(url, Is.Not.Null);
// _tempDirectory/uploads/yyyy/MM/url
var datePath = saveDate.ToString("yyyy/MM");
var expectedFilePath = Path.Combine(_tempDirectory, "uploads", url);
Assert.That(File.Exists(expectedFilePath), Is.True);
}
[Test]
public void Given_EmptyName_When_SaveAsync_Should_Throw_ArgumentException()
{
// Arrange
var data = _fixture.CreateMany<byte>(1000).ToArray();
// Act & Assert
Assert.ThrowsAsync<ArgumentException>(async () => await _service.SaveAsync(data, string.Empty));
}
[Test]
public void Given_EmptyData_When_SaveAsync_Should_Throw_ArgumentException()
{
// Arrange
var name = _fixture.Create<string>();
// Act & Assert
Assert.ThrowsAsync<ArgumentException>(async () => await _service.SaveAsync(default, name));
}
[Test]
public async Task Given_ValidUrl_When_LoadAsync_Then_Returns_FileStream()
{
// Arrange
var date = DateTime.UtcNow.ToString("yyyy/MM");
var corePath = Path.Combine(_tempDirectory, "uploads", date);
Directory.CreateDirectory(corePath);
var fileName = _fixture.Create<string>() + ".txt";
var fileContent = _fixture.Create<string>();
var filePath = Path.Combine(corePath, fileName);
await File.WriteAllTextAsync(filePath, fileContent);
// Act
var url = Path.Combine(date, fileName);
await using var stream = await _service.LoadAsync(url);
// Assert
Assert.That(stream, Is.Not.Null);
Assert.That(stream.Length, Is.GreaterThan(0));
// Дополнительная проверка: содержимое файла
using var reader = new StreamReader(stream);
var content = await reader.ReadToEndAsync();
Assert.That(content, Is.EqualTo(fileContent));
}
[Test]
public void Given_EmptyUrl_When_LoadAsync_Should_Throw_FileNotFoundException()
{
// Act & Assert
Assert.ThrowsAsync<FileNotFoundException>(async () => await _service.LoadAsync(_fixture.Create<string>()+".txt"));
}
[Test]
public async Task Given_ValidUrl_When_DeleteAsync_Then_FileIsDeleted()
{
// Arrange
var date = DateTime.UtcNow.ToString("yyyy/MM");
var corePath = Path.Combine(_tempDirectory, "uploads", date);
Directory.CreateDirectory(corePath);
var fileName = _fixture.Create<string>() + ".txt";
var fileContent = _fixture.Create<string>();
var filePath = Path.Combine(corePath, fileName);
await File.WriteAllTextAsync(filePath, fileContent);
// Act
var url = Path.Combine(date, fileName);
await _service.RemoveAsync(url);
Assert.That(File.Exists(filePath), Is.False);
}
[Test]
public async Task Given_InvalidUrl_When_DeleteAsync_TShould_Not_Throw()
{
// Act & Assert
Assert.DoesNotThrowAsync(async () => await _service.RemoveAsync(_fixture.Create<string>()+".txt"));
}
}
@@ -0,0 +1,105 @@
using Govor.Application.Synching;
namespace Govor.Application.Tests.Services;
[TestFixture]
public class SynchingServiceTests
{
private readonly SynchingService _sut; // System Under Test
public SynchingServiceTests()
{
_sut = new SynchingService();
}
[Test]
public void NormalizeNewlines_ShouldReturnEmptyString_WhenInputIsEmpty()
{
// Act
var result = _sut.NormalizeNewlines(string.Empty);
// Assert
Assert.That(result, Is.EqualTo(string.Empty));
}
[Test]
public void NormalizeNewlines_ShouldReturnNull_WhenInputIsNull()
{
// Arrange
string input = null;
// Act
var result = _sut.NormalizeNewlines(input);
// Assert
Assert.That(result, Is.Null);
}
[Test]
public void NormalizeNewlines_ShouldNotChangeUnixStyleNewlines_WhenInputIsLF()
{
// Arrange
const string input = "Line 1\nLine 2\nLine 3";
// Act
var result = _sut.NormalizeNewlines(input);
// Assert
Assert.That(result, Is.EqualTo(input));
}
[Test]
public void NormalizeNewlines_ShouldConvertWindowsStyleNewlines_WhenInputIsCRLF()
{
// Arrange
const string input = "Line 1\r\nLine 2\r\nLine 3";
const string expected = "Line 1\nLine 2\nLine 3";
// Act
var result = _sut.NormalizeNewlines(input);
// Assert
Assert.That(result, Is.EqualTo(expected));
}
[Test]
public void NormalizeNewlines_ShouldConvertMacStyleNewlines_WhenInputIsCR()
{
// Arrange
const string input = "Line 1\rLine 2\rLine 3";
const string expected = "Line 1\nLine 2\nLine 3";
// Act
var result = _sut.NormalizeNewlines(input);
// Assert
Assert.That(result, Is.EqualTo(expected));
}
[Test]
public void NormalizeNewlines_ShouldHandleMixedNewlines_WhenInputIsMixed()
{
// Arrange
const string input = "Line 1\r\nLine 2\rLine 3\nLine 4";
const string expected = "Line 1\nLine 2\nLine 3\nLine 4";
// Act
var result = _sut.NormalizeNewlines(input);
// Assert
Assert.That(result, Is.EqualTo(expected));
}
[Test]
public void NormalizeNewlines_ShouldHandleTextWithoutNewlines()
{
// Arrange
const string input = "This is a single line of text.";
// Act
var result = _sut.NormalizeNewlines(input);
// Assert
Assert.That(result, Is.EqualTo(input));
}
}
@@ -0,0 +1,43 @@
using Govor.Application.Users.UserOnlineStatus;
namespace Govor.Application.Tests.Users;
[TestFixture]
public class OnlineUserStoreTests
{
[Test]
public void UserRemainsOnlineUntilLastConnectionLeaves()
{
var store = new OnlineUserStore();
var user = Guid.NewGuid();
Assert.That(store.IsOnline(user), Is.False);
Assert.That(store.AddConnection(user, "phone"), Is.True);
Assert.That(store.AddConnection(user, "desktop"), Is.False);
Assert.That(store.AddConnection(user, "phone"), Is.False);
Assert.That(store.GetConnections(user), Is.EquivalentTo(new[] { "phone", "desktop" }));
Assert.That(store.GetAllOnlineUsers(), Is.EqualTo(new[] { user }));
Assert.That(store.RemoveConnection(user, "phone"), Is.False);
Assert.That(store.IsOnline(user), Is.True);
Assert.That(store.RemoveConnection(user, "desktop"), Is.True);
Assert.That(store.IsOnline(user), Is.False);
Assert.That(store.GetAllOnlineUsers(), Is.Empty);
Assert.That(store.GetConnections(user), Is.Empty);
}
[Test]
public void ConnectionSnapshotsAndOtherUsersAreIndependent()
{
var store = new OnlineUserStore();
var alice = Guid.NewGuid();
var bob = Guid.NewGuid();
store.AddConnection(alice, "alice");
var snapshot = store.GetConnections(alice);
store.AddConnection(alice, "second");
store.AddConnection(bob, "bob");
store.RemoveConnection(alice, "alice");
store.RemoveConnection(alice, "second");
Assert.That(snapshot, Is.EqualTo(new[] { "alice" }));
Assert.That(store.IsOnline(bob), Is.True);
Assert.That(store.RemoveConnection(Guid.NewGuid(), "unknown"), Is.False);
}
}
@@ -0,0 +1,62 @@
using AutoFixture;
using Govor.Domain.Models;
using Govor.Domain.Models.Users;
using Microsoft.Extensions.Logging;
using Moq;
namespace Govor.Application.Tests.Services.UserOnlineStatus;
[TestFixture]
[TestOf(typeof(UserNotificationScopeService))]
public class UserNotificationScopeServiceTests
{
private Mock<ILogger<UserNotificationScopeService>> _mockLogger = null!;
private Mock<IFriendshipService> _mockFriendshipService = null!;
private IUserNotificationScopeService _service = null!;
private Fixture _fixture = null!;
private Guid _userId;
[SetUp]
public void SetUp()
{
_fixture = new Fixture();
_fixture.Behaviors.OfType<ThrowingRecursionBehavior>().ToList().ForEach(b => _fixture.Behaviors.Remove(b));
_fixture.Behaviors.Add(new OmitOnRecursionBehavior());
_userId = Guid.NewGuid();
_mockLogger = new Mock<ILogger<UserNotificationScopeService>>();
_mockFriendshipService = new Mock<IFriendshipService>();
_service = new UserNotificationScopeService(_mockLogger.Object, _mockFriendshipService.Object);
}
[Test]
public async Task GetNotifiedUsers_ReturnsNotifiedUsers()
{
// Arrange
var random = new Random();
var users = _fixture.CreateMany<User>(random.Next(3, 10)).ToList();
_mockFriendshipService.Setup(f => f.GetFriendsAsync(_userId))
.ReturnsAsync(users);
// Act
var result = await _service.GetNotifiedUsers(_userId);
// Assert
Assert.That(result, Is.Not.Null);
Assert.That(result.Count, Is.EqualTo(users.Count));
Assert.That(result, Is.EquivalentTo(users.Select(u => u.Id)));
}
[Test]
public async Task GetNotifiedUsers_PropagatesFriendshipServiceFailure()
{
// Arrange
_mockFriendshipService.Setup(f => f.GetFriendsAsync(_userId))
.ThrowsAsync(new InvalidOperationException("Database is empty."));
// Act & Assert
var ex = Assert.ThrowsAsync<InvalidOperationException>(async () => await _service.GetNotifiedUsers(_userId));
Assert.That(ex.Message, Is.EqualTo("Database is empty."));
}
}