59 lines
1.7 KiB
C#
59 lines
1.7 KiB
C#
using Microsoft.Data.Sqlite;
|
||
using Microsoft.EntityFrameworkCore;
|
||
using TakeoutSaaS.Infrastructure.Dictionary.Persistence;
|
||
|
||
namespace TakeoutSaaS.Integration.Tests.Fixtures;
|
||
|
||
/// <summary>
|
||
/// 集成测试用 SQLite 内存数据库(字典库)。
|
||
/// </summary>
|
||
public sealed class DictionarySqliteTestDatabase : IDisposable
|
||
{
|
||
private readonly SqliteConnection _connection;
|
||
private readonly TestIdGenerator _idGenerator = new();
|
||
private bool _initialized;
|
||
|
||
public DictionarySqliteTestDatabase()
|
||
{
|
||
_connection = new SqliteConnection("Filename=:memory:");
|
||
_connection.Open();
|
||
Options = new DbContextOptionsBuilder<DictionaryDbContext>()
|
||
.UseSqlite(_connection)
|
||
.EnableSensitiveDataLogging()
|
||
.Options;
|
||
}
|
||
|
||
public DbContextOptions<DictionaryDbContext> Options { get; }
|
||
|
||
public DictionaryDbContext CreateContext(long tenantId, long userId = 0)
|
||
{
|
||
EnsureCreated();
|
||
// 1. AdminApi 不使用租户上下文;tenantId 参数仅用于兼容测试调用方签名
|
||
_ = tenantId;
|
||
|
||
// 2. (空行后) 按需注入当前用户与 ID 生成器
|
||
return new DictionaryDbContext(
|
||
Options,
|
||
userId == 0 ? null : new TestCurrentUserAccessor(userId),
|
||
_idGenerator);
|
||
}
|
||
|
||
public void EnsureCreated()
|
||
{
|
||
if (_initialized)
|
||
{
|
||
return;
|
||
}
|
||
|
||
// 1. 创建并初始化数据库结构
|
||
using var context = new DictionaryDbContext(Options, idGenerator: _idGenerator);
|
||
context.Database.EnsureCreated();
|
||
_initialized = true;
|
||
}
|
||
|
||
public void Dispose()
|
||
{
|
||
_connection.Dispose();
|
||
}
|
||
}
|