PlotDirector/PlotLine.Tests/GeographyTests.cs

121 lines
12 KiB
C#

using PlotLine.Models;
using PlotLine.Services;
using PlotLine.Data;
using System.Text.Json;
using System.Net;
using Microsoft.Extensions.Options;
using Microsoft.AspNetCore.Mvc;
using PlotLine.Controllers;
internal static class GeographyTests
{
private static void Check(bool value,string message){if(!value)throw new InvalidOperationException(message);}
public static async Task Run()
{
var rules=new GeographicRules(Path.GetFullPath("PlotLine/Data/Reference/Geography"));
foreach(var name in new[]{"United Kingdom","UK","England","Scotland","Wales","USA","United States","Japan","Brazil","South Africa","Australia","IND","GB-ENG","California, US"})
Check(rules.Root(name)!=null,"Recognised root: "+name);
foreach(var name in new[]{"Middle-earth","The Shire","California","Georgia","West Midlands"})Check(rules.Root(name)==null,"Unsafe root: "+name);
Check(rules.Root("Northern Ireland")?.SubdivisionCode=="GB-NIR","Northern Ireland is a distinct root.");
LocationItem Place(string name,string type,int? parent=null)=>new(){LocationName=name,LocationTypeName=type,ParentLocationID=parent};
var chain=new[]{Place("Rubery","Village",2),Place("England","Country")};
var query=rules.Query(chain)!;Check(query!=null && query.SubdivisionCode=="GB-ENG","Direct hierarchy.");
Check(rules.Query([Place("Rubery","Village",2),Place("Rednal","Town",3),Place("Birmingham","Town",4),Place("West Midlands","Region",5),Place("England","Country",6),Place("UK","Country")])?.Ancestors.Length==5,"Deep hierarchy.");
Check(rules.Query([Place("Hobbiton","Village",2),Place("Middle-earth","Country")])==null,"Fictional root.");
Check(rules.Query([Place("Pub","Building",2),Place("England","Country")])==null,"Premises excluded.");
Check(rules.Query([Place("England","Country",99)])==null,"Missing ancestor fails closed.");
var other=query! with {Ancestors=["Scotland"]};Check(GeographicRules.CacheKey(query!)!=GeographicRules.CacheKey(other),"Names in different regions cannot share a request.");
Check(GeographicRules.CacheKey(query!,"edition1")!=GeographicRules.CacheKey(query!,"edition2"),"Provider/edition isolate caches.");
var candidate=new GeographicCandidate("Fake","os-1","Rubery",52.4,-2,"GB",["England","GB-ENG"],"Synthetic test fixture");
Check(GeographicRules.Candidates(query!,[candidate,candidate,candidate with{CountryCode="US"},candidate with{Latitude=double.NaN}]).Count==1,"Filter invalid candidates and deduplicate provider identities.");
var queue=new QueueFake(chain);var provider=new ProviderFake([candidate]);
await new GeographicProcessor(queue,rules,provider).ProcessOneAsync(default);
Check(queue.Status=="Needs confirmation"&&provider.Calls==1,"Single provider ranking alone is ambiguous.");
queue.Requeue();await new GeographicProcessor(queue,rules,provider).ProcessOneAsync(default);
Check(provider.Calls==1,"Cached candidate identity avoids another provider request.");
queue.Requeue();queue.Cached=null;provider.Results=[candidate with{UniqueWithinContext=true}];
await new GeographicProcessor(queue,rules,provider).ProcessOneAsync(default);Check(queue.Status=="Resolved"&&queue.Match!=null,"Deterministic provider uniqueness resolves.");
queue.Requeue();queue.Cached=null;provider.Fail=true;
for(var attempt=0;attempt<4;attempt++){queue.Job.Attempts=attempt;await new GeographicProcessor(queue,rules,provider).ProcessOneAsync(default);}
Check(queue.Status=="Unresolved"&&queue.State=="Done"&&queue.Delay==480,"Retries bounded with exponential backoff.");
provider.Fail=false;queue.Requeue();queue.AllowReservation=false;var calls=provider.Calls;
Check(!await new GeographicProcessor(queue,rules,provider).ProcessOneAsync(default)&&provider.Calls==calls,"Database rate reservation must precede provider calls.");
queue.AllowReservation=true;queue.Requeue();provider.IsEnabled=false;
await new GeographicProcessor(queue,rules,provider).ProcessOneAsync(default);Check(queue.State=="Waiting configuration"&&provider.Calls==calls,"Unconfigured provider never called.");
queue.Requeue();queue.Chain=[Place("Hobbiton","Town",2),Place("Middle-earth","Country")];provider.IsEnabled=true;
await new GeographicProcessor(queue,rules,provider).ProcessOneAsync(default);Check(queue.Status=="Not eligible"&&provider.Calls==calls,"Fictional hierarchy never reaches provider.");
using(var response=JsonDocument.Parse("""
[{"osm_type":"node","osm_id":123,"name":"Newtown","lat":"52.5","lon":"-3.3","display_name":"Newtown, Powys, Wales, United Kingdom","addresstype":"town","address":{"town":"Newtown","county":"Powys","state":"Wales","ISO3166-2-lvl4":"GB-WLS","country_code":"gb"}}]
"""))
{
var result=NominatimGeocodingProvider.Parse(query! with{Name="Newtown",SubdivisionCode=null,Ancestors=["UK"]},response.RootElement);
Check(result.Count==1&&result[0].PlaceID=="node:123"&&!result[0].UniqueWithinContext,"Nominatim OSM identity, metadata and conservative ambiguity.");
Check(NominatimGeocodingProvider.Parse(query! with{Name="Newtown",SubdivisionCode="GB-WLS",Ancestors=["Wales","Powys"]},response.RootElement).Single().UniqueWithinContext,"Exact place plus matching county/constituent context resolves deterministically.");
Check(NominatimGeocodingProvider.Parse(query!,response.RootElement).Count==0,"Reject results outside explicit subdivision.");
}
var fallbackQueue=new QueueFake([Place("Test settlement","Village",2),Place("Nearby city","Town",3),Place("UK","Country")]);
var emptyProvider=new ProviderFake([]);
await new GeographicProcessor(fallbackQueue,rules,emptyProvider).ProcessOneAsync(default);
Check(fallbackQueue.Job.RelaxedContext&&fallbackQueue.Status=="Pending"&&fallbackQueue.Delay>=15,"Empty full-context lookup schedules one durable, rate-limited fallback.");
fallbackQueue.Cached=null;fallbackQueue.Requeue();
await new GeographicProcessor(fallbackQueue,rules,emptyProvider).ProcessOneAsync(default);
Check(fallbackQueue.Status=="Unresolved"&&emptyProvider.Calls==2,"Country fallback is bounded to one additional request.");
var denied=new GeographyController(null!,new DeniedAccess(),null!,null!,null!);
Check(await denied.State(7,null) is NotFoundResult,"Cross-account state rejected before repository.");
Check(await denied.Confirm(7,1,1,0) is NotFoundResult,"Cross-account coordinate confirmation rejected.");
Check(await denied.Retry(7,1,1) is NotFoundResult,"Cross-account retries rejected.");
Check(await denied.Exclude(7,1,1,true) is NotFoundResult,"Cross-account exclusion rejected.");
Check(await denied.Hierarchy(7,1,null!) is NotFoundResult,"Cross-account hierarchy admission rejected.");
Check(typeof(GeographyController).GetMethods().Where(m=>m.IsDefined(typeof(HttpPostAttribute),true))
.All(m=>m.IsDefined(typeof(ValidateAntiForgeryTokenAttribute),true)),"Every geography mutation requires antiforgery.");
var settings=new MonitorFake();var transport=new HttpFake();var nominatim=new NominatimGeocodingProvider(settings,transport);
Check(!nominatim.Enabled,"No external provider is enabled by default.");
settings.Value=new(){Enabled=true,Provider="Nominatim",WorkerHost=Environment.MachineName,UserAgent="PlotDirector/1.0 (+https://plotdirector.test/)"};
Check(nominatim.Enabled && nominatim.MinimumInterval.TotalSeconds>=15,"Designated worker and stricter public rate.");
await nominatim.SearchAsync(query!,default);
Check(transport.Calls==1&&transport.LastUri!.Contains("countrycodes=gb")&&transport.LastUri.Contains("Rubery")&&transport.UserAgent!.StartsWith("PlotDirector/"),"Central proxy sends only bounded place/context query and identifying User-Agent.");
settings.Value.Enabled=false;Check(!nominatim.Enabled,"Configuration disables requests without redeployment.");
settings.Value.Enabled=true;settings.Value.WorkerHost="another-host";Check(!nominatim.Enabled,"Other machines cannot send public requests.");
settings.Value.WorkerHost=Environment.MachineName;settings.Value.Provider="Disabled";Check(!nominatim.Enabled,"Provider configuration can switch off Nominatim.");
Console.WriteLine("PASS geography roots, hierarchy, provider-independent fake, cache identities, ambiguity, failures/backoff and rate reservation.");
}
sealed class DeniedAccess:IProjectAccessService
{
public Task<bool> CanAccessProjectAsync(int id)=>Task.FromResult(false);
public Task<bool> CanOwnProjectAsync(int id)=>Task.FromResult(false);
public Task<bool> CanAccessEntityAsync(string type,int id)=>Task.FromResult(false);
}
sealed class MonitorFake:IOptionsMonitor<GeocodingOptions>
{
public GeocodingOptions Value=new();public GeocodingOptions CurrentValue=>Value;
public GeocodingOptions Get(string? name)=>Value;
public IDisposable? OnChange(Action<GeocodingOptions,string?> listener)=>null;
}
sealed class HttpFake:HttpMessageHandler,IHttpClientFactory
{
public int Calls;public string? LastUri,UserAgent;
public HttpClient CreateClient(string name)=>new(this,false);
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,CancellationToken ct)
{Calls++;LastUri=request.RequestUri!.ToString();UserAgent=request.Headers.UserAgent.ToString();return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK){Content=new StringContent("[]")});}
}
sealed class ProviderFake(IReadOnlyList<GeographicCandidate> results):IGeocodingProvider
{
public string Name=>"Fake"; public bool IsEnabled=true;public bool Enabled=>IsEnabled;public TimeSpan MinimumInterval=>TimeSpan.FromSeconds(1);
public IReadOnlyList<GeographicCandidate> Results=results;public int Calls;public bool Fail;
public Task<IReadOnlyList<GeographicCandidate>> SearchAsync(GeographicQuery q,CancellationToken ct){Calls++;if(Fail)throw new IOException("Synthetic failure");return Task.FromResult(Results);}
}
sealed class QueueFake(IReadOnlyList<LocationItem> chain):IGeographicQueue
{
public GeographicJob Job=new(){LocationID=1,Generation=1,Lease=Guid.NewGuid()};public IReadOnlyList<LocationItem> Chain=chain;
public string? Status,State,Cached,Match;public int Delay;public bool AllowReservation=true;bool ready=true;
public void Requeue(){ready=true;Job.Lease=Guid.NewGuid();}
public Task<GeographicJob?> ClaimAsync(bool enabled){if(!ready)return Task.FromResult<GeographicJob?>(null);ready=false;return Task.FromResult<GeographicJob?>(Job);}
public Task<IReadOnlyList<LocationItem>> ChainAsync(int id)=>Task.FromResult(Chain);
public Task<string?> CacheAsync(string key)=>Task.FromResult(Cached);
public Task<bool> ReserveAsync(string provider,TimeSpan interval,string key,Guid lease)=>Task.FromResult(AllowReservation);
public Task ReleaseAsync(Guid lease,int cooldownSeconds=0)=>Task.CompletedTask;
public Task CompleteAsync(GeographicJob job,string status,string jobState,string? key=null,string? candidates=null,string? match=null,string? message=null,bool failure=false,int delay=0,bool relaxContext=false)
{Status=status;State=jobState;Match=match;if(relaxContext)Job.RelaxedContext=true;Delay=delay;if(candidates!=null)Cached=candidates;ready=jobState=="Queued";return Task.CompletedTask;}
}
}