The last open item on the M7 list. Number and currency formatting was already locale-aware, but every string in the UI was an English literal, so a German instance read half in each language -- German data, English chrome. This translates all of it and adds the machinery to keep it translated. Strings live in Localization/Strings.resx (English, neutral) and Strings.de.resx. The neutral file generates a strongly-typed accessor at build time, aliased as S in _Imports.razor, so components reference compiled properties -- @S.Common_Save, not a string key. That choice is the point: across 4,500 lines of markup, a key lookup that silently falls back to its own name is a defect you find in production, while a renamed property is a build error. Generation runs in MSBuild rather than the IDE designer, so dotnet build alone reproduces it anywhere. Resource fallback is the hazard here. Ask for a key the German satellite lacks and ResourceManager quietly serves the English one -- correct at runtime, disastrous at release time, because a half-translated build looks perfectly healthy. StringResourceTests reads each satellite with tryParents: false, which is the only way to see what one actually contains, and fails on a missing or blank translation, a placeholder that changed arity, an orphan, or a key nothing references. Three things needed more than substitution: - Domain enums reached the screen as bare identifiers. They stay bare in the model -- they are persisted as text and appear in the REST API, so their names are part of the data contract -- and DisplayNames is now the single place that decides how each value is spoken. Every arm ends in a fallback returning the identifier, so a value added later cannot throw mid-render; EnumDisplayNameTests is what stops that safety net quietly becoming the shipping behaviour. - Infrastructure was writing display text: FlowService's "Other (X)", MeterPeriodView's "Generation"/"Consumption", the HA connection-test verdicts, the updater's snackbar, the CSV importer's row warnings. Each now returns an outcome value and the UI supplies the words, which is where the reader's language is known. Diagnostics that are not ours -- an HTTP status, systemd's stderr, an exception message -- are passed through untranslated, and every English summary is kept alongside the outcome so log lines never move with the UI language. The UpdateRunner change is additive only; no gate was touched. - Importer warnings carry their arguments rather than a finished sentence, so the numbers inside them pick up the reader's grouping. A register that reads 2.940,19 everywhere else must not read 2940.19 only inside a warning. Switching language is a redirect through /culture/set followed by a full reload, not an interactive state change: a Blazor Server circuit is fixed to the culture of the request that opened it. That makes the endpoint a redirector taking its target from the query string, so anything but a local path is refused rather than followed. Preference order is the cookie, then Accept-Language, then MeterVault__Locale -- an instance can be pinned to one language and a reader can still switch. Locale keeps its documented default of "en". Format now follows CurrentCulture instead of a hardcoded de-DE, so an instance with nothing configured and a browser asking for English will show English number formatting where it previously showed German; set MeterVault__Locale=de to pin the old behaviour. The importer's de-DE parsing is untouched and stays that way -- that dialect is a property of the spreadsheets, not of whoever is looking at the dashboard. Anything that comes from the database -- meter names, energy-type display names, category names -- is user data and is never translated. Claude-Session: https://claude.ai/code/session_0112ezeWqaZ85kTj5bYu9JHx
This commit is contained in:
@@ -0,0 +1,180 @@
|
||||
using System.Net;
|
||||
using Microsoft.AspNetCore.Localization;
|
||||
using Microsoft.AspNetCore.Mvc.Testing;
|
||||
|
||||
namespace MeterVault.Integration.Tests.Localization;
|
||||
|
||||
/// <summary>
|
||||
/// The language picker's endpoint and the culture the middleware hands each render (SDD §12, M7).
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// A Blazor Server circuit is fixed to the culture of the request that opened it, so switching
|
||||
/// language cannot be an interactive state change — it is a redirect that writes a cookie and forces
|
||||
/// a reload. That makes <c>/culture/set</c> a redirector taking its target from the query string,
|
||||
/// which is the exact shape of an open redirect, so the off-site cases below are load-bearing.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// Nothing here touches the database: no page on these paths queries, and startup migration is off,
|
||||
/// so the connection string only has to parse. They run without Docker.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public sealed class CultureEndpointTests : IDisposable
|
||||
{
|
||||
private const string UnusedConnection = "Host=localhost;Port=1;Database=metervault;Username=none;Password=none";
|
||||
|
||||
/// <summary>Renders the full layout (app bar + nav) without needing any data.</summary>
|
||||
private static readonly Uri LayoutOnlyPage = new("/admin/settings", UriKind.Relative);
|
||||
|
||||
private readonly List<MeterVaultAppFactory> _factories = [];
|
||||
|
||||
[Fact]
|
||||
public async Task Setting_a_supported_culture_stores_the_cookie_and_returns_the_user_to_the_page()
|
||||
{
|
||||
using var client = RedirectlessClient();
|
||||
|
||||
using var response = await client.GetAsync(
|
||||
new Uri("/culture/set?culture=de&redirectUri=%2Fmeters%2F7", UriKind.Relative));
|
||||
|
||||
Assert.Equal(HttpStatusCode.Found, response.StatusCode);
|
||||
Assert.Equal("/meters/7", response.Headers.Location?.OriginalString);
|
||||
Assert.Contains("c%3Dde%7Cuic%3Dde", CultureCookie(response), StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_regional_variant_is_stored_as_the_language_we_ship()
|
||||
{
|
||||
using var client = RedirectlessClient();
|
||||
|
||||
using var response = await client.GetAsync(
|
||||
new Uri("/culture/set?culture=de-AT&redirectUri=%2F", UriKind.Relative));
|
||||
|
||||
Assert.Equal(HttpStatusCode.Found, response.StatusCode);
|
||||
Assert.Contains("c%3Dde%7Cuic%3Dde", CultureCookie(response), StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("fr")]
|
||||
[InlineData("")]
|
||||
[InlineData("../../etc/passwd")]
|
||||
public async Task A_language_we_do_not_ship_is_refused_rather_than_stored(string culture)
|
||||
{
|
||||
using var client = RedirectlessClient();
|
||||
|
||||
using var response = await client.GetAsync(
|
||||
new Uri($"/culture/set?culture={Uri.EscapeDataString(culture)}&redirectUri=%2F", UriKind.Relative));
|
||||
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.Null(CultureCookie(response));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("https://evil.example/phish")]
|
||||
[InlineData("//evil.example/phish")]
|
||||
[InlineData("/\\evil.example/phish")]
|
||||
[InlineData("")]
|
||||
public async Task An_off_site_redirect_target_lands_on_the_dashboard_instead(string redirectUri)
|
||||
{
|
||||
using var client = RedirectlessClient();
|
||||
|
||||
using var response = await client.GetAsync(
|
||||
new Uri($"/culture/set?culture=de&redirectUri={Uri.EscapeDataString(redirectUri)}", UriKind.Relative));
|
||||
|
||||
Assert.Equal(HttpStatusCode.Found, response.StatusCode);
|
||||
Assert.Equal("/", response.Headers.Location?.OriginalString);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task The_culture_cookie_decides_the_language_of_the_rendered_page()
|
||||
{
|
||||
using var client = Factory().CreateClient();
|
||||
client.DefaultRequestHeaders.Add(
|
||||
"Cookie",
|
||||
CookieRequestCultureProvider.DefaultCookieName
|
||||
+ "="
|
||||
+ Uri.EscapeDataString(CookieRequestCultureProvider.MakeCookieValue(new RequestCulture("de"))));
|
||||
|
||||
var html = await RenderedTextAsync(client, LayoutOnlyPage);
|
||||
|
||||
Assert.Contains("lang=\"de\"", html, StringComparison.Ordinal);
|
||||
Assert.Contains("Übersicht", html, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("Overview", html, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Without_a_cookie_the_instance_default_locale_applies()
|
||||
{
|
||||
using var client = Factory(locale: "de").CreateClient();
|
||||
|
||||
var html = await RenderedTextAsync(client, LayoutOnlyPage);
|
||||
|
||||
Assert.Contains("lang=\"de\"", html, StringComparison.Ordinal);
|
||||
Assert.Contains("Übersicht", html, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task English_is_the_shipped_default_when_nothing_is_configured()
|
||||
{
|
||||
using var client = Factory().CreateClient();
|
||||
|
||||
var html = await RenderedTextAsync(client, LayoutOnlyPage);
|
||||
|
||||
Assert.Contains("lang=\"en\"", html, StringComparison.Ordinal);
|
||||
Assert.Contains("Overview", html, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task An_unshipped_default_locale_degrades_to_english_instead_of_failing_to_boot()
|
||||
{
|
||||
using var client = Factory(locale: "fr").CreateClient();
|
||||
|
||||
var html = await RenderedTextAsync(client, LayoutOnlyPage);
|
||||
|
||||
Assert.Contains("lang=\"en\"", html, StringComparison.Ordinal);
|
||||
Assert.Contains("Overview", html, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task The_first_visit_pins_the_negotiated_culture_into_the_cookie()
|
||||
{
|
||||
// Otherwise a reader whose browser asks for German is served German, but opens the picker
|
||||
// to find English ticked — the cookie is the only thing either side agrees to read.
|
||||
using var client = RedirectlessClient();
|
||||
client.DefaultRequestHeaders.Add("Accept-Language", "de-DE,de;q=0.9,en;q=0.8");
|
||||
|
||||
using var response = await client.GetAsync(LayoutOnlyPage);
|
||||
|
||||
Assert.Contains("c%3Dde%7Cuic%3Dde", CultureCookie(response), StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
foreach (var factory in _factories)
|
||||
{
|
||||
factory.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Blazor entity-encodes every non-ASCII character it renders, so "Übersicht" arrives as
|
||||
/// "&#xDC;bersicht" — decoding first is what lets these assertions read like the UI does.
|
||||
/// </summary>
|
||||
private static async Task<string> RenderedTextAsync(HttpClient client, Uri page) =>
|
||||
WebUtility.HtmlDecode(await client.GetStringAsync(page));
|
||||
|
||||
private static string? CultureCookie(HttpResponseMessage response) =>
|
||||
response.Headers.TryGetValues("Set-Cookie", out var cookies)
|
||||
? cookies.FirstOrDefault(c =>
|
||||
c.StartsWith(CookieRequestCultureProvider.DefaultCookieName, StringComparison.Ordinal))
|
||||
: null;
|
||||
|
||||
private MeterVaultAppFactory Factory(string? locale = null)
|
||||
{
|
||||
var factory = new MeterVaultAppFactory(UnusedConnection, configureApiKey: false) { Locale = locale };
|
||||
_factories.Add(factory);
|
||||
return factory;
|
||||
}
|
||||
|
||||
private HttpClient RedirectlessClient() =>
|
||||
Factory().CreateClient(new WebApplicationFactoryClientOptions { AllowAutoRedirect = false });
|
||||
}
|
||||
Reference in New Issue
Block a user