Adds authentication unit tests

This commit is contained in:
BinaryAlley committed 2024-11-12 15:45:26 +02:00
1 parent a6dcf65d1c
commit 4f91f29b62
101 files changed
+5549 -135

No files matched your search

@@ -0,0 +1,41 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Infrastructure.Common.Models.Configuration;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.Authentication.Fixtures;
/// <summary>
/// Fixture class for JWT token generation tests.
/// </summary>
[ExcludeFromCodeCoverage]
public class JwtTokenGeneratorFixture
{
/// <summary>
/// Creates a valid JWT settings model for testing.
/// </summary>
/// <returns>The created settings model.</returns>
public static JwtSettingsModel CreateJwtSettings()
{
return new Faker<JwtSettingsModel>()
.CustomInstantiator(f => new JwtSettingsModel
{
SecretKey = "this-is-a-very-long-secret-key-for-testing-jwt-tokens",
ExpiryMinutes = 30,
Issuer = "test-issuer",
Audience = "test-audience"
})
.Generate();
}
/// <summary>
/// Creates test user credentials.
/// </summary>
/// <returns>A tuple containing the user ID and username.</returns>
public static (string Id, string Username) CreateUserCredentials()
{
return (Guid.NewGuid().ToString(), new Faker().Person.UserName);
}
}
@@ -0,0 +1,37 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.Authentication.Fixtures;
/// <summary>
/// Fixture class for QR code generation tests.
/// </summary>
[ExcludeFromCodeCoverage]
public class QRCodeGeneratorFixture
{
/// <summary>
/// Creates test data for QR code generation.
/// </summary>
/// <returns>A tuple containing username and secret bytes.</returns>
public static (string Username, byte[] Secret) CreateQrCodeTestData()
{
string username = new Faker().Person.UserName;
byte[] secret = new byte[20]; // Standard TOTP secret length
new Random().NextBytes(secret);
return (username, secret);
}
/// <summary>
/// Gets the expected otpauth URI format for validation.
/// </summary>
/// <param name="username">The username to use in the URI.</param>
/// <param name="base32Secret">The Base32 encoded secret.</param>
/// <returns>The formatted otpauth URI.</returns>
public static string GetExpectedOtpauthUri(string username, string base32Secret)
{
return $"otpauth://totp/Lumina:{Uri.EscapeDataString(username)}?secret={base32Secret}&issuer=Lumina";
}
}
@@ -0,0 +1,137 @@
#region ========================================================================= USING =====================================================================================
using FluentAssertions;
using Lumina.Application.Common.Infrastructure.Time;
using Lumina.Infrastructure.Common.Models.Configuration;
using Lumina.Infrastructure.Core.Authentication;
using Lumina.Infrastructure.UnitTests.Core.Authentication.Fixtures;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.Authentication;
/// <summary>
/// Contains unit tests for the <see cref="JwtTokenGenerator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class JwtTokenGeneratorTests
{
private readonly IDateTimeProvider _mockDateTimeProvider;
private readonly JwtSettingsModel _jwtSettings;
private readonly JwtTokenGenerator _sut;
private readonly DateTime _fixedUtcNow;
/// <summary>
/// Initializes a new instance of the <see cref="JwtTokenGeneratorTests"/> class.
/// </summary>
public JwtTokenGeneratorTests()
{
_mockDateTimeProvider = Substitute.For<IDateTimeProvider>();
_jwtSettings = JwtTokenGeneratorFixture.CreateJwtSettings();
_fixedUtcNow = new DateTime(2024, 1, 1, 12, 0, 0, DateTimeKind.Utc);
_mockDateTimeProvider.UtcNow.Returns(_fixedUtcNow);
IOptions<JwtSettingsModel> options = Substitute.For<IOptions<JwtSettingsModel>>();
options.Value.Returns(_jwtSettings);
_sut = new JwtTokenGenerator(_mockDateTimeProvider, options);
}
[Fact]
public void GenerateToken_WhenCalled_ShouldCreateValidJwtToken()
{
// Arrange
(string userId, string username) = JwtTokenGeneratorFixture.CreateUserCredentials();
JwtSecurityTokenHandler tokenHandler = new();
// Act
string token = _sut.GenerateToken(userId, username);
// Assert
token.Should().NotBeNullOrEmpty();
JwtSecurityToken jwtToken = tokenHandler.ReadJwtToken(token);
// verify token properties
jwtToken.Issuer.Should().Be(_jwtSettings.Issuer);
jwtToken.Audiences.Should().ContainSingle().Which.Should().Be(_jwtSettings.Audience);
jwtToken.ValidTo.Should().Be(_fixedUtcNow.AddMinutes(_jwtSettings.ExpiryMinutes));
// verify claims
jwtToken.Claims.Should().Contain(c => c.Type == JwtRegisteredClaimNames.Sub && c.Value == userId);
jwtToken.Claims.Should().Contain(c => c.Type == JwtRegisteredClaimNames.UniqueName && c.Value == username);
jwtToken.Claims.Should().Contain(c => c.Type == JwtRegisteredClaimNames.Jti && c.Value == userId);
// verify the token is actually valid
TokenValidationParameters validationParameters = new()
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtSettings.SecretKey)),
ValidateIssuer = true,
ValidIssuer = _jwtSettings.Issuer,
ValidateAudience = true,
ValidAudience = _jwtSettings.Audience,
ValidateLifetime = true,
ClockSkew = TimeSpan.Zero,
// override the current time to match our fixed test time
LifetimeValidator = (notBefore, expires, token, parameters) => expires > _fixedUtcNow
};
ClaimsPrincipal principal = tokenHandler.ValidateToken(token, validationParameters, out SecurityToken validatedToken);
principal.Should().NotBeNull();
validatedToken.Should().NotBeNull();
}
[Fact]
public void GenerateToken_WhenCalled_ShouldUseProvidedDateTimeForExpiration()
{
// Arrange
(string userId, string username) = JwtTokenGeneratorFixture.CreateUserCredentials();
JwtSecurityTokenHandler tokenHandler = new();
// Act
string token = _sut.GenerateToken(userId, username);
JwtSecurityToken jwtToken = tokenHandler.ReadJwtToken(token);
// Assert
jwtToken.ValidTo.Should().Be(_fixedUtcNow.AddMinutes(_jwtSettings.ExpiryMinutes));
_ = _mockDateTimeProvider.Received(1).UtcNow;
}
[Fact]
public void GenerateToken_WhenCalledWithDifferentUsers_ShouldCreateUniqueTokens()
{
// Arrange
(string userId1, string username1) = JwtTokenGeneratorFixture.CreateUserCredentials();
(string userId2, string username2) = JwtTokenGeneratorFixture.CreateUserCredentials();
// Act
string token1 = _sut.GenerateToken(userId1, username1);
string token2 = _sut.GenerateToken(userId2, username2);
// Assert
token1.Should().NotBe(token2);
}
[Fact]
public void GenerateToken_WhenCalledMultipleTimesForSameUser_ShouldCreateIdenticalTokens()
{
// Arrange
(string userId, string username) = JwtTokenGeneratorFixture.CreateUserCredentials();
// Act
string token1 = _sut.GenerateToken(userId, username);
string token2 = _sut.GenerateToken(userId, username);
// Assert
token1.Should().Be(token2);
}
}
@@ -0,0 +1,151 @@
#region ========================================================================= USING =====================================================================================
using AutoFixture;
using AutoFixture.AutoNSubstitute;
using FluentAssertions;
using Lumina.Infrastructure.Common.Errors;
using Lumina.Infrastructure.Common.Models.Configuration;
using Lumina.Infrastructure.Common.Validators;
using Lumina.Infrastructure.Core.Authentication;
using Lumina.Infrastructure.UnitTests.Core.Authentication.Fixtures;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.Authentication;
/// <summary>
/// Contains unit tests for the <see cref="QRCodeGenerator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class QRCodeGeneratorTests
{
private readonly QRCodeGenerator _sut;
/// <summary>
/// Initializes a new instance of the <see cref="QRCodeGeneratorTests"/> class.
/// </summary>
public QRCodeGeneratorTests()
{
_sut = new QRCodeGenerator();
}
[Fact]
public void GenerateQrCodeDataUri_WhenCalled_ShouldReturnValidDataUri()
{
// Arrange
(string username, byte[] secret) = QRCodeGeneratorFixture.CreateQrCodeTestData();
// Act
string result = _sut.GenerateQrCodeDataUri(username, secret);
// Assert
result.Should().StartWith("data:image/png;base64,");
result.Should().Match(uri => IsBase64String(uri.Substring(22))); // Skip "data:image/png;base64,"
}
[Fact]
public void GenerateQrCodeDataUri_WhenUsernameContainsSpecialCharacters_ShouldEscapeUsername()
{
// Arrange
string username = "user@example.com";
(_, byte[] secret) = QRCodeGeneratorFixture.CreateQrCodeTestData();
// Act
string result = _sut.GenerateQrCodeDataUri(username, secret);
// Assert
result.Should().StartWith("data:image/png;base64,");
result.Should().Match(uri => IsBase64String(uri.Substring(22)));
}
[Fact]
public void GenerateQrCodeDataUri_WhenCalled_ShouldGenerateUniqueQrCodesForDifferentUsers()
{
// Arrange
(string username1, byte[] secret) = QRCodeGeneratorFixture.CreateQrCodeTestData();
string username2 = username1 + "_different";
// Act
string result1 = _sut.GenerateQrCodeDataUri(username1, secret);
string result2 = _sut.GenerateQrCodeDataUri(username2, secret);
// Assert
result1.Should().NotBe(result2);
}
[Fact]
public void GenerateQrCodeDataUri_WhenCalledWithSameInput_ShouldGenerateIdenticalQrCodes()
{
// Arrange
(string username, byte[] secret) = QRCodeGeneratorFixture.CreateQrCodeTestData();
// Act
string result1 = _sut.GenerateQrCodeDataUri(username, secret);
string result2 = _sut.GenerateQrCodeDataUri(username, secret);
// Assert
result1.Should().Be(result2);
}
[Theory]
[InlineData("")]
[InlineData(" ")]
public void GenerateQrCodeDataUri_WhenUsernameIsInvalid_ShouldStillGenerateQrCode(string? invalidUsername)
{
// Arrange
(_, byte[] secret) = QRCodeGeneratorFixture.CreateQrCodeTestData();
// Act
string result = _sut.GenerateQrCodeDataUri(invalidUsername!, secret);
// Assert
result.Should().StartWith("data:image/png;base64,");
result.Should().Match(uri => IsBase64String(uri.Substring(22)));
}
[Theory]
[InlineData("user@example.com")]
[InlineData("user name with spaces")]
[InlineData("user+with+plus")]
[InlineData("user/with/slashes")]
public void GenerateQrCodeDataUri_WhenUsernameHasSpecialCharacters_ShouldStillGenerateQrCode(string username)
{
// Arrange
(_, byte[] secret) = QRCodeGeneratorFixture.CreateQrCodeTestData();
// Act
string result = _sut.GenerateQrCodeDataUri(username, secret);
// Assert
result.Should().StartWith("data:image/png;base64,");
result.Should().Match(uri => IsBase64String(uri.Substring(22)));
}
[Fact]
public void GenerateQrCodeDataUri_WhenSecretIsTooShort_ShouldStillGenerateQrCode()
{
// Arrange
(string username, _) = QRCodeGeneratorFixture.CreateQrCodeTestData();
byte[] shortSecret = [1]; // minimum length for Base32 encoding
// Act
string result = _sut.GenerateQrCodeDataUri(username, shortSecret);
// Assert
result.Should().StartWith("data:image/png;base64,");
result.Should().Match(uri => IsBase64String(uri.Substring(22)));
}
private static bool IsBase64String(string base64)
{
try
{
Convert.FromBase64String(base64);
return true;
}
catch
{
return false;
}
}
}
@@ -0,0 +1,71 @@
#region ========================================================================= USING =====================================================================================
using FluentAssertions;
using Lumina.Infrastructure.Core.Authentication;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.Authentication;
/// <summary>
/// Contains unit tests for the <see cref="TokenGenerator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class TokenGeneratorTests
{
private readonly TokenGenerator _sut;
/// <summary>
/// Initializes a new instance of the <see cref="TokenGeneratorTests"/> class.
/// </summary>
public TokenGeneratorTests()
{
_sut = new TokenGenerator();
}
[Fact]
public void GenerateToken_WhenCalled_ShouldGenerateNonEmptyToken()
{
// Act
string token = _sut.GenerateToken();
// Assert
token.Should().NotBeNullOrEmpty();
}
[Fact]
public void GenerateToken_WhenCalled_ShouldGenerateUrlSafeToken()
{
// Act
string token = _sut.GenerateToken();
// Assert
token.Should().NotContain("+", "Token should not contain '+'");
token.Should().NotContain("/", "Token should not contain '/'");
token.Should().NotContain("=", "Token should not contain '='");
}
[Fact]
public void GenerateToken_WhenCalledMultipleTimes_ShouldGenerateUniqueTokens()
{
// Act
string token1 = _sut.GenerateToken();
string token2 = _sut.GenerateToken();
string token3 = _sut.GenerateToken();
// Assert
token1.Should().NotBe(token2);
token1.Should().NotBe(token3);
token2.Should().NotBe(token3);
}
[Fact]
public void GenerateToken_WhenCalled_ShouldGenerateTokenOfCorrectLength()
{
// Act
string token = _sut.GenerateToken();
// Assert
// 32 bytes in Base64 without padding should be 43 characters
token.Length.Should().Be(43);
}
}
@@ -0,0 +1,109 @@
#region ========================================================================= USING =====================================================================================
using FluentAssertions;
using Lumina.Infrastructure.Core.Authentication;
using OtpNet;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.Authentication;
/// <summary>
/// Contains unit tests for the <see cref="TotpTokenGenerator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class TotpTokenGeneratorTests
{
private readonly TotpTokenGenerator _sut;
/// <summary>
/// Initializes a new instance of the <see cref="TotpTokenGeneratorTests"/> class.
/// </summary>
public TotpTokenGeneratorTests()
{
_sut = new TotpTokenGenerator();
}
[Fact]
public void GenerateSecret_WhenCalled_ShouldGenerateNonEmptySecret()
{
// Act
byte[] secret = _sut.GenerateSecret();
// Assert
secret.Should().NotBeEmpty();
}
[Fact]
public void GenerateSecret_WhenCalledMultipleTimes_ShouldGenerateUniqueSecrets()
{
// Act
byte[] secret1 = _sut.GenerateSecret();
byte[] secret2 = _sut.GenerateSecret();
byte[] secret3 = _sut.GenerateSecret();
// Assert
secret1.Should().NotBeEquivalentTo(secret2);
secret1.Should().NotBeEquivalentTo(secret3);
secret2.Should().NotBeEquivalentTo(secret3);
}
[Fact]
public void ValidateToken_WhenTokenIsValid_ShouldReturnTrue()
{
// Arrange
byte[] secret = _sut.GenerateSecret();
Totp totp = new(secret);
string validToken = totp.ComputeTotp();
// Act
bool result = _sut.ValidateToken(secret, validToken);
// Assert
result.Should().BeTrue();
}
[Theory]
[InlineData("")]
[InlineData(" ")]
[InlineData("123456")] // Valid format but wrong token
[InlineData("abcdef")] // Invalid format
[InlineData("12345")] // Too short
[InlineData("1234567")] // Too long
public void ValidateToken_WhenTokenIsInvalid_ShouldReturnFalse(string invalidToken)
{
// Arrange
byte[] secret = _sut.GenerateSecret();
// Act
bool result = _sut.ValidateToken(secret, invalidToken);
// Assert
result.Should().BeFalse();
}
[Fact]
public void ValidateToken_WhenSecretIsWrong_ShouldReturnFalse()
{
// Arrange
byte[] secret1 = _sut.GenerateSecret();
byte[] secret2 = _sut.GenerateSecret();
Totp totp = new(secret1);
string token = totp.ComputeTotp();
// Act
bool result = _sut.ValidateToken(secret2, token);
// Assert
result.Should().BeFalse();
}
[Fact]
public void GenerateSecret_WhenCalled_ShouldGenerateSecretOfCorrectLength()
{
// Act
byte[] secret = _sut.GenerateSecret();
// Assert
secret.Length.Should().Be(20); // Standard TOTP secret length
}
}
@@ -0,0 +1,161 @@
#region ========================================================================= USING =====================================================================================
using FluentAssertions;
using Lumina.Infrastructure.Common.Models.Configuration;
using Lumina.Infrastructure.Core.Security;
using Lumina.Infrastructure.UnitTests.Core.Security.Fixtures;
using Microsoft.Extensions.Options;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Security.Cryptography;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.Security;
/// <summary>
/// Contains unit tests for the <see cref="CryptographyService"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class CryptographyServiceTests
{
private readonly CryptographyService _sut;
private readonly IOptions<EncryptionSettingsModel> _encryptionSettings;
/// <summary>
/// Initializes a new instance of the <see cref="CryptographyServiceTests"/> class.
/// </summary>
public CryptographyServiceTests()
{
_encryptionSettings = CryptographyServiceFixture.CreateEncryptionSettings();
_sut = new CryptographyService(_encryptionSettings);
}
[Fact]
public void Encrypt_WhenCalledWithValidData_ShouldReturnNonEmptyString()
{
// Arrange
string plaintext = CryptographyServiceFixture.CreateTestData();
// Act
string result = _sut.Encrypt(plaintext);
// Assert
result.Should().NotBeNullOrEmpty();
result.Should().NotBe(plaintext);
}
[Fact]
public void Encrypt_WhenCalledMultipleTimesWithSameInput_ShouldReturnDifferentResults()
{
// Arrange
string plaintext = CryptographyServiceFixture.CreateTestData();
// Act
string result1 = _sut.Encrypt(plaintext);
string result2 = _sut.Encrypt(plaintext);
// Assert
result1.Should().NotBe(result2);
}
[Theory]
[InlineData(null)]
[InlineData("")]
public void Encrypt_WhenInputIsNullOrEmpty_ShouldThrowArgumentException(string? invalidInput)
{
// Act
Action act = () => _sut.Encrypt(invalidInput!);
// Assert
act.Should().Throw<ArgumentException>()
.WithParameterName("plaintext")
.WithMessage("Value cannot be null or empty*");
}
[Fact]
public void Decrypt_WhenCalledWithValidData_ShouldReturnOriginalText()
{
// Arrange
string originalText = CryptographyServiceFixture.CreateTestData();
string encrypted = _sut.Encrypt(originalText);
// Act
string decrypted = _sut.Decrypt(encrypted);
// Assert
decrypted.Should().Be(originalText);
}
[Theory]
[InlineData(null)]
[InlineData("")]
public void Decrypt_WhenInputIsNullOrEmpty_ShouldThrowArgumentException(string? invalidInput)
{
// Act
Action act = () => _sut.Decrypt(invalidInput!);
// Assert
act.Should().Throw<ArgumentException>()
.WithParameterName("ciphertext")
.WithMessage("Value cannot be null or empty*");
}
[Theory]
[InlineData("invalid")]
[InlineData("not-base64-!@#")]
public void Decrypt_WhenInputIsNotBase64_ShouldThrowFormatException(string invalidInput)
{
// Act
Action act = () => _sut.Decrypt(invalidInput);
// Assert
act.Should().Throw<FormatException>();
}
[Fact]
public void Decrypt_WhenInputIsTooShort_ShouldThrowArgumentException()
{
// Arrange
string shortCiphertext = Convert.ToBase64String(new byte[8]); // less than required 16 bytes
// Act
Action act = () => _sut.Decrypt(shortCiphertext);
// Assert
act.Should().Throw<ArgumentException>()
.WithMessage("Invalid ciphertext");
}
[Fact]
public void Decrypt_WhenInputIsCorrupted_ShouldThrowCryptographicException()
{
// Arrange
string originalText = CryptographyServiceFixture.CreateTestData();
string encrypted = _sut.Encrypt(originalText);
// decode the Base64 string, modify one byte, then re-encode
byte[] encryptedBytes = Convert.FromBase64String(encrypted);
encryptedBytes[^1] ^= 0xFF; // flip all bits in the last byte
string corrupted = Convert.ToBase64String(encryptedBytes);
// Act
Action act = () => _sut.Decrypt(corrupted);
// Assert
act.Should().Throw<CryptographicException>();
}
[Fact]
public void Dispose_WhenCalled_ShouldClearKey()
{
// Arrange
string plaintext = CryptographyServiceFixture.CreateTestData();
string encrypted = _sut.Encrypt(plaintext);
// Act
_sut.Dispose();
// Assert
Action act = () => _sut.Decrypt(encrypted);
act.Should().Throw<CryptographicException>();
}
}
@@ -0,0 +1,49 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Infrastructure.Common.Models.Configuration;
using Microsoft.Extensions.Options;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Security.Cryptography;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.Security.Fixtures;
/// <summary>
/// Fixture class for cryptography service tests.
/// </summary>
[ExcludeFromCodeCoverage]
public class CryptographyServiceFixture
{
/// <summary>
/// Creates a valid encryption settings model for testing.
/// </summary>
/// <returns>The configured options.</returns>
public static IOptions<EncryptionSettingsModel> CreateEncryptionSettings()
{
// Generate a valid 256-bit (32 byte) key for AES-256
byte[] key = new byte[32];
RandomNumberGenerator.Fill(key);
string base64Key = Convert.ToBase64String(key);
EncryptionSettingsModel settings = new()
{
SecretKey = base64Key
};
IOptions<EncryptionSettingsModel> options = Substitute.For<IOptions<EncryptionSettingsModel>>();
options.Value.Returns(settings);
return options;
}
/// <summary>
/// Creates test data for encryption/decryption.
/// </summary>
/// <returns>A string to be encrypted/decrypted.</returns>
public static string CreateTestData()
{
return new Faker().Lorem.Sentence();
}
}
@@ -0,0 +1,165 @@
#region ========================================================================= USING =====================================================================================
using FluentAssertions;
using Lumina.Infrastructure.Core.Security;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.Security;
/// <summary>
/// Contains unit tests for the <see cref="HashService"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class HashServiceTests
{
private readonly HashService _sut;
/// <summary>
/// Initializes a new instance of the <see cref="HashServiceTests"/> class.
/// </summary>
public HashServiceTests()
{
_sut = new HashService();
}
[Fact]
public void HashString_WhenCalled_ShouldReturnNonEmptyHash()
{
// Arrange
string password = "TestPassword123!";
// Act
string result = _sut.HashString(password);
// Assert
result.Should().NotBeNullOrEmpty();
result.Should().NotBe(password);
}
[Fact]
public void HashString_WhenCalledMultipleTimesWithSameInput_ShouldReturnDifferentHashes()
{
// Arrange
string password = "TestPassword123!";
// Act
string hash1 = _sut.HashString(password);
string hash2 = _sut.HashString(password);
// Assert
hash1.Should().NotBe(hash2);
}
[Theory]
[InlineData(" ")]
[InlineData("short")]
[InlineData("verylongpasswordwithlotsofcharactersbutnostringformatting")]
[InlineData("Password123!")]
[InlineData("@#$%^&*()")]
public void HashString_WhenCalledWithDifferentInputs_ShouldGenerateValidHashes(string input)
{
// Act
string hash = _sut.HashString(input);
// Assert
hash.Should().NotBeNullOrEmpty();
// verify it's a valid Base64 string
Action decode = () => Convert.FromBase64String(hash);
decode.Should().NotThrow();
}
[Fact]
public void CheckStringAgainstHash_WhenPasswordMatches_ShouldReturnTrue()
{
// Arrange
string password = "TestPassword123!";
string hash = _sut.HashString(password);
// Act
bool result = _sut.CheckStringAgainstHash(password, hash);
// Assert
result.Should().BeTrue();
}
[Fact]
public void CheckStringAgainstHash_WhenPasswordDoesNotMatch_ShouldReturnFalse()
{
// Arrange
string password = "TestPassword123!";
string wrongPassword = "WrongPassword123!";
string hash = _sut.HashString(password);
// Act
bool result = _sut.CheckStringAgainstHash(wrongPassword, hash);
// Assert
result.Should().BeFalse();
}
[Theory]
[InlineData("")]
[InlineData("dGVzdA==")] // valid base64 but wrong length
[InlineData("YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXo=")] // valid base64 but wrong length
public void CheckStringAgainstHash_WhenHashIsInvalidLength_ShouldReturnFalse(string invalidHash)
{
// Arrange
string password = "TestPassword123!";
// Act
bool result = _sut.CheckStringAgainstHash(password, invalidHash);
// Assert
result.Should().BeFalse();
}
[Fact]
public void CheckStringAgainstHash_WhenHashIsNotBase64_ShouldThrowFormatException()
{
// Arrange
string password = "TestPassword123!";
string invalidHash = "not-base64-string";
// Act
Action act = () => _sut.CheckStringAgainstHash(password, invalidHash);
// Assert
act.Should().Throw<FormatException>();
}
[Theory]
[InlineData(null)]
public void HashString_WhenPasswordIsNull_ShouldThrowArgumentNullException(string? nullPassword)
{
// Act
Action act = () => _sut.HashString(nullPassword!);
// Assert
act.Should().Throw<ArgumentNullException>();
}
[Theory]
[InlineData(null)]
public void CheckStringAgainstHash_WhenPasswordIsNull_ShouldThrowArgumentNullException(string? nullPassword)
{
// Arrange
string hash = _sut.HashString("somepassword");
// Act
Action act = () => _sut.CheckStringAgainstHash(nullPassword!, hash);
// Assert
act.Should().Throw<ArgumentNullException>();
}
[Fact]
public void CheckStringAgainstHash_WhenHashIsNull_ShouldThrowArgumentNullException()
{
// Act
Action act = () => _sut.CheckStringAgainstHash("password", null!);
// Assert
act.Should().Throw<ArgumentNullException>();
}
}