PlotDirector/PlotLine.Tests/MapSettlementDatabaseTests.cs

53 lines
6.1 KiB
C#

// Explicit Development-only persistence/restore regression. All data belongs to a disposable test identity.
using System.Data;
using System.Diagnostics;
using System.Text.Json;
using Dapper;
using Microsoft.Data.SqlClient;
using Microsoft.Extensions.Configuration;
using PlotLine.Data;
using PlotLine.Models;
internal static class MapSettlementDatabaseTests
{
static void Check(bool ok,string message){if(!ok)throw new InvalidOperationException(message);}
public static async Task Run(string path)
{
if(!Path.GetFullPath(path).StartsWith("/tmp/pd-dev-browser-",StringComparison.Ordinal))throw new InvalidOperationException("Dedicated Development identity required.");
using var identity=JsonDocument.Parse(await File.ReadAllTextAsync(path));var account=identity.RootElement;
if(account.GetProperty("Database").GetString()!="PlotDirector_Development"||!account.GetProperty("Email").GetString()!.StartsWith("pwa-browser-"))throw new InvalidOperationException("Wrong identity scope.");
var start=new ProcessStartInfo("sudo"){RedirectStandardOutput=true,RedirectStandardError=true};foreach(var arg in new[]{"-n","cat","/etc/plotdirector/plotdirector.env"})start.ArgumentList.Add(arg);
using var process=Process.Start(start)!;var environment=await process.StandardOutput.ReadToEndAsync();await process.WaitForExitAsync();if(process.ExitCode!=0)throw new InvalidOperationException("Development configuration unavailable.");
var connectionString=environment.Split('\n').Single(s=>s.StartsWith("ConnectionStrings__DefaultConnection=")).Split('=',2)[1].Trim().Trim('"','\'');
if(new SqlConnectionStringBuilder(connectionString).InitialCatalog!="PlotDirector_Development")throw new InvalidOperationException("Wrong configured database.");
using var db=new SqlConnection(connectionString);await db.OpenAsync();Check(await db.ExecuteScalarAsync<string>("SELECT DB_NAME()") == "PlotDirector_Development","Verify effective Development database.");
var user=account.GetProperty("UserID").GetInt32();Check(await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.AppUser WHERE UserID=@user AND Email=@email",new{user,email=account.GetProperty("Email").GetString()})==1,"Verify disposable account.");
var config=new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string,string?>{{"ConnectionStrings:DefaultConnection",connectionString}}).Build();var factory=new SqlConnectionFactory(config);
var title="Settlement boundary regression "+Guid.NewGuid().ToString("N");
var project=await db.QuerySingleAsync<int>("dbo.Project_Save",new{ProjectName=title,UserID=user},commandType:CommandType.StoredProcedure);
var locations=new LocationRepository(factory);var root=await locations.SaveAsync(new(){ProjectID=project,LocationName="Settlement fixture"});
var building=await locations.SaveAsync(new(){ProjectID=project,LocationName="Building fixture",ParentLocationID=root});
var maps=new MapRepository(factory);var map=await maps.CreateAsync(new(){ProjectID=project,Name="Boundary fixture",Kind="Local Area"},user);
var document=(await maps.GetAsync(project,map,user))!;
var town=new MapFeature{Name="Settlement fixture",Type="Town",LocationID=root,X=50,Y=70,GeometryJson="""{"drawingOrder":123456,"boundary":{"offsetX":20,"offsetY":-10,"width":330,"height":220,"rotation":12,"coast":"Rugged","points":[[-0.5,-0.5],[0.5,-0.5],[0.5,0.5],[-0.5,0.5]],"appearance":{"fillColor":"#9977aa","fillOpacity":0.3,"borderColor":"#443355","borderWidth":2,"borderStyle":"Dashed"}}}"""};
var house=new MapFeature{Name="Building fixture",Type="House",LocationID=building,X=60,Y=80};
var road=new MapFeature{Name="Road fixture",Type="Road",GeometryClass="Path",EndFeatureID=town.FeatureID};
document.Features=[town,house,road];await maps.SaveAsync(document,user);document=(await maps.GetAsync(project,map,user))!;
var boundary=town.GeometryJson;Check(document.Features.Single(f=>f.FeatureID==town.FeatureID).GeometryJson==boundary,"Save/reload retains exact boundary/style JSON.");
Check(document.Features.Single(f=>f.FeatureID==road.FeatureID).EndFeatureID==town.FeatureID,"Existing road reference still targets the Marker anchor.");
var export=(await new ProjectBackupRepository(factory).GetProjectBackupAsync(project,user))!;
var imported=JsonSerializer.Deserialize<ProjectBackupExport>(JsonSerializer.Serialize(export))!;
Check(imported.Data.MapFeatures.Single(f=>f.FeatureID==town.FeatureID).GeometryJson==boundary,"Real project export/import carries exact geometry.");
document.Features.Single(f=>f.FeatureID==town.FeatureID).GeometryJson="{}";await maps.SaveAsync(document,user);
// Restore only the unique project just created above, never a human project or the database itself.
Check(await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.Projects WHERE ProjectID=@project AND ProjectName=@title",new{project,title})==1,"Verify isolated restore target.");
await db.ExecuteAsync("dbo.ProjectRestore_ApplyFromJson",new{ProjectID=project,JsonData=BookRecoveryRepository.Encode(imported,null)},commandType:CommandType.StoredProcedure,commandTimeout:180);
var restored=(await maps.GetAsync(project,map,user))!;
Check(restored.Features.Single(f=>f.FeatureID==town.FeatureID).GeometryJson==boundary,"Full SQL project restore retains settlement boundaries.");
Check(restored.Features.Single(f=>f.FeatureID==town.FeatureID).LocationID==root && restored.Features.Single(f=>f.FeatureID==road.FeatureID).EndFeatureID==town.FeatureID,"Restore preserves story identity and connection targets.");
Check((await locations.GetAsync(building))!.ParentLocationID==root,"Map edits and restore preserve the building's story parent.");
Check(restored.Map.Revision>document.Map.Revision,"Restore invalidates stale editors.");
Console.WriteLine("PASS Development settlement JSON Save/reload, real backup/export/import, isolated full-project restore, anchor/road/story identity and stale-editor revision. Temporary account owns all fixtures for normal cleanup.");
}
}