PlotDirector/PlotLine.Tests/SqlLaunchResetTests.cs

70 lines
5.6 KiB
C#

using System.Data;
using System.Text.Json;
using Dapper;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging.Abstractions;
using PlotLine.Data;
using PlotLine.Services;
internal static class SqlLaunchResetTests
{
sealed record Contract(string procedure,string sql);
sealed class EnvironmentStub(string name):IHostEnvironment
{
public string EnvironmentName {get;set;}=name;
public string ApplicationName {get;set;}="Tests";
public string ContentRootPath {get;set;}=".";
public IFileProvider ContentRootFileProvider {get;set;}=new NullFileProvider();
}
static void Check(bool ok,string name){if(!ok)throw new Exception(name);Console.WriteLine("PASS "+name);}
public static async Task Run(bool express=false)
{
using var db=await SqlLaunchDatabaseTests.Open(express);
var contracts=JsonSerializer.Deserialize<Contract[]>(File.ReadAllText("PlotLine.Tests/Fixtures/SqlLaunchLegacyReset.json"),new JsonSerializerOptions{PropertyNameCaseInsensitive=true})!;
var owner=await db.ExecuteScalarAsync<int>("SELECT TOP(1) a.UserID FROM dbo.ProjectUserAccess a JOIN dbo.Books b ON b.ProjectID=a.ProjectID WHERE a.AccessRole=N'Owner' AND a.IsActive=1 ORDER BY (SELECT COUNT(*) FROM dbo.StoryIntelligenceBookPipelines p WHERE p.BookID=b.BookID) DESC");
foreach(var contract in contracts)
{
var results=new List<string>();var states=new List<string>();
foreach(var stored in new[]{false,true})
{
using var tx=db.BeginTransaction();
try
{
var row=await db.QuerySingleAsync(stored?contract.procedure:contract.sql,new{UserID=owner},tx,commandTimeout:120,commandType:stored?CommandType.StoredProcedure:CommandType.Text);
results.Add(JsonSerializer.Serialize((IDictionary<string,object>)row));
var tables=new[]{"Projects","StoryIntelligenceBookPipelines","StoryIntelligenceRuns","StoryMemoryCharacters","StoryMemoryLocations","StoryMemoryAssets","StoryMemoryIllustrationAssignments","StoryMemoryIllustrationDemands","IllustrationLibraryItems"};
var counts=new List<int>();foreach(var table in tables)counts.Add(await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.["+table+"]",transaction:tx));states.Add(string.Join(',',counts));
}
finally{tx.Rollback();}
}
Check(results[0]==results[1]&&states[0]==states[1],contract.procedure+" populated owner preparation/verification parity, all mutations rolled back");
}
var config=new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string,string?>{{"ConnectionStrings:DefaultConnection",SqlLaunchDatabaseTests.ConfiguredConnectionString(db)}}).Build();var factory=new SqlConnectionFactory(config);var projects=new ProjectRepository(factory);
var author=await db.ExecuteScalarAsync<int>("INSERT dbo.AppUser(Email,DisplayName,PasswordHash) VALUES(CONVERT(nvarchar(36),NEWID())+N'@sql-launch.invalid',N'Synthetic SQL reset',N'not-a-credential');SELECT CONVERT(int,SCOPE_IDENTITY());");
var owned=0;var shared=0;
try
{
owned=await projects.SaveAsync(new(){ProjectName="Synthetic owned reset",CreatedByUserID=author},author,null);
shared=await projects.SaveAsync(new(){ProjectName="Synthetic shared reset",CreatedByUserID=owner},owner,null);
await db.ExecuteAsync("INSERT dbo.ProjectUserAccess(ProjectID,UserID,AccessRole,IsActive) VALUES(@shared,@author,N'Collaborator',1)",new{shared,author});
var service=new StoryIntelligenceDevelopmentResetService(factory,projects,NullLogger<StoryIntelligenceDevelopmentResetService>.Instance,new EnvironmentStub("Production"));
try{await service.ResetOwnedProjectsAndImportsAsync(author);throw new Exception("Production reset accepted");}catch(InvalidOperationException e)when(e.Message.Contains("only in Development")){}
Check(await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.Projects WHERE ProjectID=@owned",new{owned})==1,"Production environment guard rejects reset before mutation");
var illustrations=await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.IllustrationLibraryItems");
service=new(factory,projects,NullLogger<StoryIntelligenceDevelopmentResetService>.Instance,new EnvironmentStub("Development"));
var result=await service.ResetOwnedProjectsAndImportsAsync(author);
Check(result.Success&&result.DeletedProjects==1,"Actual Development reset service deletes exactly the owned fixture");
Check(await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.Projects WHERE ProjectID=@shared",new{shared})==1,"Collaborator project preserved by normal owner checks");
Check(await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.IllustrationLibraryItems")==illustrations,"Shared illustration library retained");
}
finally
{
if(owned>0 && await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.Projects WHERE ProjectID=@owned",new{owned})>0){await projects.ArchiveForOwnerAsync(owned,author);await projects.HardDeleteForOwnerAsync(owned,author);}
if(shared>0){await projects.ArchiveForOwnerAsync(shared,owner);await projects.HardDeleteForOwnerAsync(shared,owner);}
await db.ExecuteAsync("DELETE dbo.ProjectUserAccess WHERE UserID=@author;DELETE dbo.AppUser WHERE UserID=@author AND Email LIKE N'%@sql-launch.invalid'",new{author});
}
}
}