OpenDataVisualizer/Schaad.OpenData.Tests/SwisstopoClientTestShould.cs
Claudio Schaad e729ea3403 Add Thurgau traffic visualizer with animated map
ASP.NET Core 10 API and React client that visualize the canton of
Thurgau's hourly traffic counts by vehicle class (data.tg.ch, CC0).

- Background refresh from data.tg.ch every 6 h into a per-day JSON
  cache, so history grows beyond the source's two-week window
- Road geometry per station direction from swisstopo swissTLM3D,
  oriented by geocoding the direction's target town; roundabout arms
  follow the road outward only
- Leaflet map with canvas animation: dots drive along the road in
  both directions, density by hourly count, colour by vehicle class,
  right-hand traffic; play/pause, time slider and day selection
- Station panel with per-class counts and Chart.js charts (hourly,
  weekday/weekend profile, daily totals, class mix)
- swisstopo base map switcher (grey, colour, aerial)
- Dockerfile and docker-compose with a data volume
- xUnit tests for mapping, cache, geometry, geocoding and analysis

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 20:33:58 +01:00

124 lines
5 KiB
C#

using System.Net;
using System.Text;
using Schaad.OpenData.Traffic.Geometry;
using Schaad.OpenData.Traffic.Models;
namespace Schaad.OpenData.Tests;
public class SwisstopoClientTestShould
{
private sealed class StubHandler(params (HttpStatusCode Status, string Body)[] responses) : HttpMessageHandler
{
private int index;
public List<Uri> Requests { get; } = [];
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
Requests.Add(request.RequestUri!);
var (status, body) = responses[Math.Min(index++, responses.Length - 1)];
return Task.FromResult(new HttpResponseMessage(status) { Content = new StringContent(body, Encoding.UTF8, "application/json") });
}
}
private static SwisstopoClient Client(StubHandler handler) =>
new(new HttpClient(handler) { BaseAddress = new Uri("https://api3.geo.admin.ch/rest/services/api/") });
private const string LandquartResults = """
{"results":[
{"attrs":{"label":"<b>Landquart (GR)</b>","lat":46.956,"lon":9.578}},
{"attrs":{"label":"Landquart [district]","lat":46.961,"lon":9.560}},
{"attrs":{"label":"Populated Place <b>Landquart (TG)</b> - Arbon","lat":47.501,"lon":9.423}},
{"attrs":{"label":"Landstrasse","lat":47.502,"lon":9.425}}
]}
""";
[Fact]
public async Task PickNearestMatchingPlaceWhenNameIsAmbiguous()
{
var client = Client(new StubHandler((HttpStatusCode.OK, LandquartResults)));
var place = await client.FindPlaceAsync("Landquart", new GeoPoint(47.502, 9.425), CancellationToken.None);
place.ShouldBe(new GeoPoint(47.501, 9.423));
}
[Fact]
public async Task MatchTransliteratedNameWhenLabelHasUmlaut()
{
var body = """{"results":[{"attrs":{"label":"<b>Tägerwilen (TG)</b>","lat":47.645,"lon":9.129}}]}""";
var client = Client(new StubHandler((HttpStatusCode.OK, body)));
var place = await client.FindPlaceAsync("Taegerwilen", new GeoPoint(47.62, 9.1), CancellationToken.None);
place.ShouldBe(new GeoPoint(47.645, 9.129));
}
[Fact]
public async Task ReturnNullWhenNoLabelMatches()
{
var body = """{"results":[{"attrs":{"label":"Somewhere Else","lat":47,"lon":9}}]}""";
var client = Client(new StubHandler((HttpStatusCode.OK, body)));
(await client.FindPlaceAsync("Nowhere", new GeoPoint(47, 9), CancellationToken.None)).ShouldBeNull();
}
[Fact]
public async Task RetryWhenServiceIsTemporarilyUnavailable()
{
var handler = new StubHandler((HttpStatusCode.ServiceUnavailable, ""), (HttpStatusCode.OK, LandquartResults));
var client = Client(handler);
var place = await client.FindPlaceAsync("Landquart", new GeoPoint(47.5, 9.42), CancellationToken.None);
place.ShouldNotBeNull();
handler.Requests.Count.ShouldBe(2);
}
[Fact]
public async Task FlagRoadsWithTrafficImportanceAsMainRoadsWhenLoadingSegments()
{
var body = """
{"results":[
{"geometry":{"type":"MultiLineString","coordinates":[[[9.1,47.5],[9.2,47.5]]]},"properties":{"verkehrsbedeutung":200}},
{"geometry":{"type":"LineString","coordinates":[[9.1,47.6],[9.2,47.6]]},"properties":{"verkehrsbedeutung":999998}}
]}
""";
var client = Client(new StubHandler((HttpStatusCode.OK, body)));
var segments = await client.GetRoadSegmentsAsync(new GeoPoint(47.5, 9.15), 300, CancellationToken.None);
segments.Select(s => s.IsMainRoad).ShouldBe([true, false]);
segments[0].Points[0].ShouldBe(new GeoPoint(47.5, 9.1));
}
[Fact]
public async Task FlagPathsAsNotDrivableWhenLoadingSegments()
{
var body = """
{"results":[
{"geometry":{"type":"LineString","coordinates":[[9.1,47.5],[9.2,47.5]]},"properties":{"objektart":9}},
{"geometry":{"type":"LineString","coordinates":[[9.1,47.6],[9.2,47.6]]},"properties":{"objektart":15}}
]}
""";
var client = Client(new StubHandler((HttpStatusCode.OK, body)));
var segments = await client.GetRoadSegmentsAsync(new GeoPoint(47.5, 9.15), 300, CancellationToken.None);
segments.Select(s => s.IsDrivable).ShouldBe([true, false]);
}
[Fact]
public async Task RequestNextPageWhenPageIsFull()
{
var feature = """{"geometry":{"type":"LineString","coordinates":[[9.1,47.5],[9.2,47.5]]},"properties":{}}""";
var fullPage = $$"""{"results":[{{string.Join(',', Enumerable.Repeat(feature, 200))}}]}""";
var handler = new StubHandler((HttpStatusCode.OK, fullPage), (HttpStatusCode.OK, $$"""{"results":[{{feature}}]}"""));
var client = Client(handler);
var segments = await client.GetRoadSegmentsAsync(new GeoPoint(47.5, 9.15), 300, CancellationToken.None);
segments.Count.ShouldBe(201);
handler.Requests.Select(r => r.Query.Contains("offset=200")).ShouldBe([false, true]);
}
}