Files
Academic-Affairs-System/tests/Jiaowu.Api.Tests/AuditLogRetentionWorkerTests.cs
T

74 lines
2.6 KiB
C#

using Jiaowu.Api.Domain.System;
using Jiaowu.Api.Infrastructure.Operations;
using Jiaowu.Api.Infrastructure.Persistence;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging.Abstractions;
namespace Jiaowu.Api.Tests;
public sealed class AuditLogRetentionWorkerTests
{
[Fact]
public async Task Cleanup_removes_only_records_older_than_retention_window()
{
var databasePath = Path.Combine(
Path.GetTempPath(),
$"jiaowu-audit-retention-{Guid.NewGuid():N}.sqlite");
var services = new ServiceCollection();
services.AddDbContext<AppDbContext>(options =>
options.UseSqlite($"Data Source={databasePath};Pooling=False"));
var provider = services.BuildServiceProvider();
try
{
await using (var scope = provider.CreateAsyncScope())
{
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
await db.Database.EnsureCreatedAsync();
db.AuditLogs.AddRange(
CreateLog(DateTime.UtcNow.AddDays(-366), "/api/old-1"),
CreateLog(DateTime.UtcNow.AddDays(-400), "/api/old-2"),
CreateLog(DateTime.UtcNow.AddDays(-10), "/api/current"));
await db.SaveChangesAsync();
}
var worker = new AuditLogRetentionWorker(
provider.GetRequiredService<IServiceScopeFactory>(),
new OperationsOptions
{
AuditRetentionDays = 365,
AuditCleanupBatchSize = 100
},
TimeProvider.System,
NullLogger<AuditLogRetentionWorker>.Instance);
var removed = await worker.CleanupOnceAsync(CancellationToken.None);
Assert.Equal(2, removed);
await using var assertScope = provider.CreateAsyncScope();
var remaining = await assertScope.ServiceProvider
.GetRequiredService<AppDbContext>()
.AuditLogs.AsNoTracking()
.Select(x => x.Path)
.ToArrayAsync();
Assert.Equal(["/api/current"], remaining);
}
finally
{
await provider.DisposeAsync();
File.Delete(databasePath);
}
}
private static AuditLog CreateLog(DateTime createdAt, string path) =>
new()
{
Method = "POST",
Path = path,
StatusCode = 200,
CreatedAt = createdAt,
UpdatedAt = createdAt
};
}