PlotDirector/PlotLine.Tests/CharacterWorkspaceDatabaseTests.cs

47 lines
15 KiB
C#

using PlotLine.Models;
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("global grouped alphabetical pagination",async tx=>{
string token="Isolated workspace regression Group "+Guid.NewGuid().ToString("N");var expected=new List<(int ID,string Name)>();
for(int i=0;i<28;i++){string name=token+" "+(i==0?"alpha":i==1?"ALPHA":((char)('b'+i%22)).ToString()+i.ToString("00"));int c=await db.QuerySingleAsync<int>("dbo.Character_Save",new{ProjectID=project,CharacterName=name},tx,commandType:CommandType.StoredProcedure);expected.Add((c,name));await Rel(tx,c);}
int focus=expected[0].ID;await Rel(tx,focus,false,friend);await Rel(tx,focus,false,childType,true);for(int i=0;i<25;i++)await Rel(tx,focus);
async Task<(int Total,List<dynamic> Rows)> Read(int page=1,string? category=null,int? other=null,int definitionPage=1){using var grid=await db.QueryMultipleAsync("dbo.CharacterWorkspace_Relationships",new{CharacterID=actor,UserID=owner,Page=page,Search=token,Category=category,OtherCharacterID=other,DefinitionPage=definitionPage},tx,commandType:CommandType.StoredProcedure);int total=await grid.ReadSingleAsync<int>();await grid.ReadAsync<dynamic>();await grid.ReadAsync<dynamic>();await grid.ReadAsync<dynamic>();return(total,(await grid.ReadAsync<dynamic>()).ToList());}
var first=await Read();var second=await Read(2);var actual=first.Rows.Concat(second.Rows).Select(r=>(int)((int)r.CharacterAID==actor?r.CharacterBID:r.CharacterAID)).Distinct().ToArray();var sorted=expected.OrderBy(e=>e.Name,StringComparer.OrdinalIgnoreCase).ThenBy(e=>e.ID).Select(e=>e.ID).ToArray();Check(first.Total==28&&actual.SequenceEqual(sorted),"case-insensitive alphabetical groups span all pages, direction independent and duplicate names stable by identity");
var group=await Read(other:focus);var more=await Read(other:focus,definitionPage:2);Check(group.Total==1&&group.Rows.Count==25&&more.Rows.Count==3,"one character group retains 28 distinct definitions with bounded inner pagination");
var family=await Read(category:"family",other:focus);var story=await Read(category:"story",other:focus);Check(family.Total==1&&story.Total==1&&story.Rows.Count==1&&(string)story.Rows[0].RelationshipTypeName=="Friend","family/story filters classify individual definitions, including one pair in both categories");
Check(await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.CharacterRelationships WHERE ProjectID=@project AND (CharacterAID=@focus AND CharacterBID=@actor OR CharacterBID=@focus AND CharacterAID=@actor)",new{project,focus,actor},tx)==28,"grouping and pagination never merge or deduplicate canonical definitions");
});
async Task Structural(SqlTransaction tx,int r,string v,int type,bool reverse=false,bool? reciprocal=null)=>await db.ExecuteAsync("dbo.CharacterWorkspace_ChangeRelationship",new{CharacterID=actor,UserID=owner,RelationshipID=r,Version=v,Action="definition",Notes="Structural isolated edit",TypeID=type,ReverseDirection=reverse,Reciprocal=reciprocal},tx,commandType:CommandType.StoredProcedure);
await Case("canonical type and direction edits retain record",async tx=>{int c=await NewCharacter(tx),r=await Rel(tx,c);var frame=await Frame(tx,r);await Structural(tx,r,frame.Version,childType,true);var row=await db.QuerySingleAsync<(int Type,int A,int B)>("SELECT RelationshipTypeID,CharacterAID,CharacterBID FROM dbo.CharacterRelationships WHERE CharacterRelationshipID=@r",new{r},tx);Check(row.Type==childType&&row.A==c&&row.B==actor,"canonical family type/direction edit retains exact definition ID without recreating records");});
await Case("story reciprocity edit retains one record",async tx=>{int c=await NewCharacter(tx),r=await Rel(tx,c,false,friend);var frame=await Frame(tx,r);await Structural(tx,r,frame.Version,friend,reciprocal:true);Check(await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.CharacterRelationships WHERE CharacterRelationshipID=@r AND IsReciprocal=1",new{r},tx)==1,"story reciprocity is one flag on the same canonical definition");});
await Case("incompatible category rejected",async tx=>{int c=await NewCharacter(tx),r=await Rel(tx,c);var frame=await Frame(tx,r);try{await Structural(tx,r,frame.Version,friend);throw new Exception("Cross-category change accepted");}catch(SqlException ex)when(ex.Number==51022){Check(true,"cross-category type change requires full-editor review");}});
await Case("history prevents semantic rewrite",async tx=>{int c=await NewCharacter(tx),r=await Rel(tx,c);await Event(tx,r);var frame=await Frame(tx,r);try{await Structural(tx,r,frame.Version,childType);throw new Exception("History reinterpretation accepted");}catch(SqlException ex)when(ex.Number==51022){Check(true,"dependent history prevents unsafe structural reinterpretation");}});
await Case("family reciprocity cannot manufacture reverse parentage",async tx=>{int c=await NewCharacter(tx),r=await Rel(tx,c);var frame=await Frame(tx,r);try{await Structural(tx,r,frame.Version,parent,reciprocal:true);throw new Exception("Family reciprocity change accepted");}catch(SqlException ex)when(ex.Number==51022){Check(true,"family reciprocity changes require explicit full-editor review");}});
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("dedicated history canonical order and bounded pages",async tx=>{int c=await NewCharacter(tx),r=await Rel(tx,c);for(int i=0;i<28;i++)await Event(tx,r,"Recorded history "+i);async Task<List<RelationshipProgressionPoint>> Read(int page){using var grid=await db.QueryMultipleAsync("dbo.Dynamics_RelationshipEvolution",new{CharacterRelationshipID=r,Page=page},tx,commandType:CommandType.StoredProcedure);await grid.ReadAsync<CharacterRelationship>();var rows=(await grid.ReadAsync<RelationshipProgressionPoint>()).ToList();await grid.ReadAsync<dynamic>();return rows;}var first=await Read(1);var second=await Read(2);Check(first.Count==25&&second.Count==3&&first.All(e=>e.TotalRecords==28),"dedicated history pages 28 actual events as 25 + 3 with no synthetic transitions");Check(first.Concat(second).Select(e=>e.RelationshipEventID).SequenceEqual(first.Concat(second).Select(e=>e.RelationshipEventID).OrderBy(id=>id)),"same-scene developments retain stable canonical event order");});
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");
}
}