41 lines
1.2 KiB
C#
41 lines
1.2 KiB
C#
using Microsoft.EntityFrameworkCore;
|
|
using global::BuildFlow.Shared.Domain.Common;
|
|
|
|
namespace BuildFlow.Workflow.Tests;
|
|
|
|
|
|
public static class TestDbFactory
|
|
{
|
|
/// <summary>新建带审计模拟的 InMemory DbContext。</summary>
|
|
public static WorkflowDbContext Create()
|
|
{
|
|
var options = new DbContextOptionsBuilder<WorkflowDbContext>()
|
|
.UseInMemoryDatabase($"wf-test-{Guid.NewGuid()}")
|
|
.Options;
|
|
var db = new WorkflowDbContext(options);
|
|
AttachAuditStub(db);
|
|
return db;
|
|
}
|
|
|
|
/// <summary>给已有 DbContext 挂上审计字段自动填充(供各测试 helper 复用)。</summary>
|
|
public static void AttachAuditStub(WorkflowDbContext db)
|
|
{
|
|
db.SavingChanges += (sender, _) =>
|
|
{
|
|
if (sender is not DbContext ctx) return;
|
|
foreach (var entry in ctx.ChangeTracker.Entries())
|
|
{
|
|
if (entry.Entity is IAuditable a)
|
|
{
|
|
a.CreatedBy ??= "test";
|
|
a.UpdatedBy ??= "test";
|
|
}
|
|
if (entry.Entity is IHasOperatorIP o)
|
|
{
|
|
o.OperatorIP ??= "127.0.0.1";
|
|
}
|
|
}
|
|
};
|
|
}
|
|
}
|