PlotDirector/PlotLine.Tests/MapGeographicHierarchyDatabaseTests.cs

57 lines
7.4 KiB
C#

// Explicit Development-only test. Creates/restores only a new project owned by a disposable 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;
using PlotLine.Services;
internal static class MapGeographicHierarchyDatabaseTests
{
static void Check(bool ok,string message){if(!ok)throw new InvalidOperationException(message);}
static readonly JsonSerializerOptions Json=new(JsonSerializerDefaults.Web);
public static async Task Run(string path,bool topology=false)
{
Check(Path.GetFullPath(path).StartsWith("/tmp/pd-dev-browser-",StringComparison.Ordinal),"Dedicated identity required.");
using var identity=JsonDocument.Parse(await File.ReadAllTextAsync(path));var account=identity.RootElement;
Check(account.GetProperty("Database").GetString()=="PlotDirector_Development"&&account.GetProperty("Email").GetString()!.StartsWith("pwa-browser-"),"Wrong test account scope.");
var start=new ProcessStartInfo("sudo"){RedirectStandardOutput=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();Check(process.ExitCode==0,"Development configuration unavailable.");
var connectionString=environment.Split('\n').Single(s=>s.StartsWith("ConnectionStrings__DefaultConnection=")).Split('=',2)[1].Trim().Trim('"','\'');
Check(new SqlConnectionStringBuilder(connectionString).InitialCatalog=="PlotDirector_Development","Wrong configured database.");
using var db=new SqlConnection(connectionString);await db.OpenAsync();Check(await db.ExecuteScalarAsync<string>("SELECT DB_NAME()") == "PlotDirector_Development","Wrong effective 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 user.");
var config=new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string,string?>{{"ConnectionStrings:DefaultConnection",connectionString}}).Build();var factory=new SqlConnectionFactory(config);
var title="Hierarchy geography 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 ids=new Dictionary<string,int>();
var specifications=topology?new (string,string?)[]{("Birmingham",null),("Solihull",null),("Third area",null),("Boundary house","Birmingham")}:new (string,string?)[]{("Rubery",null),("Frankley",null),("Redditch",null),("Barmouth",null),("The Doweries","Rubery"),("Maggie's flat","The Doweries"),("Forest","Rubery"),("Reservoir","Frankley"),("Own place","Rubery"),("Own child","Own place")};
foreach(var (name,parent) in specifications)
ids[name]=await locations.SaveAsync(new(){ProjectID=project,LocationName=name,ParentLocationID=parent is null?null:ids[parent]});
var maps=new MapRepository(factory);var map=await maps.CreateAsync(new(){ProjectID=project,Name="Isolated hierarchy geography",Kind="Region"},user);
var input=Path.Combine(Path.GetDirectoryName(path)!,topology?"topology-input.json":"hierarchy-input.json");var output=Path.Combine(Path.GetDirectoryName(path)!,topology?"topology-fixture.json":"hierarchy-fixture.json");
await File.WriteAllTextAsync(input,JsonSerializer.Serialize(new{projectId=project,mapId=map,locations=await locations.ListByProjectAsync(project)},Json));
var node=new ProcessStartInfo("node");node.ArgumentList.Add(topology?"PlotLine.Tests/Browser/maps-topology-fixture.cjs":"PlotLine.Tests/Browser/maps-geography-hierarchy-fixture.cjs");node.ArgumentList.Add(input);node.ArgumentList.Add(output);using var generator=Process.Start(node)!;await generator.WaitForExitAsync();Check(generator.ExitCode==0,"Fixture projection failed.");
using var fixture=JsonDocument.Parse(await File.ReadAllTextAsync(output));var before=fixture.RootElement.GetProperty("before").Deserialize<List<MapFeature>>(Json)!;var after=fixture.RootElement.GetProperty("after").Deserialize<List<MapFeature>>(Json)!;
var document=(await maps.GetAsync(project,map,user))!;document.Features=before;Check(MapValidation.Validate(document) is null,"Original fixture validates.");await maps.SaveAsync(document,user);document=(await maps.GetAsync(project,map,user))!;
document.Features=after;Check(MapValidation.Validate(document) is null,"Complete transformed fixture validates.");await maps.SaveAsync(document,user);document=(await maps.GetAsync(project,map,user))!;Verify(document,after);
var backup=(await new ProjectBackupRepository(factory).GetProjectBackupAsync(project,user))!;var imported=JsonSerializer.Deserialize<ProjectBackupExport>(JsonSerializer.Serialize(backup))!;
Check(imported.Data.MapFeatures.All(f=>after.Any(a=>a.FeatureID==f.FeatureID&&a.GeometryJson==f.GeometryJson)),"Export/import retains complete road and boundary geometry.");
document.Features=before;await maps.SaveAsync(document,user);
Check(await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.Projects WHERE ProjectID=@project AND ProjectName=@title",new{project,title})==1,"Verify unique owned restore target.");
await db.ExecuteAsync("dbo.ProjectRestore_ApplyFromJson",new{ProjectID=project,JsonData=BookRecoveryRepository.Encode(imported,null)},commandType:CommandType.StoredProcedure,commandTimeout:180);
document=(await maps.GetAsync(project,map,user))!;Verify(document,after);
if(topology)Check((await locations.GetAsync(ids["Boundary house"]))!.ParentLocationID==ids["Birmingham"],"Shared topology never rewrites canonical parents.");
else Check((await locations.GetAsync(ids["Maggie's flat"]))!.ParentLocationID==ids["The Doweries"]&&(await locations.GetAsync(ids["The Doweries"]))!.ParentLocationID==ids["Rubery"],"Canonical hierarchy remains intact.");
// Leave only this owned map at its original positions for authenticated acceptance; normal identity cleanup removes it.
document.Features=before;await maps.SaveAsync(document,user);
Console.WriteLine(topology?"PASS Development shared vertices/edges, three-way junction, private curves and styles Save/reload, export/import/full-project restore, original identities/anchors/parents; isolated fixture ready.":"PASS Development complete transformed map Save/reload, backup/export/import/full-project restore, road/settlement JSON, canonical hierarchy and identities. Owned fixture ready for browser acceptance.");
}
static void Verify(MapDocument document,List<MapFeature> expected)
{
Check(document.Features.Count==expected.Count,"All pieces preserved.");
foreach(var f in expected){var actual=document.Features.Single(a=>a.FeatureID==f.FeatureID);Check((actual.X,actual.Y,actual.Width,actual.Height,actual.Rotation,actual.LabelX,actual.LabelY,actual.GeometryJson,actual.LocationID,actual.StartFeatureID,actual.EndFeatureID)==(f.X,f.Y,f.Width,f.Height,f.Rotation,f.LabelX,f.LabelY,f.GeometryJson,f.LocationID,f.StartFeatureID,f.EndFeatureID),"Exact transformed geometry, order, identity and connections persist.");}
}
}