Files
pos-system/services/iam-service-net/tests/IamService.FunctionalTests/CustomWebApplicationFactory.cs
Ho Ngoc Hai fdcc24bdf4 feat(infrastructure): Enhance dependency injection for Redis caching and add InMemory cache service for testing
- Updated AddInfrastructure method to accept an environment name parameter for conditional Redis caching configuration.
- Implemented logic to skip Redis caching setup in the Testing environment.
- Added InMemoryCacheService for testing purposes, providing a mock implementation of ICacheService.
- Enhanced TransactionBehavior to skip transactions for InMemory databases.
- Updated functional tests to remove Redis-related services and ensure proper database setup for testing.
2026-01-12 19:04:49 +07:00

187 lines
6.9 KiB
C#

using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using IamService.Infrastructure;
using IamService.Infrastructure.Caching;
using StackExchange.Redis;
namespace IamService.FunctionalTests;
/// <summary>
/// EN: Custom WebApplicationFactory for functional tests.
/// VI: WebApplicationFactory tùy chỉnh cho functional tests.
/// </summary>
public class CustomWebApplicationFactory : WebApplicationFactory<Program>
{
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder.UseEnvironment("Testing");
builder.ConfigureServices(services =>
{
// EN: Remove Redis-related registrations FIRST (before they get resolved)
// VI: Xóa các đăng ký liên quan đến Redis TRƯỚC TIÊN (trước khi chúng được resolve)
var redisDescriptors = services.Where(d =>
d.ServiceType == typeof(IConnectionMultiplexer) ||
d.ServiceType == typeof(ICacheService) ||
d.ImplementationType?.FullName?.Contains("Redis") == true ||
d.ServiceType.FullName?.Contains("Redis") == true)
.ToList();
foreach (var descriptor in redisDescriptors)
{
services.Remove(descriptor);
}
// EN: Remove ALL DbContext-related registrations
// VI: Xóa TẤT CẢ các đăng ký liên quan đến DbContext
var descriptorsToRemove = services.Where(
d => d.ServiceType == typeof(DbContextOptions<IamServiceContext>) ||
d.ServiceType == typeof(IamServiceContext) ||
d.ServiceType.FullName?.Contains("EntityFrameworkCore") == true ||
d.ImplementationType?.FullName?.Contains("Npgsql") == true)
.ToList();
foreach (var descriptor in descriptorsToRemove)
{
services.Remove(descriptor);
}
// EN: Remove the DbContextOptions generic
// VI: Xóa DbContextOptions generic
services.RemoveAll(typeof(DbContextOptions));
// EN: Add mock cache service for testing
// VI: Thêm mock cache service để test
services.AddSingleton<ICacheService, InMemoryCacheService>();
// EN: Add in-memory database for testing
// VI: Thêm in-memory database để test
var dbName = "TestDatabase_" + Guid.NewGuid().ToString();
services.AddDbContext<IamServiceContext>(options =>
{
options.UseInMemoryDatabase(dbName);
options.UseOpenIddict(); // EN: Required for OpenIddict / VI: Cần cho OpenIddict
options.EnableSensitiveDataLogging();
});
});
}
/// <summary>
/// EN: Ensure database is created after host is built
/// VI: Đảm bảo database được tạo sau khi host được build
/// </summary>
protected override void ConfigureClient(HttpClient client)
{
base.ConfigureClient(client);
// EN: Create the database when the first client is created
// VI: Tạo database khi client đầu tiên được tạo
using var scope = Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<IamServiceContext>();
db.Database.EnsureCreated();
}
}
/// <summary>
/// EN: In-memory cache service for testing
/// VI: Cache service in-memory cho testing
/// </summary>
public class InMemoryCacheService : ICacheService
{
private readonly Dictionary<string, (object Value, DateTime? Expiry)> _cache = new();
private readonly HashSet<string> _blacklist = new();
public Task<T?> GetAsync<T>(string key, CancellationToken cancellationToken = default) where T : class
{
if (_cache.TryGetValue(key, out var entry))
{
if (entry.Expiry == null || entry.Expiry > DateTime.UtcNow)
{
return Task.FromResult((T?)entry.Value);
}
_cache.Remove(key);
}
return Task.FromResult<T?>(null);
}
public Task<string?> GetStringAsync(string key, CancellationToken cancellationToken = default)
{
if (_cache.TryGetValue(key, out var entry))
{
if (entry.Expiry == null || entry.Expiry > DateTime.UtcNow)
{
return Task.FromResult((string?)entry.Value);
}
_cache.Remove(key);
}
return Task.FromResult<string?>(null);
}
public Task SetAsync<T>(string key, T value, TimeSpan? expiration = null, CancellationToken cancellationToken = default) where T : class
{
var expiry = expiration.HasValue ? DateTime.UtcNow.Add(expiration.Value) : (DateTime?)null;
_cache[key] = (value, expiry);
return Task.CompletedTask;
}
public Task SetStringAsync(string key, string value, TimeSpan? expiration = null, CancellationToken cancellationToken = default)
{
var expiry = expiration.HasValue ? DateTime.UtcNow.Add(expiration.Value) : (DateTime?)null;
_cache[key] = (value, expiry);
return Task.CompletedTask;
}
public Task RemoveAsync(string key, CancellationToken cancellationToken = default)
{
_cache.Remove(key);
return Task.CompletedTask;
}
public Task RemoveByPatternAsync(string pattern, CancellationToken cancellationToken = default)
{
var keysToRemove = _cache.Keys.Where(k => k.Contains(pattern.Replace("*", ""))).ToList();
foreach (var key in keysToRemove)
{
_cache.Remove(key);
}
return Task.CompletedTask;
}
public Task<bool> ExistsAsync(string key, CancellationToken cancellationToken = default)
{
if (_cache.TryGetValue(key, out var entry))
{
if (entry.Expiry == null || entry.Expiry > DateTime.UtcNow)
{
return Task.FromResult(true);
}
_cache.Remove(key);
}
return Task.FromResult(false);
}
public async Task<T?> GetOrSetAsync<T>(string key, Func<Task<T>> factory, TimeSpan? expiration = null, CancellationToken cancellationToken = default) where T : class
{
var cached = await GetAsync<T>(key, cancellationToken);
if (cached != null) return cached;
var value = await factory();
await SetAsync(key, value, expiration, cancellationToken);
return value;
}
public Task BlacklistAsync(string key, TimeSpan expiration, CancellationToken cancellationToken = default)
{
_blacklist.Add(key);
return Task.CompletedTask;
}
public Task<bool> IsBlacklistedAsync(string key, CancellationToken cancellationToken = default)
{
return Task.FromResult(_blacklist.Contains(key));
}
}