using BuildFlow.Infrastructure.Persistence;
using BuildFlow.Shared.Domain.Common;
using Microsoft.EntityFrameworkCore;
namespace BuildFlow.Rag.Tests;
/// Rag 模块测试数据库工厂,使用独立 InMemory 数据库并自动补齐审计字段(IAuditable / IHasOperatorIP)。
internal static class RagTestDb
{
public static RagDbContext Create([System.Runtime.CompilerServices.CallerMemberName] string testName = "")
{
var options = new DbContextOptionsBuilder()
.UseInMemoryDatabase($"rag-{testName}-{Guid.NewGuid()}")
.Options;
var db = new RagDbContext(options);
db.SavingChanges += (_, _) => FillAudit(db);
return db;
}
/// 兜底补齐审计字段,供各测试文件的 CreateDb() 直接挂载 SavingChanges 事件。
public static void FillAudit(RagDbContext db)
{
foreach (var entry in db.ChangeTracker.Entries())
{
if (entry.Entity is IAuditable auditable)
{
auditable.CreatedBy ??= "test";
auditable.UpdatedBy ??= "test";
if (auditable.CreatedAt == default) auditable.CreatedAt = DateTime.UtcNow;
if (auditable.UpdatedAt == default) auditable.UpdatedAt = DateTime.UtcNow;
}
if (entry.Entity is IHasOperatorIP operatorEntity)
operatorEntity.OperatorIP ??= "127.0.0.1";
}
}
}