Vertaalbestanden 1/6: tekstcatalogus (JSON per taal, benoemde plaatshouders, typed sleutels, lagen: map-override en later database, fail-soft) + TextAudit en tests
Embedded resources met WithCulture=false (anders maakt de SDK van 'X.Texts.en.json' een satellite-assembly). Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -29,6 +29,10 @@
|
||||
<Using Include="Xunit" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<EmbeddedResource Include="TextFixtures\*.json" WithCulture="false" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\SlpModularCms.Core\SlpModularCms.Core.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"sample": {
|
||||
"hello": "Hello {name}",
|
||||
"nested": { "deep": "Deep" },
|
||||
"plain": "Plain text"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"sample": {
|
||||
"hello": "Hallo {name}",
|
||||
"onlynl": "Alleen nl",
|
||||
"nested": { "deep": "Diep" },
|
||||
"plain": "Gewone tekst"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
using FluentAssertions;
|
||||
using SlpModularCms.Core.Texts;
|
||||
using Xunit;
|
||||
|
||||
namespace SlpModularCms.Core.Tests.Texts;
|
||||
|
||||
public class TextAuditTests
|
||||
{
|
||||
private static readonly System.Reflection.Assembly Fixtures = typeof(TextAuditTests).Assembly;
|
||||
|
||||
public static class AllSampleKeys
|
||||
{
|
||||
public static readonly TextKey Hello = new("sample.hello", "name");
|
||||
public static readonly TextKey Plain = new("sample.plain");
|
||||
public static readonly TextKey Deep = new("sample.nested.deep");
|
||||
public static readonly TextKey OnlyNl = new("sample.onlynl");
|
||||
}
|
||||
|
||||
public static class WrongKeys
|
||||
{
|
||||
public static readonly TextKey HelloWithoutPlaceholder = new("sample.hello");
|
||||
public static readonly TextKey Plain = new("sample.plain");
|
||||
public static readonly TextKey Misspelled = new("sample.plian");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void KeysOf_FindsEveryDeclaredKey_FieldsAndNestedTypes()
|
||||
=> TextAudit.KeysOf(typeof(AllSampleKeys)).Select(k => k.Path).Should().BeEquivalentTo(
|
||||
["sample.hello", "sample.plain", "sample.nested.deep", "sample.onlynl"]);
|
||||
|
||||
[Fact]
|
||||
public void AFileSetThatMatchesTheKeys_HasNoProblems_ForTheLanguagesThatHaveAFile()
|
||||
{
|
||||
var keys = TextAudit.KeysOf(typeof(AllSampleKeys)).Where(k => k.Path != "sample.onlynl").ToList();
|
||||
|
||||
TextAudit.Verify(Fixtures, keys, "nl", "en").Should().Contain(p => p.Contains("sample.onlynl") && p.StartsWith("[nl]"),
|
||||
"the nl file has a text that no key declares");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AKeyMissingInALanguage_IsReported()
|
||||
{
|
||||
var problems = TextAudit.Verify(Fixtures, TextAudit.KeysOf(typeof(AllSampleKeys)), "nl", "en");
|
||||
|
||||
problems.Should().Contain("[en] missing text for key 'sample.onlynl'");
|
||||
problems.Should().NotContain(p => p.StartsWith("[nl]"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DifferingPlaceholders_AndMisspelledOrOrphanKeys_AreReported()
|
||||
{
|
||||
var problems = TextAudit.Verify(Fixtures, TextAudit.KeysOf(typeof(WrongKeys)), "nl", "en");
|
||||
|
||||
problems.Should().Contain(p => p.Contains("'sample.hello'") && p.Contains("placeholders {name}"));
|
||||
problems.Should().Contain("[nl] missing text for key 'sample.plian'");
|
||||
problems.Should().Contain(p => p.Contains("'sample.onlynl'") && p.Contains("not declared"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ARequiredLanguageWithoutAFile_IsReported()
|
||||
=> TextAudit.Verify(Fixtures, TextAudit.KeysOf(typeof(AllSampleKeys)), "nl", "en", "de")
|
||||
.Should().Contain(p => p.Contains("language 'de'"));
|
||||
|
||||
[Fact]
|
||||
public void ADuplicateKeyDeclaration_IsReported()
|
||||
=> TextAudit.Verify(Fixtures, [new TextKey("sample.plain"), new TextKey("sample.plain")], "nl")
|
||||
.Should().Contain("key 'sample.plain' is declared more than once");
|
||||
}
|
||||
@@ -0,0 +1,215 @@
|
||||
using FluentAssertions;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using SlpModularCms.Core.Texts;
|
||||
using Xunit;
|
||||
|
||||
namespace SlpModularCms.Core.Tests.Texts;
|
||||
|
||||
public sealed class TextCatalogTests : IDisposable
|
||||
{
|
||||
private static readonly TextKey Hello = new("sample.hello", "name");
|
||||
private static readonly TextKey Plain = new("sample.plain");
|
||||
private static readonly TextKey OnlyNl = new("sample.onlynl");
|
||||
private static readonly TextKey Deep = new("sample.nested.deep");
|
||||
private static readonly TextKey Nope = new("sample.does.not.exist");
|
||||
|
||||
private readonly string _folder = Path.Combine(Path.GetTempPath(), "slp-texts-" + Guid.NewGuid().ToString("N"));
|
||||
private readonly List<string> _errors = [];
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (Directory.Exists(_folder)) Directory.Delete(_folder, recursive: true);
|
||||
}
|
||||
|
||||
private sealed class ListLogger(List<string> sink) : ILogger<TextCatalog>
|
||||
{
|
||||
public IDisposable? BeginScope<TState>(TState state) where TState : notnull => null;
|
||||
public bool IsEnabled(LogLevel logLevel) => true;
|
||||
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
|
||||
{
|
||||
if (logLevel >= LogLevel.Warning) sink.Add(formatter(state, exception));
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class FixedOverrides(Dictionary<(string Language, string Key), string> values) : ITextOverrides
|
||||
{
|
||||
public string? Find(string language, string key) => values.GetValueOrDefault((language, key));
|
||||
}
|
||||
|
||||
private TextCatalog Catalog(string defaultLanguage = "nl", string? directory = null, params ITextOverrides[] overrides) => new(
|
||||
Options.Create(new TextsOptions { DefaultLanguage = defaultLanguage, Directory = directory }),
|
||||
[new TextAssembly(typeof(TextCatalogTests).Assembly)],
|
||||
overrides,
|
||||
new ListLogger(_errors));
|
||||
|
||||
private void WriteFolder(string file, string json)
|
||||
{
|
||||
Directory.CreateDirectory(_folder);
|
||||
File.WriteAllText(Path.Combine(_folder, file), json);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheDefaultLanguageIsUsed_WhenNoneIsAsked_AndPlaceholdersAreFilled()
|
||||
{
|
||||
Catalog().Get(Hello, args: ("name", "Jan")).Should().Be("Hallo Jan");
|
||||
Catalog("en").Get(Hello, args: ("name", "Jan")).Should().Be("Hello Jan");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("en", "Hello Jan")]
|
||||
[InlineData("EN", "Hello Jan")]
|
||||
[InlineData("en-GB", "Hello Jan")]
|
||||
[InlineData("nl", "Hallo Jan")]
|
||||
public void AnAskedLanguage_WinsOverTheDefault(string asked, string expected)
|
||||
=> Catalog().Get(Hello, asked, ("name", "Jan")).Should().Be(expected);
|
||||
|
||||
[Fact]
|
||||
public void NestedJson_BecomesDottedKeys()
|
||||
=> Catalog().Get(Deep).Should().Be("Diep");
|
||||
|
||||
[Fact]
|
||||
public void AnUnknownLanguage_FallsBackToTheDefault_AndIsReportedOnce()
|
||||
{
|
||||
var catalog = Catalog();
|
||||
|
||||
catalog.Get(Plain, "fr").Should().Be("Gewone tekst");
|
||||
catalog.Get(Plain, "fr").Should().Be("Gewone tekst");
|
||||
|
||||
_errors.Should().ContainSingle().Which.Should().Contain("sample.plain").And.Contain("fr");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ATextMissingInTheAskedLanguage_FallsBack_AndIsReportedOnce()
|
||||
{
|
||||
var catalog = Catalog();
|
||||
|
||||
catalog.Get(OnlyNl, "en").Should().Be("Alleen nl");
|
||||
catalog.Get(OnlyNl, "en");
|
||||
|
||||
_errors.Should().ContainSingle();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AMissingKey_ReturnsTheKeyPath_NeverThrows_AndIsReportedOnce()
|
||||
{
|
||||
var catalog = Catalog();
|
||||
|
||||
catalog.Get(Nope).Should().Be("sample.does.not.exist");
|
||||
catalog.Get(Nope).Should().Be("sample.does.not.exist");
|
||||
|
||||
_errors.Should().ContainSingle().Which.Should().Contain("sample.does.not.exist");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AMissingValueForAPlaceholder_LeavesItInTheText_AndIsReported()
|
||||
{
|
||||
Catalog().Get(Hello).Should().Be("Hallo {name}");
|
||||
|
||||
_errors.Should().ContainSingle().Which.Should().Contain("name");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ValuesAreFormattedInvariantly_AndNullBecomesEmpty()
|
||||
{
|
||||
Catalog().Get(Hello, args: ("name", 1234.5m)).Should().Be("Hallo 1234.5");
|
||||
Catalog().Get(Hello, args: ("name", null)).Should().Be("Hallo ");
|
||||
}
|
||||
|
||||
// ---- layers ----
|
||||
|
||||
[Fact]
|
||||
public void TheOverrideFolder_WinsOverTheEmbeddedText_KeyByKey()
|
||||
{
|
||||
WriteFolder("nl.json", "{ \"sample\": { \"plain\": \"Aangepast\" } }");
|
||||
|
||||
var catalog = Catalog(directory: _folder);
|
||||
|
||||
catalog.Get(Plain).Should().Be("Aangepast");
|
||||
catalog.Get(OnlyNl).Should().Be("Alleen nl", "keys the folder does not mention keep their embedded text");
|
||||
catalog.Get(Plain, "en").Should().Be("Plain text");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheOverrideFolder_AcceptsAnyFileNamedForALanguage()
|
||||
{
|
||||
WriteFolder("site.en.json", "{ \"sample\": { \"plain\": \"Custom\" } }");
|
||||
|
||||
Catalog(directory: _folder).Get(Plain, "en").Should().Be("Custom");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ABrokenOverrideFile_IsIgnoredAndLogged_TheEmbeddedTextsStay()
|
||||
{
|
||||
WriteFolder("nl.json", "{ not json");
|
||||
|
||||
Catalog(directory: _folder).Get(Plain).Should().Be("Gewone tekst");
|
||||
|
||||
_errors.Should().ContainSingle().Which.Should().Contain("nl.json");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AMissingOverrideFolder_IsNoProblem_ButIsMentioned()
|
||||
{
|
||||
Catalog(directory: Path.Combine(_folder, "nope")).Get(Plain).Should().Be("Gewone tekst");
|
||||
|
||||
_errors.Should().ContainSingle().Which.Should().Contain("does not exist");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ADatabaseStyleOverride_WinsOverTheFolderAndTheEmbeddedText()
|
||||
{
|
||||
WriteFolder("nl.json", "{ \"sample\": { \"plain\": \"Map\" } }");
|
||||
var overrides = new FixedOverrides(new() { [("nl", "sample.plain")] = "Database" });
|
||||
|
||||
var catalog = Catalog(directory: _folder, overrides: overrides);
|
||||
|
||||
catalog.Get(Plain).Should().Be("Database");
|
||||
catalog.Get(Plain, "en").Should().Be("Plain text");
|
||||
}
|
||||
|
||||
// ---- files ----
|
||||
|
||||
[Fact]
|
||||
public void Flatten_AcceptsCommentsAndTrailingCommas_AndRejectsNonTextValues()
|
||||
{
|
||||
using var ok = new MemoryStream("{ // note\n \"a\": { \"b\": \"x\", }, }"u8.ToArray());
|
||||
TextCatalog.Flatten(ok).Should().Equal(new Dictionary<string, string> { ["a.b"] = "x" });
|
||||
|
||||
using var number = new MemoryStream("{ \"a\": 1 }"u8.ToArray());
|
||||
var act = () => TextCatalog.Flatten(number);
|
||||
act.Should().Throw<FormatException>().WithMessage("*'a'*");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("SlpModularCms.Core.Texts.nl.json", "nl")]
|
||||
[InlineData("SlpModularCms.Modules.Offerings.Texts.EN.json", "en")]
|
||||
[InlineData("SlpModularCms.Core.Tests.TextFixtures.Sample.Texts.nl.json", "nl")]
|
||||
[InlineData("SlpModularCms.Core.Hosting.WebsitePlaceholder.html", null)]
|
||||
[InlineData("SlpModularCms.Core.Texts.nl.txt", null)]
|
||||
public void OnlyTextResources_AreRecognised(string resource, string? language)
|
||||
=> TextCatalog.LanguageOfResource(resource).Should().Be(language);
|
||||
|
||||
[Fact]
|
||||
public void PlaceholdersIn_ListsTheNames()
|
||||
=> TextCatalog.PlaceholdersIn("Hallo {name}, {site} {name} {1} { x }").Should().BeEquivalentTo(["name", "site"]);
|
||||
|
||||
// ---- registration ----
|
||||
|
||||
[Fact]
|
||||
public void TheRealRegistration_ResolvesTheCatalog_WithCoreAssembly()
|
||||
{
|
||||
var services = new ServiceCollection();
|
||||
services.AddLogging();
|
||||
var configuration = new ConfigurationBuilder()
|
||||
.AddInMemoryCollection(new Dictionary<string, string?> { ["Texts:DefaultLanguage"] = "en" }).Build();
|
||||
services.AddCmsTexts(configuration).AddCmsTextsFrom(typeof(TextCatalogTests).Assembly);
|
||||
|
||||
var catalog = services.BuildServiceProvider().GetRequiredService<ITextCatalog>();
|
||||
|
||||
catalog.DefaultLanguage.Should().Be("en");
|
||||
catalog.Get(Plain).Should().Be("Plain text");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user