`. A backend of your own implements the
same two contracts. Code written against Microsoft's `IStringLocalizer` reads the same strings through
[`formaui-net.Framework.Localization.StringLocalizerAdapter`](https://github.com/FormaUI/Forma/blob/main/src/Framework/Forma.Framework.Localization.StringLocalizerAdapter/README.md). `NullStringLocaleFactory.Instance` is a factory whose locales return every key
-as its own text, with holes filled and plural forms resolved in the source language, and
+as its own text, with holes filled and plural and gender forms resolved in the source language, and
`GetStringLocaleFactory` resolves the registered factory or that one, which is how Forma's components
read their strings where a host registers no localization.
@@ -91,10 +91,11 @@ such as one that began before the switch.
### Holes
A hole is `{Name}`, optionally with an alignment and a format specifier, `{Name,8}` or
-`{Ratio:P1}`. Values pair with the key's holes by position, in the order the holes first appear,
-one value per distinct hole; any other count throws `ArgumentException`. A localized string refers to
-the holes by name, so it may reorder them, and it may choose its own specifier. A literal brace is
-doubled, `{{`, in keys and localized strings alike.
+`{Ratio:P1}`. Values pair by position with the names the key uses, its holes and the arguments its
+expressions name, in the order each name first appears, one value per distinct name; any other count
+throws `ArgumentException`. A localized string refers to the holes by name, so it may reorder them,
+and it may choose its own specifier. A literal brace is doubled, `{{`, in keys and localized strings
+alike.
### Plural forms
@@ -118,9 +119,41 @@ count's category directly:
CommonPluralRuleSet.Default.Select(CultureInfo.GetCultureInfo("he"), 2) // PluralCategory.Two
```
+### Gender forms
+
+A gender expression selects one of its fields by whom the string is about:
+
+```text
+[$ [Rider] gender; female: Escaladora; other: Escalador; $]
+```
+
+`[Rider]` names the argument holding the gender, and is left out when the gender is the only value.
+The fields are `female`, `male` and `other`, and each language writes the ones its words change for:
+Spanish writes `female` beside `other` for a climber, and a language whose words don't change writes
+`other` alone. A field a localized string omits falls back to `other`.
+
+The argument is an enum value or a string, and selects the field its name spells, whatever its
+case: `Gender.Female` and `"female"` select `female`. A null, or a name without a field of its own,
+such as `NonBinary`, selects `other`.
+
+A key whose gender is its only value carries no expression where its words are the same for
+everyone, and its localization reads the value unnamed. A key with other values carries the
+expression with `other` alone, which names the argument, so the values pair with `[Rider]` and
+`{Name}` in the order they first appear:
+
+```csharp
+locale["Climber", rider.Gender]
+locale["[$ [Rider] gender; other: {Name} is the best climber; $]", rider.Gender, rider.Name]
+```
+
+```json
+"Climber": "[$ gender; female: Escaladora; other: Escalador; $]",
+"[$ [Rider] gender; other: {Name} is the best climber; $]": "[$ [Rider] gender; female: {Name} es la mejor escaladora; other: {Name} es el mejor escalador; $]"
+```
+
### Rendering holes as markup
-`Resolve` returns the localized format with its plural forms selected and its holes still open, so
+`Resolve` returns the localized format with its plural and gender forms selected and its holes still open, so
a caller can render a hole as something other than text, such as a link or a component:
```csharp
@@ -335,7 +368,7 @@ and referencing this package, whose build does the rest:
-
+
@@ -379,7 +412,7 @@ instead.
| `LocalizedText` | A localized string: `Value`, `Name`, `ResourceNotFound`, `SearchedLocation`. |
| `LocalizedPattern` | A localized format with its holes open: `Format`, `Arguments`, `EnumerateSegments()`. |
| `LocalizedSegment` | One run of a format: literal `Text`, or a hole with a `Name`, `Alignment` and `Format`. |
-| `LocalizedFormat` | Pairs values with a format's holes, `Bind`, and renders it, `Render`, without a locale. |
+| `LocalizedFormat` | Pairs values with the names a format uses, `Bind`, and renders it, `Render`, without a locale. |
| `CommonPluralRuleSet` | The CLDR plural rules behind `IPluralRuleSet`, in `Forma.Framework.Localization.Language`. |
The `Forma.Framework.Localization.Files` and `Forma.Framework.Localization.Parser` namespaces read
diff --git a/src/Locales/Forma.Blazor.Locales.Spanish/Forma.Blazor.Composer/es.json b/src/Locales/Forma.Blazor.Locales.Spanish/Forma.Blazor.Composer/es.json
index 154ed2666..b77f703cc 100644
--- a/src/Locales/Forma.Blazor.Locales.Spanish/Forma.Blazor.Composer/es.json
+++ b/src/Locales/Forma.Blazor.Locales.Spanish/Forma.Blazor.Composer/es.json
@@ -96,11 +96,11 @@
"Emoji": "Emoji",
"Table": "Tabla",
"Insert Table...": "Insertar Tabla...",
- "Add Row Above": "Añadir Fila Arriba",
- "Add Row Below": "Añadir Fila Abajo",
+ "Add Row Above": "Agregar Fila Arriba",
+ "Add Row Below": "Agregar Fila Abajo",
"Delete Row": "Eliminar Fila",
- "Add Column Left": "Añadir Columna a la Izquierda",
- "Add Column Right": "Añadir Columna a la Derecha",
+ "Add Column Left": "Agregar Columna a la Izquierda",
+ "Add Column Right": "Agregar Columna a la Derecha",
"Delete Column": "Eliminar Columna",
"Toggle Header Row": "Alternar Fila de Encabezado",
"Delete Table": "Eliminar Tabla",
@@ -112,7 +112,7 @@
"Media": "Medios",
"Edit Image": "Editar Imagen",
"Insert Image": "Insertar Imagen",
- "Enter the address of the image before inserting.": "Introduce la dirección de la imagen antes de insertarla.",
+ "Enter the address of the image before inserting.": "Ingresa la dirección de la imagen antes de insertarla.",
"This could not be inserted into the document.": "No se pudo insertar esto en el documento.",
"Attach Files": "Adjuntar Archivos",
"Attachments": "Adjuntos",
@@ -129,7 +129,7 @@
"Video URL": "URL del Video",
"Title": "Título",
"Autoplay": "Reproducción Automática",
- "Enter the address of the video before inserting.": "Introduce la dirección del video antes de insertarlo.",
+ "Enter the address of the video before inserting.": "Ingresa la dirección del video antes de insertarlo.",
"A video address has to start with http:// or https://.": "La dirección de un video debe empezar por http:// o https://.",
"View": "Vista",
"Preview": "Vista Previa",
@@ -165,11 +165,11 @@
"Settings": "Configuración",
"Article Layout": "Diseño de Artículo",
"Sidebar Callout": "Cuadro Destacado Lateral",
- "Enter a name for the anchor before inserting.": "Introduce un nombre para el ancla antes de insertarla.",
- "Enter the address of the link before inserting.": "Introduce la dirección del enlace antes de insertarlo.",
+ "Enter a name for the anchor before inserting.": "Ingresa un nombre para el ancla antes de insertarla.",
+ "Enter the address of the link before inserting.": "Ingresa la dirección del enlace antes de insertarlo.",
"An address has to be a web address, a mail or telephone link, a path within this site, or an inline picture.": "Una dirección debe ser una dirección web, un enlace de correo o teléfono, una ruta dentro de este sitio o una imagen incrustada.",
- "Enter the embed type before inserting.": "Introduce el tipo de inserción antes de insertarlo.",
- "Enter the identifier before inserting.": "Introduce el identificador antes de insertarlo.",
+ "Enter the embed type before inserting.": "Ingresa el tipo de inserción antes de insertarlo.",
+ "Enter the identifier before inserting.": "Ingresa el identificador antes de insertarlo.",
"{Format} on": "{Format} activado",
"{Format} off": "{Format} desactivado",
"Keyboard Shortcuts": "Atajos de Teclado",
diff --git a/src/Locales/Forma.Blazor.Locales.Spanish/Forma.Blazor.Explorer/es.json b/src/Locales/Forma.Blazor.Locales.Spanish/Forma.Blazor.Explorer/es.json
index 91c30e42c..41e8fe5db 100644
--- a/src/Locales/Forma.Blazor.Locales.Spanish/Forma.Blazor.Explorer/es.json
+++ b/src/Locales/Forma.Blazor.Locales.Spanish/Forma.Blazor.Explorer/es.json
@@ -25,7 +25,7 @@
"[$ plural; one: This explorer holds at most # item.; other: This explorer holds at most # items.; $]": "[$ plural; one: Este explorador admite como máximo # elemento.; other: Este explorador admite como máximo # elementos.; $]",
"Folder": "Carpeta",
"Image": "Imagen",
- "Video": "Vídeo",
+ "Video": "Video",
"Audio": "Audio",
"Archive": "Archivo Comprimido",
"Document": "Documento",
diff --git a/src/Locales/Forma.Blazor.Locales.Spanish/Forma.Blazor/Components/Debugging/es.json b/src/Locales/Forma.Blazor.Locales.Spanish/Forma.Blazor/Components/Debugging/es.json
index 5050eb970..9efd732e9 100644
--- a/src/Locales/Forma.Blazor.Locales.Spanish/Forma.Blazor/Components/Debugging/es.json
+++ b/src/Locales/Forma.Blazor.Locales.Spanish/Forma.Blazor/Components/Debugging/es.json
@@ -5,7 +5,7 @@
"Input router": "Enrutador de entrada",
"Inspector": "Inspector",
"Paused": "En pausa",
- "Press a key, click, or scroll to see how the router resolves it.": "Pulse una tecla, haga clic o desplácese para ver cómo lo resuelve el enrutador.",
+ "Press a key, click, or scroll to see how the router resolves it.": "Presiona una tecla, haz clic o desplázate para ver cómo lo resuelve el enrutador.",
"Owner": "Propietario",
"nothing": "nada",
"Action": "Acción",
diff --git a/src/Locales/Forma.Blazor.Locales.Spanish/Forma.Blazor/Components/Inputs/es.json b/src/Locales/Forma.Blazor.Locales.Spanish/Forma.Blazor/Components/Inputs/es.json
index 98f8c0523..f511d2df9 100644
--- a/src/Locales/Forma.Blazor.Locales.Spanish/Forma.Blazor/Components/Inputs/es.json
+++ b/src/Locales/Forma.Blazor.Locales.Spanish/Forma.Blazor/Components/Inputs/es.json
@@ -68,8 +68,8 @@
"Avoid repeating the same characters.": "Evita repetir los mismos caracteres.",
"[$ plural; one: Use at least # character.; other: Use at least # characters.; $]": "[$ plural; one: Usa al menos # carácter.; other: Usa al menos # caracteres.; $]",
"Mix uppercase and lowercase letters.": "Combina mayúsculas y minúsculas.",
- "Add a number.": "Añade un número.",
- "Add a symbol.": "Añade un símbolo."
+ "Add a number.": "Agrega un número.",
+ "Add a symbol.": "Agrega un símbolo."
},
"FormaSearchBox": {
"Search...": "Buscar...",
diff --git a/src/Locales/Forma.Blazor.Locales.Spanish/README.md b/src/Locales/Forma.Blazor.Locales.Spanish/README.md
index 5821b35df..75b9d616f 100644
--- a/src/Locales/Forma.Blazor.Locales.Spanish/README.md
+++ b/src/Locales/Forma.Blazor.Locales.Spanish/README.md
@@ -3,7 +3,7 @@
The Spanish localization of Forma, as a locale pack: a package of locale files alone, carrying the
Spanish strings of `Forma.Blazor`, `Forma.Blazor.Composer`, `Forma.Blazor.DataView` and
`Forma.Blazor.Explorer`. Installing it is all an application does to show Forma's components in
-Spanish.
+Spanish. The strings are written in Latin American Spanish and address the reader as *tú*.
## Install
diff --git a/tests/e2e/Forma.Blazor.Browser.Tests/Components/FeedbackTests.cs b/tests/e2e/Forma.Blazor.Browser.Tests/Components/FeedbackTests.cs
index c6d58cc76..7ccd87989 100644
--- a/tests/e2e/Forma.Blazor.Browser.Tests/Components/FeedbackTests.cs
+++ b/tests/e2e/Forma.Blazor.Browser.Tests/Components/FeedbackTests.cs
@@ -157,9 +157,10 @@ public async Task Should_open_below_its_anchor_at_the_anchor_s_start(string runt
var details = page.Locator("#details");
var trigger = page.Locator("#details-trigger");
- // Act
+ // Act — the layer is stamped as the popover registers, ahead of the call that shows and places it
await trigger.ClickAsync();
await WaitForLayerAsync(details);
+ await Assertions.Expect(details).ToBeVisibleAsync();
// Assert — four pixels below the anchor, its start edge held four pixels within the viewport
var anchor = (await page.Locator("span", new() { Has = trigger }).BoundingBoxAsync())!;
diff --git a/tests/e2e/Forma.Blazor.Browser.Tests/Components/TransferTests.cs b/tests/e2e/Forma.Blazor.Browser.Tests/Components/TransferTests.cs
index 35bf8bab6..fffa9914d 100644
--- a/tests/e2e/Forma.Blazor.Browser.Tests/Components/TransferTests.cs
+++ b/tests/e2e/Forma.Blazor.Browser.Tests/Components/TransferTests.cs
@@ -14,15 +14,20 @@ public sealed class TransferTests
// for a script's.
private static readonly LocatorAssertionsToHaveTextOptions Saved = new() { Timeout = 30_000 };
- // A paste of megabytes is taken, and its preview drawn, on WebAssembly's one thread, which a loaded runner took longer than
- // half a minute to do, so the check waits for each as long as for WebAssembly to start.
- private static readonly LocatorAssertionsToHaveTextOptions Taken = new() { Timeout = 60_000 };
- private static readonly LocatorClickOptions Drawn = new() { Timeout = 60_000 };
+ // A document of two megabytes in words and paragraphs, as a reader's document runs, since WebKit takes half a minute to lay out
+ // as much on one unbroken line, and Chromium lays out a paragraph that takes its direction from its own text, as the composer's
+ // do, in time growing with the square of the paragraph's length.
+ private const int ParagraphWords = 100;
+ private const int Paragraphs = 2_000;
// A value as the check page writes it: its length and the start of its SHA-256.
private static string Describe(string value)
=> $"{value.Length}:{Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(value)))[..16]}";
+ // The document of two megabytes, every word of it the one given.
+ private static string CreateDocument(string word)
+ => string.Concat(Enumerable.Repeat($"{string.Join(' ', Enumerable.Repeat(word, ParagraphWords))}
", Paragraphs));
+
public sealed class Forms(BrowserHost host)
{
[Theory]
@@ -72,15 +77,14 @@ public async Task Should_save_a_document_of_megabytes_pasted_into_the_rich_text_
await using var _ = context;
var canvas = page.Locator("#forma-body .forma-composer-rich-text-canvas");
await WaitForInputScopeAsync(page, "#forma-body .forma-composer-rich-text-canvas");
- // Two megabytes as words, as a reader's text runs, since WebKit takes half a minute to lay out as much on one unbroken line.
- const int Words = 200_000;
- await canvas.EvaluateAsync("(canvas, words) => { canvas.focus(); canvas.innerHTML = '' + Array(words).fill('xxxxxxxxx').join(' ') + '
'; canvas.dispatchEvent(new Event('input', { bubbles: true })); }", Words);
+ var document = CreateDocument("xxxxxxxxx");
+ await canvas.EvaluateAsync("(canvas, html) => { canvas.focus(); canvas.innerHTML = html; canvas.dispatchEvent(new Event('input', { bubbles: true })); }", document);
// Act
await page.Locator("#forma-save").ClickAsync();
// Assert
- await Assertions.Expect(page.Locator("#forma-body-saved")).ToHaveTextAsync(Describe($"{string.Join(' ', Enumerable.Repeat("xxxxxxxxx", Words))}
"), Saved);
+ await Assertions.Expect(page.Locator("#forma-body-saved")).ToHaveTextAsync(Describe(document), Saved);
}
[Theory]
@@ -232,12 +236,10 @@ public async Task Should_export_a_document_of_megabytes_from_its_preview(string
await using var _ = context;
var canvas = page.Locator("#forma-body .forma-composer-rich-text-canvas");
await WaitForInputScopeAsync(page, "#forma-body .forma-composer-rich-text-canvas");
- // Two megabytes as words, as a reader's text runs, since WebKit takes half a minute to lay out as much on one unbroken line.
- const int Words = 200_000;
- await canvas.EvaluateAsync("(canvas, words) => { canvas.focus(); canvas.innerHTML = '' + Array(words).fill('zzzzzzzzz').join(' ') + '
'; canvas.dispatchEvent(new Event('input', { bubbles: true })); }", Words);
- var document = $"{string.Join(' ', Enumerable.Repeat("zzzzzzzzz", Words))}
";
- await Assertions.Expect(page.Locator("#forma-body-length")).ToHaveTextAsync(document.Length.ToString(CultureInfo.InvariantCulture), Taken);
- await page.Locator("#forma-body").GetByRole(AriaRole.Tab, new() { Name = "Preview", Exact = true }).ClickAsync(Drawn);
+ var document = CreateDocument("zzzzzzzzz");
+ await canvas.EvaluateAsync("(canvas, html) => { canvas.focus(); canvas.innerHTML = html; canvas.dispatchEvent(new Event('input', { bubbles: true })); }", document);
+ await Assertions.Expect(page.Locator("#forma-body-length")).ToHaveTextAsync(document.Length.ToString(CultureInfo.InvariantCulture));
+ await page.Locator("#forma-body").GetByRole(AriaRole.Tab, new() { Name = "Preview", Exact = true }).ClickAsync();
var export = page.Locator("#forma-body .forma-composer-toolbar").GetByRole(AriaRole.Button, new() { Name = "Export HTML", Exact = true });
// Act
@@ -245,7 +247,7 @@ public async Task Should_export_a_document_of_megabytes_from_its_preview(string
// Assert — the page the browser composed, the document whole within it
var exported = await page.EvaluateAsync("address => fetch(address).then(response => response.text()).then(text => text.split('zzzzzzzzz').length - 1)", download.Url);
- Assert.Equal(Words, exported);
+ Assert.Equal(Paragraphs * ParagraphWords, exported);
}
// The name as an item of the list holds it.
diff --git a/tests/e2e/Forma.Blazor.Browser.Tests/CulturePages.cs b/tests/e2e/Forma.Blazor.Browser.Tests/CulturePages.cs
index 4bef5fb9b..c205f0b4a 100644
--- a/tests/e2e/Forma.Blazor.Browser.Tests/CulturePages.cs
+++ b/tests/e2e/Forma.Blazor.Browser.Tests/CulturePages.cs
@@ -22,7 +22,28 @@ public static async Task WaitForDocumentAsync(IPage page, string document, float
{
ArgumentNullException.ThrowIfNull(page);
- await page.WaitForFunctionAsync("expected => `${document.documentElement.lang}/${document.documentElement.dir}` === expected", document, new() { Timeout = timeout }).ConfigureAwait(false);
+ try
+ {
+ await page.WaitForFunctionAsync("expected => `${document.documentElement.lang}/${document.documentElement.dir}` === expected", document, new() { Timeout = timeout }).ConfigureAwait(false);
+ }
+ catch (TimeoutException exception)
+ {
+ throw new TimeoutException($"The document didn't read {document} within {timeout} ms: {await DescribeDocumentAsync(page).ConfigureAwait(false)}", exception);
+ }
+ }
+
+ // The document's language and direction, and the UI culture of the marker it started from, which a page whose coordinator never
+ // started lacks.
+ private static async Task DescribeDocumentAsync(IPage page)
+ {
+ try
+ {
+ return await page.EvaluateAsync("() => `it reads ${document.documentElement.lang}/${document.documentElement.dir}, and its culture marker names ${document.head.querySelector('meta[name=\"forma-culture\"]')?.getAttribute('data-ui-culture') ?? 'nothing, since the page carries none'}`").ConfigureAwait(false);
+ }
+ catch (PlaywrightException exception)
+ {
+ return $"it couldn't be read: {exception.Message}";
+ }
}
/// Waits until the Server's culture panel on the page is interactive.
diff --git a/tests/e2e/Forma.Blazor.Browser.Tests/WebViewExampleTests.cs b/tests/e2e/Forma.Blazor.Browser.Tests/WebViewExampleTests.cs
index 142620680..cf76aca41 100644
--- a/tests/e2e/Forma.Blazor.Browser.Tests/WebViewExampleTests.cs
+++ b/tests/e2e/Forma.Blazor.Browser.Tests/WebViewExampleTests.cs
@@ -31,8 +31,8 @@ public async Task Should_switch_every_web_view_and_native_window_title_with_stri
await first.Locator(".hebrew").ClickAsync();
// Assert
- await ExpectHebrewAsync(first);
- await ExpectHebrewAsync(second);
+ await ExpectHebrewAsync(application, first);
+ await ExpectHebrewAsync(application, second);
await WaitForTitlesAsync(windows, HebrewTitle);
Assert.False(Directory.Exists(Path.Combine(application.Folder, ".locales")), "The publish carries no folder of locale files, so the host's strings come from its assembly.");
}
@@ -57,7 +57,7 @@ public async Task Should_keep_switching_the_native_window_left_and_its_web_view_
await first.Locator(".hebrew").ClickAsync();
// Assert
- await ExpectHebrewAsync(first);
+ await ExpectHebrewAsync(application, first);
await WaitForTitlesAsync(opened, HebrewTitle);
Assert.False(application.HasExited, $"The application exited as its other native window closed. It wrote:{Environment.NewLine}{application.GetOutput(40)}");
}
@@ -71,7 +71,7 @@ public async Task Should_start_in_the_culture_its_last_run_saved(string example)
{
var page = await OpenInEnglishAsync(previous);
await page.Locator(".hebrew").ClickAsync();
- await ExpectHebrewAsync(page);
+ await ExpectHebrewAsync(previous, page);
NativeWindows.Close((await WaitForWindowsAsync(previous, 1)).Single());
await previous.WaitForExitAsync();
}
@@ -81,7 +81,7 @@ public async Task Should_start_in_the_culture_its_last_run_saved(string example)
var restarted = await application.GetOtherWebViewAsync([], Runtime);
// Assert
- await ExpectHebrewAsync(restarted);
+ await ExpectHebrewAsync(application, restarted);
await WaitForTitlesAsync(await WaitForWindowsAsync(application, 1), HebrewTitle);
await restarted.Locator(".english").ClickAsync();
await Assertions.Expect(restarted.Locator(".welcome")).ToHaveTextAsync("Welcome");
@@ -103,11 +103,42 @@ private static async Task OpenInEnglishAsync(WebViewApplication applicati
}
// The host's own string, from the files its application embeds, the library's from the Hebrew pack, and the document's language and direction.
- private static async Task ExpectHebrewAsync(IPage page)
+ private static async Task ExpectHebrewAsync(WebViewApplication application, IPage page)
{
await Assertions.Expect(page.Locator(".welcome")).ToHaveTextAsync(Welcome);
await Assertions.Expect(page.Locator("nav")).ToHaveAttributeAsync("aria-label", PaginationLabel);
- await WaitForDocumentAsync(page, "he/rtl");
+
+ try
+ {
+ await WaitForDocumentAsync(page, "he/rtl");
+ }
+ catch (TimeoutException exception)
+ {
+ throw new TimeoutException($"{exception.Message}; {await DescribeFollowingAsync(application, page)}", exception);
+ }
+ }
+
+ // What tells a web view its application's coordinator let go of from one whose document missed a single switch: the native
+ // windows' titles, which follow the application's culture, and whether the document follows a switch to English after it.
+ private static async Task DescribeFollowingAsync(WebViewApplication application, IPage page)
+ {
+ var titles = string.Join(", ", NativeWindows.Find(application.ProcessId).Select(NativeWindows.GetTitle));
+
+ try
+ {
+ await page.Locator(".english").ClickAsync(new() { Timeout = 5000 });
+ await WaitForDocumentAsync(page, "en-US/ltr", 5000);
+
+ return $"the native windows' titles read {titles}, and a switch to English after it moved the document to en-US/ltr";
+ }
+ catch (TimeoutException exception)
+ {
+ return $"the native windows' titles read {titles}, and a switch to English after it didn't move the document: {exception.Message}";
+ }
+ catch (PlaywrightException exception)
+ {
+ return $"the native windows' titles read {titles}, and a switch to English after it couldn't be made: {exception.Message}";
+ }
}
// The application's native windows, once it shows as many as it is asked for.
diff --git a/tests/unit/Framework/Forma.Framework.Localization.Json.Tests/Fixtures/Gendered/.locales/es.json b/tests/unit/Framework/Forma.Framework.Localization.Json.Tests/Fixtures/Gendered/.locales/es.json
new file mode 100644
index 000000000..8aaf622ac
--- /dev/null
+++ b/tests/unit/Framework/Forma.Framework.Localization.Json.Tests/Fixtures/Gendered/.locales/es.json
@@ -0,0 +1,5 @@
+{
+ "$localization": "SchemaVersion: 1.0.0; Culture: es;",
+ "Climber": "[$ gender; female: Escaladora; other: Escalador; $]",
+ "[$ [Rider] gender; other: {Name} is the best climber; $]": "[$ [Rider] gender; female: {Name} es la mejor escaladora; other: {Name} es el mejor escalador; $]"
+}
diff --git a/tests/unit/Framework/Forma.Framework.Localization.Json.Tests/Fixtures/ResourceSources.cs b/tests/unit/Framework/Forma.Framework.Localization.Json.Tests/Fixtures/ResourceSources.cs
index 06260514c..c85d64397 100644
--- a/tests/unit/Framework/Forma.Framework.Localization.Json.Tests/Fixtures/ResourceSources.cs
+++ b/tests/unit/Framework/Forma.Framework.Localization.Json.Tests/Fixtures/ResourceSources.cs
@@ -16,6 +16,9 @@ public sealed class PathScoped;
/// A type whose localized string carries a plural expression.
public sealed class Pluralized;
+/// A type whose localized strings carry a gender expression.
+public sealed class Gendered;
+
/// A type whose file carries no metadata entry.
public sealed class Unmarked;
diff --git a/tests/unit/Framework/Forma.Framework.Localization.Json.Tests/JsonStringLocaleTests.cs b/tests/unit/Framework/Forma.Framework.Localization.Json.Tests/JsonStringLocaleTests.cs
index ac467952b..51c68a60f 100644
--- a/tests/unit/Framework/Forma.Framework.Localization.Json.Tests/JsonStringLocaleTests.cs
+++ b/tests/unit/Framework/Forma.Framework.Localization.Json.Tests/JsonStringLocaleTests.cs
@@ -5,6 +5,12 @@ namespace Forma.Framework.Localization.Json.Tests;
public sealed class JsonStringLocaleTests
{
+ private enum RiderGender
+ {
+ Female,
+ Male,
+ }
+
private static IStringLocale CreateLocale()
=> new JsonStringLocaleFactory().Create(typeof(T));
@@ -571,6 +577,38 @@ public void Should_evaluate_the_plural_expression_in_a_text()
});
}
+ [Fact]
+ public void Should_evaluate_the_gender_expression_in_a_text()
+ {
+ // Arrange
+ using var culture = new CultureScope("es");
+ var strings = CreateLocale();
+
+ // Act
+ var female = strings["Climber", RiderGender.Female];
+ var male = strings["Climber", RiderGender.Male];
+
+ // Assert
+ Assert.Equal(["Escaladora", "Escalador"], [female.Value, male.Value]);
+ }
+
+ [Theory]
+ [InlineData("es", "Ana es la mejor escaladora")]
+ [InlineData("en", "Ana is the best climber")]
+ public void Should_pair_a_gender_the_key_names_with_its_holes(string language, string expected)
+ {
+ // Arrange
+ const string Key = "[$ [Rider] gender; other: {Name} is the best climber; $]";
+ using var culture = new CultureScope(language);
+ var strings = CreateLocale();
+
+ // Act
+ var localized = strings[Key, RiderGender.Female, "Ana"];
+
+ // Assert
+ Assert.Equal(expected, localized.Value);
+ }
+
[Theory]
[InlineData("[$ plural; one: # file; other: # files $]")]
[InlineData("[$ select; male: his; female: her; $]")]
diff --git a/tests/unit/Framework/Forma.Framework.Localization.Tests/Language/PluralExpressionEvaluatorLanguageTests.cs b/tests/unit/Framework/Forma.Framework.Localization.Tests/Language/LocaleExpressionEvaluatorLanguageTests.cs
similarity index 96%
rename from tests/unit/Framework/Forma.Framework.Localization.Tests/Language/PluralExpressionEvaluatorLanguageTests.cs
rename to tests/unit/Framework/Forma.Framework.Localization.Tests/Language/LocaleExpressionEvaluatorLanguageTests.cs
index da5942022..498f7995e 100644
--- a/tests/unit/Framework/Forma.Framework.Localization.Tests/Language/PluralExpressionEvaluatorLanguageTests.cs
+++ b/tests/unit/Framework/Forma.Framework.Localization.Tests/Language/LocaleExpressionEvaluatorLanguageTests.cs
@@ -1,13 +1,13 @@
namespace Forma.Framework.Localization.Tests.Language;
-public sealed class PluralExpressionEvaluatorLanguageTests
+public sealed class LocaleExpressionEvaluatorLanguageTests
{
private const string English = "[$ plural; one: # file; other: # files; $]";
private const string Hebrew = "[$ plural; one: קובץ אחד; two: שני קבצים; other: # קבצים; $]";
private const string Arabic = "[$ plural; zero: لا ملفات; one: ملف واحد; two: ملفان; few: # ملفات; many: # ملفًا; other: # ملف; $]";
private const string French = "[$ plural; one: # fichier; many: # millions de fichiers; other: # fichiers; $]";
- private static readonly PluralExpressionEvaluator Evaluator = new(CommonPluralRuleSet.Default);
+ private static readonly LocaleExpressionEvaluator Evaluator = new(CommonPluralRuleSet.Default);
[Theory]
[InlineData("en", English, 0, "0 files")]
diff --git a/tests/unit/Framework/Forma.Framework.Localization.Tests/Language/PluralExpressionEvaluatorTests.cs b/tests/unit/Framework/Forma.Framework.Localization.Tests/Language/LocaleExpressionEvaluatorTests.cs
similarity index 57%
rename from tests/unit/Framework/Forma.Framework.Localization.Tests/Language/PluralExpressionEvaluatorTests.cs
rename to tests/unit/Framework/Forma.Framework.Localization.Tests/Language/LocaleExpressionEvaluatorTests.cs
index dcaea4d7c..3e9981b57 100644
--- a/tests/unit/Framework/Forma.Framework.Localization.Tests/Language/PluralExpressionEvaluatorTests.cs
+++ b/tests/unit/Framework/Forma.Framework.Localization.Tests/Language/LocaleExpressionEvaluatorTests.cs
@@ -2,7 +2,7 @@ namespace Forma.Framework.Localization.Tests.Language;
using Forma.Framework.Localization.Language;
-public sealed class PluralExpressionEvaluatorTests
+public sealed class LocaleExpressionEvaluatorTests
{
private const string AllFields = "[$ [count] plural; zero: none; one: # one; two: # two; few: # few; many: # many; other: # other; $]";
@@ -19,7 +19,7 @@ private static LocalizedArgument Count(object? value)
public void Should_choose_the_field_the_rules_select(PluralCategory category, string expected)
{
// Arrange
- var evaluator = new PluralExpressionEvaluator(new StubPluralRuleSet(category));
+ var evaluator = new LocaleExpressionEvaluator(new StubPluralRuleSet(category));
// Act
var evaluated = evaluator.Evaluate(AllFields, CultureInfo.InvariantCulture, [Count(3)]);
@@ -32,7 +32,7 @@ public void Should_choose_the_field_the_rules_select(PluralCategory category, st
public void Should_leave_a_hash_alone_when_the_text_holds_no_expression()
{
// Arrange
- var evaluator = new PluralExpressionEvaluator(new StubPluralRuleSet(PluralCategory.One));
+ var evaluator = new LocaleExpressionEvaluator(new StubPluralRuleSet(PluralCategory.One));
// Act
var evaluated = evaluator.Evaluate("Issue #42 in C# is #1.", CultureInfo.InvariantCulture, []);
@@ -45,7 +45,7 @@ public void Should_leave_a_hash_alone_when_the_text_holds_no_expression()
public void Should_leave_a_hash_outside_an_expression_alone()
{
// Arrange
- var evaluator = new PluralExpressionEvaluator(new StubPluralRuleSet(PluralCategory.One));
+ var evaluator = new LocaleExpressionEvaluator(new StubPluralRuleSet(PluralCategory.One));
// Act
var evaluated = evaluator.Evaluate(
@@ -61,7 +61,7 @@ public void Should_leave_a_hash_outside_an_expression_alone()
public void Should_write_a_doubled_hash_in_a_field_as_a_literal_hash()
{
// Arrange
- var evaluator = new PluralExpressionEvaluator(new StubPluralRuleSet(PluralCategory.One));
+ var evaluator = new LocaleExpressionEvaluator(new StubPluralRuleSet(PluralCategory.One));
// Act
var evaluated = evaluator.Evaluate(
@@ -77,7 +77,7 @@ public void Should_write_a_doubled_hash_in_a_field_as_a_literal_hash()
public void Should_write_the_count_beside_a_literal_hash()
{
// Arrange
- var evaluator = new PluralExpressionEvaluator(new StubPluralRuleSet(PluralCategory.Other));
+ var evaluator = new LocaleExpressionEvaluator(new StubPluralRuleSet(PluralCategory.Other));
// Act
var evaluated = evaluator.Evaluate(
@@ -93,7 +93,7 @@ public void Should_write_the_count_beside_a_literal_hash()
public void Should_keep_a_doubled_hash_outside_an_expression_as_written()
{
// Arrange
- var evaluator = new PluralExpressionEvaluator(new StubPluralRuleSet(PluralCategory.One));
+ var evaluator = new LocaleExpressionEvaluator(new StubPluralRuleSet(PluralCategory.One));
// Act
var evaluated = evaluator.Evaluate(
@@ -109,7 +109,7 @@ public void Should_keep_a_doubled_hash_outside_an_expression_as_written()
public void Should_read_the_sole_argument_for_an_expression_naming_none()
{
// Arrange
- var evaluator = new PluralExpressionEvaluator(new StubPluralRuleSet(PluralCategory.One));
+ var evaluator = new LocaleExpressionEvaluator(new StubPluralRuleSet(PluralCategory.One));
// Act
var evaluated = evaluator.Evaluate(
@@ -125,7 +125,7 @@ public void Should_read_the_sole_argument_for_an_expression_naming_none()
public void Should_reject_an_expression_naming_no_argument_when_more_than_one_is_supplied()
{
// Arrange
- var evaluator = new PluralExpressionEvaluator(new StubPluralRuleSet(PluralCategory.One));
+ var evaluator = new LocaleExpressionEvaluator(new StubPluralRuleSet(PluralCategory.One));
// Act & Assert
Assert.Throws(() => evaluator.Evaluate(
@@ -138,7 +138,7 @@ public void Should_reject_an_expression_naming_no_argument_when_more_than_one_is
public void Should_reject_an_expression_naming_no_argument_when_the_argument_is_named()
{
// Arrange
- var evaluator = new PluralExpressionEvaluator(new StubPluralRuleSet(PluralCategory.One));
+ var evaluator = new LocaleExpressionEvaluator(new StubPluralRuleSet(PluralCategory.One));
// Act & Assert
Assert.Throws(() => evaluator.Evaluate(
@@ -151,7 +151,7 @@ public void Should_reject_an_expression_naming_no_argument_when_the_argument_is_
public void Should_fall_back_to_other_when_the_text_omits_the_chosen_field()
{
// Arrange
- var evaluator = new PluralExpressionEvaluator(new StubPluralRuleSet(PluralCategory.Many));
+ var evaluator = new LocaleExpressionEvaluator(new StubPluralRuleSet(PluralCategory.Many));
// Act
var evaluated = evaluator.Evaluate("[$ [count] plural; one: # file; other: # files; $]", CultureInfo.InvariantCulture, [Count(7)]);
@@ -164,7 +164,7 @@ public void Should_fall_back_to_other_when_the_text_omits_the_chosen_field()
public void Should_fall_back_to_other_when_the_rules_carry_no_entry_for_the_language()
{
// Arrange
- var evaluator = new PluralExpressionEvaluator(new StubPluralRuleSet(category: null));
+ var evaluator = new LocaleExpressionEvaluator(new StubPluralRuleSet(category: null));
// Act
var evaluated = evaluator.Evaluate(AllFields, CultureInfo.InvariantCulture, [Count(3)]);
@@ -177,7 +177,7 @@ public void Should_fall_back_to_other_when_the_rules_carry_no_entry_for_the_lang
public void Should_leave_other_holes_open_for_formatting()
{
// Arrange
- var evaluator = new PluralExpressionEvaluator(new StubPluralRuleSet(PluralCategory.Other));
+ var evaluator = new LocaleExpressionEvaluator(new StubPluralRuleSet(PluralCategory.Other));
// Act
var evaluated = evaluator.Evaluate("[$ [count] plural; other: # files; $] in {album}", CultureInfo.InvariantCulture, [Count(2), new LocalizedArgument("album", "Photos")]);
@@ -190,7 +190,7 @@ public void Should_leave_other_holes_open_for_formatting()
public void Should_resolve_every_plural_expression_in_one_sentence()
{
// Arrange
- var evaluator = new PluralExpressionEvaluator(new StubPluralRuleSet(PluralCategory.One));
+ var evaluator = new LocaleExpressionEvaluator(new StubPluralRuleSet(PluralCategory.One));
// Act
var evaluated = evaluator.Evaluate(
@@ -206,7 +206,7 @@ public void Should_resolve_every_plural_expression_in_one_sentence()
public void Should_return_a_format_without_plurals_unchanged()
{
// Arrange
- var evaluator = new PluralExpressionEvaluator(new StubPluralRuleSet(PluralCategory.Other));
+ var evaluator = new LocaleExpressionEvaluator(new StubPluralRuleSet(PluralCategory.Other));
// Act
var evaluated = evaluator.Evaluate("Stored {stored} of {total}.", CultureInfo.InvariantCulture, [new LocalizedArgument("stored", 1), new LocalizedArgument("total", 2)]);
@@ -219,7 +219,7 @@ public void Should_return_a_format_without_plurals_unchanged()
public void Should_treat_a_missing_argument_as_no_count()
{
// Arrange
- var evaluator = new PluralExpressionEvaluator(new StubPluralRuleSet(PluralCategory.Zero));
+ var evaluator = new LocaleExpressionEvaluator(new StubPluralRuleSet(PluralCategory.Zero));
// Act
var evaluated = evaluator.Evaluate(AllFields, CultureInfo.InvariantCulture, []);
@@ -235,7 +235,7 @@ public void Should_treat_a_missing_argument_as_no_count()
public void Should_leave_a_malformed_plural_expression_alone(string format)
{
// Arrange
- var evaluator = new PluralExpressionEvaluator(new StubPluralRuleSet(PluralCategory.One));
+ var evaluator = new LocaleExpressionEvaluator(new StubPluralRuleSet(PluralCategory.One));
// Act
var evaluated = evaluator.Evaluate(format, CultureInfo.InvariantCulture, [Count(1)]);
@@ -249,7 +249,7 @@ public void Should_leave_a_expression_named_for_something_else_alone()
{
// Arrange
const string Format = "[$ select {count}; male: his; female: her; $] bike";
- var evaluator = new PluralExpressionEvaluator(new StubPluralRuleSet(PluralCategory.One));
+ var evaluator = new LocaleExpressionEvaluator(new StubPluralRuleSet(PluralCategory.One));
// Act
var evaluated = evaluator.Evaluate(Format, CultureInfo.InvariantCulture, [Count(1)]);
@@ -262,7 +262,7 @@ public void Should_leave_a_expression_named_for_something_else_alone()
public void Should_treat_a_count_that_is_not_a_number_as_zero()
{
// Arrange
- var evaluator = new PluralExpressionEvaluator(new StubPluralRuleSet(PluralCategory.Other));
+ var evaluator = new LocaleExpressionEvaluator(new StubPluralRuleSet(PluralCategory.Other));
// Act
var evaluated = evaluator.Evaluate("[$ [count] plural; other: # files; $]", CultureInfo.InvariantCulture, [Count("abc")]);
@@ -276,7 +276,7 @@ public void Should_report_an_argument_that_is_not_a_count_once_per_format_withou
{
// Arrange
using var loggerFactory = new FakeLoggerFactory();
- var evaluator = new PluralExpressionEvaluator(new StubPluralRuleSet(PluralCategory.Other), loggerFactory.CreateLogger("plural"));
+ var evaluator = new LocaleExpressionEvaluator(new StubPluralRuleSet(PluralCategory.Other), loggerFactory.CreateLogger("plural"));
// Act
var first = evaluator.Evaluate(AllFields, CultureInfo.InvariantCulture, [Count("secret")]);
@@ -301,7 +301,7 @@ public void Should_report_an_argument_that_is_not_a_count_as_a_warning_under_dia
{
// Arrange
using var loggerFactory = new FakeLoggerFactory();
- var evaluator = new PluralExpressionEvaluator(new StubPluralRuleSet(PluralCategory.Other), loggerFactory.CreateLogger("plural"), new LocalizationDiagnostics());
+ var evaluator = new LocaleExpressionEvaluator(new StubPluralRuleSet(PluralCategory.Other), loggerFactory.CreateLogger("plural"), new LocalizationDiagnostics());
// Act
_ = evaluator.Evaluate(AllFields, CultureInfo.InvariantCulture, [Count("secret")]);
@@ -316,12 +316,12 @@ public void Should_report_an_argument_that_is_not_a_count_as_a_warning_under_dia
[Fact]
public void Should_reject_a_null_rule_set()
- => Assert.Throws(() => new PluralExpressionEvaluator(null!));
+ => Assert.Throws(() => new LocaleExpressionEvaluator(null!));
[Fact]
public void Should_reject_a_null_format()
{
// Arrange
- var evaluator = new PluralExpressionEvaluator(new StubPluralRuleSet(PluralCategory.Other));
+ var evaluator = new LocaleExpressionEvaluator(new StubPluralRuleSet(PluralCategory.Other));
// Assert
Assert.Throws(() => evaluator.Evaluate(null!, CultureInfo.InvariantCulture, []));
@@ -331,9 +331,171 @@ public void Should_reject_a_null_format()
public void Should_reject_a_null_culture()
{
// Arrange
- var evaluator = new PluralExpressionEvaluator(new StubPluralRuleSet(PluralCategory.Other));
+ var evaluator = new LocaleExpressionEvaluator(new StubPluralRuleSet(PluralCategory.Other));
// Assert
Assert.Throws(() => evaluator.Evaluate(AllFields, null!, []));
}
+
+ public sealed class Gender
+ {
+ private const string Format = "[$ [Rider] gender; female: Escaladora; male: Escalador; other: Ciclista; $]";
+
+ public enum RiderGender
+ {
+ Female,
+ Male,
+ Unstated,
+ }
+
+ private static LocaleExpressionEvaluator CreateEvaluator()
+ => new(new StubPluralRuleSet(PluralCategory.Other));
+
+ private static LocalizedArgument Rider(object? value)
+ => new("Rider", value);
+
+ [Theory]
+ [InlineData(RiderGender.Female, "Escaladora")]
+ [InlineData(RiderGender.Male, "Escalador")]
+ public void Should_choose_the_field_an_enum_member_names(RiderGender gender, string expected)
+ {
+ // Act
+ var evaluated = CreateEvaluator().Evaluate(Format, CultureInfo.InvariantCulture, [Rider(gender)]);
+
+ // Assert
+ Assert.Equal(expected, evaluated);
+ }
+
+ [Theory]
+ [InlineData("female", "Escaladora")]
+ [InlineData("FEMALE", "Escaladora")]
+ [InlineData("Male", "Escalador")]
+ public void Should_choose_the_field_a_string_names_whatever_its_case(string gender, string expected)
+ {
+ // Act
+ var evaluated = CreateEvaluator().Evaluate(Format, CultureInfo.InvariantCulture, [Rider(gender)]);
+
+ // Assert
+ Assert.Equal(expected, evaluated);
+ }
+
+ [Theory]
+ [InlineData(RiderGender.Unstated)]
+ [InlineData("nonbinary")]
+ [InlineData(null)]
+ public void Should_choose_other_for_a_gender_without_a_field_of_its_own(object? gender)
+ {
+ // Act
+ var evaluated = CreateEvaluator().Evaluate(Format, CultureInfo.InvariantCulture, [Rider(gender)]);
+
+ // Assert
+ Assert.Equal("Ciclista", evaluated);
+ }
+
+ [Fact]
+ public void Should_fall_back_to_other_when_the_text_omits_the_named_field()
+ {
+ // Act
+ var evaluated = CreateEvaluator().Evaluate(
+ "[$ [Rider] gender; female: Escaladora; other: Escalador; $]",
+ CultureInfo.InvariantCulture,
+ [Rider(RiderGender.Male)]);
+
+ // Assert
+ Assert.Equal("Escalador", evaluated);
+ }
+
+ [Fact]
+ public void Should_read_the_sole_argument_for_an_expression_naming_none()
+ {
+ // Act
+ var evaluated = CreateEvaluator().Evaluate(
+ "[$ gender; female: Escaladora; other: Escalador; $]",
+ CultureInfo.InvariantCulture,
+ [LocalizedArgument.Unnamed(RiderGender.Female)]);
+
+ // Assert
+ Assert.Equal("Escaladora", evaluated);
+ }
+
+ [Fact]
+ public void Should_write_a_hash_in_a_field_as_written()
+ {
+ // Act
+ var evaluated = CreateEvaluator().Evaluate(
+ "[$ [Rider] gender; female: La #1; other: El #1; $]",
+ CultureInfo.InvariantCulture,
+ [Rider(RiderGender.Female)]);
+
+ // Assert
+ Assert.Equal("La #1", evaluated);
+ }
+
+ [Fact]
+ public void Should_resolve_a_gender_and_a_plural_in_one_sentence()
+ {
+ // Act
+ var evaluated = CreateEvaluator().Evaluate(
+ "{Name} [$ [Rider] gender; female: ganó; other: ganó; $] [$ [Stages] plural; one: # etapa; other: # etapas; $], [$ [Rider] gender; female: invicta; other: invicto; $]",
+ CultureInfo.InvariantCulture,
+ [new LocalizedArgument("Name", "Ana"), Rider(RiderGender.Female), new LocalizedArgument("Stages", 3)]);
+
+ // Assert
+ Assert.Equal("{Name} ganó 3 etapas, invicta", evaluated);
+ }
+
+ [Fact]
+ public void Should_report_a_gender_that_is_neither_an_enum_nor_a_string_once_per_format_without_its_value()
+ {
+ // Arrange
+ using var loggerFactory = new FakeLoggerFactory();
+ var evaluator = new LocaleExpressionEvaluator(new StubPluralRuleSet(PluralCategory.Other), loggerFactory.CreateLogger("gender"));
+
+ // Act
+ var first = evaluator.Evaluate(Format, CultureInfo.InvariantCulture, [Rider(1)]);
+ var second = evaluator.Evaluate(Format, CultureInfo.InvariantCulture, [Rider(1)]);
+
+ // Assert
+ var entry = Assert.Single(loggerFactory.Entries);
+ Assert.Multiple(() =>
+ {
+ Assert.Equal("Ciclista", first);
+ Assert.Equal("Ciclista", second);
+ Assert.Equal(Microsoft.Extensions.Logging.LogLevel.Debug, entry.Level);
+ Assert.Equal(9, entry.EventId.Id);
+ Assert.Equal("Rider", entry.Fields["Argument"]);
+ Assert.Equal("Int32", entry.Fields["ArgumentType"]);
+ Assert.Contains("neither an enum nor a string", entry.Message, StringComparison.Ordinal);
+ });
+ }
+
+ [Fact]
+ public void Should_report_a_gender_that_is_neither_an_enum_nor_a_string_as_a_warning_under_diagnostics()
+ {
+ // Arrange
+ using var loggerFactory = new FakeLoggerFactory();
+ var evaluator = new LocaleExpressionEvaluator(new StubPluralRuleSet(PluralCategory.Other), loggerFactory.CreateLogger("gender"), new LocalizationDiagnostics());
+
+ // Act
+ _ = evaluator.Evaluate(Format, CultureInfo.InvariantCulture, [Rider(1)]);
+
+ // Assert
+ var entry = Assert.Single(loggerFactory.Entries);
+ Assert.Equal(Microsoft.Extensions.Logging.LogLevel.Warning, entry.Level);
+ }
+
+ [Fact]
+ public void Should_report_nothing_for_a_null_gender()
+ {
+ // Arrange
+ using var loggerFactory = new FakeLoggerFactory();
+ var evaluator = new LocaleExpressionEvaluator(new StubPluralRuleSet(PluralCategory.Other), loggerFactory.CreateLogger("gender"), new LocalizationDiagnostics());
+
+ // Act
+ _ = evaluator.Evaluate(Format, CultureInfo.InvariantCulture, [Rider(null)]);
+
+ // Assert
+ Assert.Empty(loggerFactory.Entries);
+ }
+ }
}
diff --git a/tests/unit/Framework/Forma.Framework.Localization.Tests/LocalizedFormatTests.cs b/tests/unit/Framework/Forma.Framework.Localization.Tests/LocalizedFormatTests.cs
index 992cfcc72..c52606ca1 100644
--- a/tests/unit/Framework/Forma.Framework.Localization.Tests/LocalizedFormatTests.cs
+++ b/tests/unit/Framework/Forma.Framework.Localization.Tests/LocalizedFormatTests.cs
@@ -32,6 +32,38 @@ public void Should_hold_a_lone_value_unnamed_when_the_format_names_no_hole()
Assert.Equal([LocalizedArgument.Unnamed(2)], arguments);
}
+ [Fact]
+ public void Should_pair_values_with_the_holes_and_the_expressions_arguments_in_the_order_they_first_appear()
+ {
+ // Act
+ var arguments = LocalizedFormat.Bind("{Team}: [$ [Rider] gender; other: {Name} won; $] in {Stage}", "Azul", "female", "Ana", 3);
+
+ // Assert
+ Assert.Equal(
+ [new LocalizedArgument("Team", "Azul"), new LocalizedArgument("Rider", "female"), new LocalizedArgument("Name", "Ana"), new LocalizedArgument("Stage", 3)],
+ arguments);
+ }
+
+ [Fact]
+ public void Should_count_an_argument_an_expression_names_once_with_its_hole()
+ {
+ // Act
+ var arguments = LocalizedFormat.Bind("{Count} [$ [Count] plural; one: file; other: files; $] in {Folder}", 2, "Photos");
+
+ // Assert
+ Assert.Equal([new LocalizedArgument("Count", 2), new LocalizedArgument("Folder", "Photos")], arguments);
+ }
+
+ [Fact]
+ public void Should_name_the_value_an_expression_names_when_the_format_has_no_hole()
+ {
+ // Act
+ var arguments = LocalizedFormat.Bind("[$ [Rider] gender; other: Climber; $]", "female");
+
+ // Assert
+ Assert.Equal([new LocalizedArgument("Rider", "female")], arguments);
+ }
+
[Fact]
public void Should_pair_nothing_for_a_format_with_neither_holes_nor_values()
=> Assert.Empty(LocalizedFormat.Bind("Save"));
@@ -40,6 +72,7 @@ public void Should_pair_nothing_for_a_format_with_neither_holes_nor_values()
[InlineData("Stored {stored} of {total}.", 1)]
[InlineData("Stored {stored} of {total}.", 3)]
[InlineData("Save", 2)]
+ [InlineData("[$ [Rider] gender; other: {Name} won; $]", 1)]
public void Should_reject_a_value_count_the_format_has_no_holes_for(string format, int count)
=> Assert.Throws(() => LocalizedFormat.Bind(format, new object?[count]));