PlotDirector/PlotLine.Tests/CharacterWorkspaceDatabaseTests.cs

29 lines
9.2 KiB
C#

using System.Data;using System.Text.Json;using Dapper;using Microsoft.Data.SqlClient;
internal static class CharacterWorkspaceDatabaseTests
{
public static async Task Run(string scopePath)
{
var settings=File.ReadLines("/etc/plotdirector/plotdirector.env").Single(s=>s.StartsWith("ConnectionStrings__DefaultConnection="));var builder=new SqlConnectionStringBuilder(settings[(settings.IndexOf('=')+1)..].Trim().Trim('"','\''));if(builder.InitialCatalog!="PlotDirector_Development")throw new Exception("Wrong configured database");await using var db=new SqlConnection(builder.ConnectionString);await db.OpenAsync();if(await db.ExecuteScalarAsync<string>("SELECT DB_NAME()")!="PlotDirector_Development")throw new Exception("Wrong effective database");var scope=JsonDocument.Parse(File.ReadAllText(scopePath)).RootElement;int project=scope.GetProperty("project").GetInt32(),owner=scope.GetProperty("user").GetInt32(),scene=scope.GetProperty("scene").GetInt32(),book=scope.GetProperty("book").GetInt32(),actor=scope.GetProperty("characters")[0].GetInt32();
if(await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.ProjectUserAccess a JOIN dbo.AppUser u ON u.UserID=a.UserID WHERE a.ProjectID=@project AND a.UserID=@owner AND a.IsActive=1 AND a.AccessRole=N'Owner' AND u.Email LIKE N'pwa-browser-%'",new{project,owner})!=1)throw new Exception("Explicitly disposable Development scope required");
int parent=await db.ExecuteScalarAsync<int>("SELECT TOP(1) RelationshipTypeID FROM dbo.RelationshipTypes WHERE TypeName=N'Parent'"),childType=await db.ExecuteScalarAsync<int>("SELECT TOP(1) RelationshipTypeID FROM dbo.RelationshipTypes WHERE TypeName=N'Child'"),friend=await db.ExecuteScalarAsync<int>("SELECT TOP(1) RelationshipTypeID FROM dbo.RelationshipTypes WHERE TypeName=N'Friend'"),state=await db.ExecuteScalarAsync<int>("SELECT TOP(1) RelationshipStateID FROM dbo.RelationshipStates ORDER BY SortOrder,RelationshipStateID");
void Check(bool ok,string text){if(!ok)throw new Exception(text);Console.WriteLine("PASS Development workspace SQL: "+text);}
async Task<int> NewCharacter(SqlTransaction tx)=>await db.QuerySingleAsync<int>("dbo.Character_Save",new{ProjectID=project,CharacterName="Isolated workspace regression "+Guid.NewGuid().ToString("N")},tx,commandType:CommandType.StoredProcedure);
async Task<int> Rel(SqlTransaction tx,int child,bool reciprocal=false,int? type=null,bool reverse=false)=>await db.QuerySingleAsync<int>("dbo.Relationship_Save",new{ProjectID=project,CharacterAID=reverse?child:actor,CharacterBID=reverse?actor:child,RelationshipTypeID=type??parent,IsPermanent=true,IsKnownToReader=false,IsInitialRelationship=true,InitialRelationshipStateID=state,IsReciprocal=reciprocal,Notes="Synthetic definition"},tx,commandType:CommandType.StoredProcedure);
async Task<int> Event(SqlTransaction tx,int r,string description="Synthetic event")=>await db.QuerySingleAsync<int>("dbo.RelationshipEvent_Save",new{CharacterRelationshipID=r,SceneID=scene,RelationshipStateID=state,Intensity=4,IsKnownToOtherCharacter=false,Description=description},tx,commandType:CommandType.StoredProcedure);
async Task<(string Version,int Events,int Other)> Frame(SqlTransaction tx,int r,int? e=null){using var rows=await db.QueryMultipleAsync("dbo.CharacterWorkspace_RelationshipFrame",new{CharacterID=actor,UserID=owner,RelationshipID=r,EventID=e},tx,commandType:CommandType.StoredProcedure);var row=(IDictionary<string,object>)(await rows.ReadAsync<dynamic>()).Single();await rows.ReadAsync<dynamic>();return((string)row["Version"],(int)row["EventCount"],(int)row["OtherPairRecords"]);}
async Task Change(SqlTransaction tx,int r,string version,string action,bool confirmed=true,int? e=null,string notes="Updated isolated definition",int? user=null)=>await db.ExecuteAsync("dbo.CharacterWorkspace_ChangeRelationship",new{CharacterID=actor,UserID=user??owner,RelationshipID=r,Version=version,Action=action,Confirmed=confirmed,EventID=e,Notes=notes,StateID=state,Intensity=6,Awareness=true},tx,commandType:CommandType.StoredProcedure);
async Task Case(string name,Func<SqlTransaction,Task> action){using var tx=db.BeginTransaction();try{await action(tx);}finally{try{tx.Rollback();}catch(InvalidOperationException){}}Console.WriteLine("PASS rolled back isolated case: "+name);}
await Case("parent archive retains history and restores",async tx=>{int c=await NewCharacter(tx),r=await Rel(tx,c);await Event(tx,r);await Event(tx,r);var frame=await Frame(tx,r);Check(frame.Events==2,"preview reports dependent scene events");await Change(tx,r,frame.Version,"archive");Check(await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.CharacterRelationships WHERE CharacterRelationshipID=@r AND IsArchived=1",new{r},tx)==1&&await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.RelationshipEvents WHERE CharacterRelationshipID=@r",new{r},tx)==2,"erroneous parent definition archives reversibly without cascading its two events");await db.ExecuteAsync("dbo.Archive_Restore",new{EntityType="Relationship",EntityID=r},tx,commandType:CommandType.StoredProcedure);Check(await db.ExecuteScalarAsync<int>("SELECT IsArchived FROM dbo.CharacterRelationships WHERE CharacterRelationshipID=@r",new{r},tx)==0,"existing canonical restore reactivates the same definition and retained history");});
await Case("reciprocal single record and independent reverse",async tx=>{int c=await NewCharacter(tx),r=await Rel(tx,c,true);Check(await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.CharacterRelationships WHERE CharacterAID=@actor AND CharacterBID=@c OR CharacterAID=@c AND CharacterBID=@actor",new{actor,c},tx)==1,"canonical reciprocal flag does not create an extra reverse row");int reverse=await Rel(tx,c,false,childType,true);var frame=await Frame(tx,r);Check(frame.Other==1,"confirmation distinguishes a separately authored reverse fact");await Change(tx,r,frame.Version,"archive");Check(await db.ExecuteScalarAsync<int>("SELECT IsArchived FROM dbo.CharacterRelationships WHERE CharacterRelationshipID=@reverse",new{reverse},tx)==0,"independent reverse fact is retained, not silently cascaded");});
foreach(var type in new[]{parent,friend})await Case("definition edit "+type,async tx=>{int c=await NewCharacter(tx),r=await Rel(tx,c,false,type);var frame=await Frame(tx,r);await Change(tx,r,frame.Version,"definition");var row=await db.QuerySingleAsync<(int Type,int A,int B,bool Initial,string Notes)>("SELECT RelationshipTypeID,CharacterAID,CharacterBID,IsInitialRelationship,Notes FROM dbo.CharacterRelationships WHERE CharacterRelationshipID=@r",new{r},tx);Check(row.Type==type&&row.A==actor&&row.B==c&&row.Initial&&row.Notes=="Updated isolated definition","focused definition edit preserves pair/type and family/story meaning");});
await Case("single event edit then remove",async tx=>{int c=await NewCharacter(tx),r=await Rel(tx,c);int e=await Event(tx,r),other=await Event(tx,r);var frame=await Frame(tx,r,e);await Change(tx,r,frame.Version,"event-edit",e:e,notes:"Updated one event");Check(await db.ExecuteScalarAsync<string>("SELECT Description FROM dbo.RelationshipEvents WHERE RelationshipEventID=@e",new{e},tx)=="Updated one event","one event changes without rewriting the definition");frame=await Frame(tx,r,e);await Change(tx,r,frame.Version,"event-remove",e:e);Check(await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.RelationshipEvents WHERE RelationshipEventID=@other",new{other},tx)==1&&await db.ExecuteScalarAsync<int>("SELECT IsArchived FROM dbo.CharacterRelationships WHERE CharacterRelationshipID=@r",new{r},tx)==0,"single-event deletion leaves the other event and definition active");});
await Case("stale dependent history",async tx=>{int c=await NewCharacter(tx),r=await Rel(tx,c);var frame=await Frame(tx,r);await Event(tx,r);try{await Change(tx,r,frame.Version,"archive");throw new Exception("Stale archive accepted");}catch(SqlException ex)when(ex.Number==51021){Check(true,"new dependent event invalidates the confirmation atomically");}});
await Case("permission enforcement",async tx=>{int c=await NewCharacter(tx),r=await Rel(tx,c);var frame=await Frame(tx,r);try{await Change(tx,r,frame.Version,"archive",user:-991);throw new Exception("Foreign user accepted");}catch(SqlException ex)when(ex.Number==51020){Check(true,"ungranted user cannot mutate a definition");}});
await Case("missing explicit confirmation",async tx=>{int c=await NewCharacter(tx),r=await Rel(tx,c);var frame=await Frame(tx,r);try{await Change(tx,r,frame.Version,"archive",false);throw new Exception("Unconfirmed accepted");}catch(SqlException ex)when(ex.Number==51022){Check(true,"SQL enforces explicit destructive confirmation");}});
await Case("protected source event",async tx=>{int c=await NewCharacter(tx),r=await Rel(tx,c),e=await Event(tx,r);await db.ExecuteAsync("INSERT dbo.ManuscriptEvidenceIndex(BookID,EvidenceID,EventKind,EventID,IsPrimary,EvidenceState) VALUES(@book,NEWID(),'Relationship',@e,1,N'Verified')",new{book,e},tx);var frame=await Frame(tx,r,e);try{await Change(tx,r,frame.Version,"event-remove",e:e);throw new Exception("Protected deletion accepted");}catch(SqlException ex)when(ex.Number==51022){Check(true,"evidence-linked event is blocked before canonical deletion");}});
Check(await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.Characters WHERE CharacterName LIKE N'Isolated workspace regression %'")==0,"all new character/relationship/event fixtures rolled back; no manuscript relationships changed");
}
}