Initial commit.

This commit is contained in:
2026-08-19 23:19:08 +02:00
commit 22e737d9c2
153 changed files with 11680 additions and 0 deletions
@@ -0,0 +1,77 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "2700"
version = "1.7">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES"
buildArchitectures = "Automatic">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "Localization"
BuildableName = "Localization"
ReferencedContainer = "container:">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES"
shouldAutocreateTestPlan = "YES">
<Testables>
<TestableReference
skipped = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "LocalizationTests"
BuildableName = "LocalizationTests"
ReferencedContainer = "container:">
</BuildableReference>
</TestableReference>
</Testables>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES"
queueDebuggingEnabled = "No">
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "Localization"
BuildableName = "Localization"
ReferencedContainer = "container:">
</BuildableReference>
</MacroExpansion>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
+37
View File
@@ -0,0 +1,37 @@
// swift-tools-version: 6.3
import PackageDescription
let package = Package(
name: "Localization",
defaultLocalization: "en",
platforms: [
.macOS(.v15),
],
products: [
.library(
name: "Localization",
targets: [
"Localization"
]
)
],
targets: [
.target(
name: "Localization",
path: "Sources",
),
.testTarget(
name: "LocalizationTests",
dependencies: [
.byName(name: "Localization")
],
path: "Tests",
resources: [
// Copied verbatim rather than processed: the String Catalog is read as raw JSON at runtime so it
// resolves identically on Darwin and Linux (which cannot compile it).
.copy("Catalogs/Localizable.xcstrings")
]
),
]
)
+43
View File
@@ -0,0 +1,43 @@
# Localization
The server-side localization toolkit the **Loud** services build on: locale-explicit String Catalog lookups, `Accept-Language` negotiation, and the catalog-derived language list — with no dependencies beyond Foundation.
## Overview
| Role | Types |
| --- | --- |
| Lookup | `Localize`, a bundle-bound localizer that resolves a catalog key for an explicit locale |
| Negotiation | `Negotiate`, which picks the best supported language from an `Accept-Language` header per RFC 9110 |
| Languages | `LanguageList`, the supported and default languages a bundle's String Catalog defines |
| Diagnostics | `CatalogState`, the outcome of reading the catalog (`loaded`, `missing`, or `undecodable`) |
## Design rules
- **The String Catalog is the single source of truth.** Supported languages, the default language, and every string come from the bundle's `Localizable.xcstrings`, so adding a language is a translation-only change.
- **The locale is always explicit.** A server has no single "current" locale, so every lookup names the locale to resolve in; nothing reads process-wide locale state.
- **Raw `.xcstrings` parsing, for Linux parity.** The catalog is decoded from its JSON rather than through Foundation's compiled-catalog APIs, which are unavailable or non-functional on Linux. Consumers must `.copy` the resource verbatim (never `.process` it) so it ships as raw JSON everywhere. Only simple `stringUnit` values are decoded — plural and device variations are not.
- **Resolution never fails.** A missing entry falls back to the source-language string, then to the key itself; a missing or undecodable catalog degrades the language list to the default. Check `catalogState` at startup and warn when it is not `.loaded`.
- **Method structs.** `Localize` and `Negotiate` hold their lifetime-fixed configuration (the bundle) in `init` and take only per-call inputs in `callAsFunction`.
- **One decoded catalog per bundle.** Catalogs are immutable at runtime, so every `Localize`, `Negotiate`, and `LanguageList` bound to the same bundle and table shares one cached `StringCatalog`.
## Layout
Sources are split by visibility, then by kind, one type per file:
```
Sources/
├── Public/
│ ├── Enumerations/ CatalogState
│ ├── Methods/ Localize, Negotiate
│ └── Types/ LanguageList
└── Internal/
├── Protocols/ CatalogResolving, the seam between the public API and the catalog backend
└── Types/ StringCatalog (the cached .xcstrings decoder), LanguageRange
Tests/
├── Cases/ the test suites, mirroring the Sources/ layout
├── Catalogs/ the String Catalog fixture, copied verbatim so it loads on Linux
└── Utils/ the StubCatalog resolver and the suite Tag constants
```
## Testing
Every suite carries a tag for the kind of API it exercises — `.method` or `.type`, declared in `Tests/Utils/Extensions/Tag+Constants.swift` — so test plans and summaries can slice a run by kind. A new suite adopts the tag matching its subject, or adds one when none fits.
## Requirements
- Swift 6.3 toolchain (`swift-tools-version:6.3`).
- macOS 15, matching the sibling packages (the services deploy to Linux containers; the packages carry no UI platforms).
- No package dependencies — Foundation and Synchronization only.
@@ -0,0 +1,38 @@
import Foundation
/// A backend that resolves localized strings for an explicit locale and reports the languages it serves.
///
/// This is the seam that decouples ``Localize`` and ``LanguageList`` from *how* localizations are stored and resolved. The shipping implementation,
/// ``StringCatalog``, reads a raw `.xcstrings` catalog so it behaves identically on Darwin and Linux. A future backend for example one built on
/// `String(localized:)` for a native Apple app that needs plural and device variations can conform without changing any caller.
///
/// Resolution never fails: an implementation returns the key itself when it has no localization for it, mirroring Foundation's `String(localized:)`.
/// This is the contract both a dictionary lookup and the native API can honour, since the native API cannot distinguish a missing key from a translation that
/// happens to equal the key.
protocol CatalogResolving: Sendable {
// MARK: Properties
/// The source (development) language, used as the final fallback when a locale has no localization and as the default language a ``LanguageList``
/// serves.
var sourceLanguage: String { get }
/// The outcome of reading the backing catalog, for consumers to surface at startup.
var state: CatalogState { get }
/// Every language the backend can resolve strings for, including the source language.
var languages: Set<String> { get }
// MARK: Methods
/// Resolves a catalog key in the given locale.
/// - Parameters:
/// - key: the catalog key to look up.
/// - locale: the locale to resolve the key in.
/// - Returns: the localized string, falling back to the source language, then to the key itself.
func string(
for key: String,
in locale: Locale
) -> String
}
@@ -0,0 +1,16 @@
/// A single language range parsed from an `Accept-Language` header entry.
///
/// A range pairs the language tag a client asked for with the `q` weight expressing how much the client prefers it, as RFC 9110 defines them.
/// ``Negotiate`` parses each comma-separated header entry into one of these, then orders the ranges by descending weight so the most preferred tag
/// is matched first.
struct LanguageRange {
// MARK: Properties
/// The language tag the client asked for, such as `de` or `de-AT`, or the `*` wildcard.
let tag: String
/// The tag's `q` weight, from 0 ("not acceptable") to 1 (most preferred, the default when an entry names no weight).
let quality: Double
}
@@ -0,0 +1,232 @@
import Foundation
import Synchronization
/// A decoded `.xcstrings` String Catalog, read directly from a bundle's resources.
///
/// The catalog is parsed from raw JSON rather than through Foundation's compiled-catalog APIs (`String(localized:)`,
/// `Bundle.localizations`, `Bundle.preferredLocalizations`). Those are either unavailable or non-functional on non-Darwin platforms
/// (Linux), where the toolchain ships no `xcstringstool` and so copies the raw `.xcstrings` into the resource bundle instead of compiling it.
/// Reading the catalog ourselves gives identical behaviour on every platform the service builds for.
///
/// Only simple `stringUnit` values are decoded; plural and device variations are not represented.
struct StringCatalog: Sendable {
// MARK: Properties
/// The source language of the catalog, used as the fallback when a key lacks a requested localization.
let sourceLanguage: String
/// The resolved entries, keyed by catalog key then by language code.
let entries: [String: [String: String]]
/// The outcome of reading the catalog from its bundle.
let state: CatalogState
// MARK: Computed
/// Every language the catalog provides a localization for, including the source language.
var languages: Set<String> {
var languages = Set(entries.values.flatMap(\.keys))
languages.insert(sourceLanguage)
return languages
}
// MARK: Initializers
/// Reads the catalog named `table` from `bundle`.
///
/// Falls back to an empty catalog (source language `"en"`, no entries) when the resource is missing or cannot be decoded, so lookups degrade
/// to returning the key and the language list to the default.
/// - Parameters:
/// - bundle: the bundle whose resources contain the String Catalog.
/// - table: the name of the String Catalog resource, without the `.xcstrings` extension.
init(
bundle: Bundle,
table: String = "Localizable"
) {
guard let url = bundle.url(
forResource: table,
withExtension: .Extension.stringCatalog
) else {
self.sourceLanguage = .Default.sourceLanguage
self.entries = [:]
self.state = .missing
return
}
do {
let decoder = JSONDecoder()
let data = try Data(contentsOf: url)
let decoded = try decoder.decode(
Decoded.self,
from: data
)
self.sourceLanguage = decoded.sourceLanguage
self.entries = decoded.strings
.mapValues { entry in
(entry.localizations ?? [:])
.compactMapValues { $0.stringUnit?.value }
}
self.state = .loaded
} catch {
self.sourceLanguage = .Default.sourceLanguage
self.entries = [:]
self.state = .undecodable
}
}
}
// MARK: - Cache
extension StringCatalog {
/// A cache key identifying a catalog by its bundle location and table name.
private struct Key: Hashable, Sendable {
let bundle: URL
let table: String
}
/// The decoded catalogs, keyed by bundle and table.
private static let cache = Mutex<[Key: StringCatalog]>([:])
/// Returns the catalog for the given bundle and table, decoding it on first access.
///
/// Catalogs are immutable at runtime, so every ``Localize``, ``Negotiate``, and ``LanguageList`` bound to the same bundle shares one
/// decoded catalog instead of re-reading its JSON.
/// - Parameters:
/// - bundle: the bundle whose resources contain the String Catalog.
/// - table: the name of the String Catalog resource, without the `.xcstrings` extension.
/// - Returns: the decoded catalog, from the cache when it has been read before.
static func cached(
bundle: Bundle,
table: String = "Localizable"
) -> StringCatalog {
let key = Key(
bundle: bundle.bundleURL,
table: table
)
return cache.withLock { cache in
if let catalog = cache[key] {
return catalog
}
let catalog = StringCatalog(
bundle: bundle,
table: table
)
cache[key] = catalog
return catalog
}
}
}
// MARK: - CatalogResolving
extension StringCatalog: CatalogResolving {
/// Resolves a key by the most specific language tag first: the locale's full tag (`pt-BR`), then its primary language code (`pt`), then the source
/// language, then the key itself. Tags are matched case-insensitively, so a regional catalog entry resolves for the locale ``Negotiate`` picked it for.
func string(
for key: String,
in locale: Locale
) -> String {
guard let byLanguage = entries[key] else {
return key
}
for tag in locale.catalogTags {
if let match = byLanguage.first(
where: { $0.key.lowercased() == tag }
) {
return match.value
}
}
return byLanguage[sourceLanguage] ?? key
}
}
// MARK: - Locale+Extensions
private extension Locale {
/// The language tags to resolve a catalog entry against, most specific first.
///
/// The locale's full identifier comes first, as a hyphenated, lowercased tag (`pt_BR` becomes `pt-br`), followed by its primary language code when
/// the two differ.
var catalogTags: [String] {
var tags: [String] = []
let identifier = identifier
.replacingOccurrences(
of: String.Separator.underscore,
with: String.Separator.dash
)
.lowercased()
if !identifier.isEmpty {
tags.append(identifier)
}
if let code = language.languageCode?.identifier.lowercased(),
code != identifier {
tags.append(code)
}
return tags
}
}
// MARK: - Decoding Types
private extension StringCatalog {
/// The subset of the `.xcstrings` format needed to resolve simple string entries.
struct Decoded: Decodable {
let sourceLanguage: String
let strings: [String: Entry]
struct Entry: Decodable {
let localizations: [String: Localization]?
}
struct Localization: Decodable {
let stringUnit: StringUnit?
}
struct StringUnit: Decodable {
let value: String
}
}
}
// MARK: - String+Constants
private extension String {
/// The source language assumed when a catalog is missing or cannot be decoded, matching the
/// package's default localization.
enum Default {
static let sourceLanguage = "en"
}
enum Extension {
static let stringCatalog = "xcstrings"
}
enum Separator {
static let dash = "-"
static let underscore = "_"
}
}
@@ -0,0 +1,12 @@
/// The outcome of reading a String Catalog from its bundle.
///
/// The package degrades gracefully when a catalog cannot be read lookups return their keys and the language list falls back to the default language so
/// nothing fails at the call site. This state is the signal a server checks once at startup to warn before visitors ever see raw localization keys.
public enum CatalogState: Equatable, Sendable {
/// The catalog was found and decoded; its entries are resolvable.
case loaded
/// No catalog resource exists in the bundle; every lookup returns its key.
case missing
/// The catalog resource exists but is not valid `.xcstrings` JSON; every lookup returns its key.
case undecodable
}
@@ -0,0 +1,69 @@
import Foundation
/// A reusable, bundle-bound localizer that resolves String Catalog entries for an explicit locale.
///
/// A server has no single "current" locale, so each lookup must name the locale to use. An instance is bound to the bundle whose catalog holds the strings,
/// then invoked like a function to resolve a key in a chosen locale.
public struct Localize: Sendable {
// MARK: Properties
/// The backend that resolves keys against the catalog.
private let resolver: any CatalogResolving
// MARK: Computed
/// The outcome of reading the bundle's String Catalog.
///
/// Resolution degrades to returning raw keys rather than failing, so check this once at startup and warn when it is not ``CatalogState/loaded``.
public var catalogState: CatalogState {
resolver.state
}
// MARK: Initializers
/// Creates a localizer backed by the String Catalog in the given bundle.
/// - Parameters:
/// - bundle: the bundle whose String Catalog contains the keys to resolve.
/// - table: the name of the String Catalog resource, without the `.xcstrings` extension.
public init(
bundle: Bundle,
table: String = "Localizable"
) {
self.init(resolver: StringCatalog.cached(
bundle: bundle,
table: table
))
}
/// Creates a localizer backed by the given resolver.
///
/// The seam for tests and alternative backends; the public API resolves against a bundled catalog.
/// - Parameter resolver: the backend that resolves keys to localized strings.
init(
resolver: any CatalogResolving
) {
self.resolver = resolver
}
// MARK: Methods
/// Resolves a catalog key in the given locale.
///
/// Invoked by calling the instance directly, for example `localize("index.title", locale: locale)`.
/// - Parameters:
/// - key: the String Catalog key to look up.
/// - locale: the locale to resolve the key in.
/// - Returns: the localized string for the locale, the source-language string when the locale has no entry, or the key itself when the catalog has no
/// entry for it.
public func callAsFunction(
_ key: String,
locale: Locale
) -> String {
resolver.string(
for: key,
in: locale
)
}
}
@@ -0,0 +1,198 @@
import Foundation
/// Negotiates the best supported language for a request from its `Accept-Language` header.
///
/// Bound to a bundle's catalog languages via ``LanguageList``, an instance is invoked like a function through
/// ``callAsFunction(acceptLanguage:)`` to resolve a header value to a supported language identifier, honouring the header's `q` weights as
/// RFC 9110 prescribes and falling back to the default language.
public struct Negotiate: Sendable {
// MARK: Properties
/// The supported languages and default language, derived from the bundle's String Catalog.
private let list: LanguageList
// MARK: Initializers
/// Creates a language negotiator backed by the given bundle's String Catalog.
/// - Parameter bundle: the bundle whose String Catalog defines the supported languages.
public init(
bundle: Bundle
) {
self.list = .init(bundle: bundle)
}
// MARK: Methods
/// Picks the best supported language for the given `Accept-Language` header value.
///
/// Invoked by calling the instance directly, for example `negotiate(acceptLanguage: header)`.
/// The header is parsed into its language ranges, which are ordered by descending `q` weight as RFC 9110 prescribes: an entry without a weight
/// counts as 1, entries weighted 0 are "not acceptable" and dropped, and equal weights keep the header order. Each tag is then matched against the
/// supported languages in turn first by an exact match, then by its primary language subtag, so `de-AT` resolves to a supported `de` while the
/// `*` wildcard accepts the default language. When the header is absent or matches nothing, the default language is returned.
/// - Parameter acceptLanguage: the raw `Accept-Language` header value, if any.
/// - Returns: the identifier of the supported language to serve.
public func callAsFunction(
acceptLanguage language: String?
) -> String {
guard let language else {
return list.default
}
let ranges = ranges(from: language)
guard !ranges.isEmpty else {
return list.default
}
let supported = list.all
for range in ranges {
if range.tag == .wildcard {
return list.default
}
if let match = match(range.tag, in: supported) {
return match
}
}
return list.default
}
}
// MARK: - Helpers
private extension Negotiate {
// MARK: Methods
/// Parses an `Accept-Language` header value into its ``LanguageRange`` list, ordered by preference.
///
/// Each comma-separated entry yields its language tag and `q` weight. The ranges are sorted by descending weight, entries weighted 0 are dropped
/// as "not acceptable", and equally weighted entries keep the header order.
/// - Parameter acceptLanguage: the raw `Accept-Language` header value.
/// - Returns: the language ranges, most preferred first.
func ranges(
from acceptLanguage: String
) -> [LanguageRange] {
acceptLanguage
.split(separator: .Separator.comma)
.compactMap(range(from:))
.filter { $0.quality > 0 }
.enumerated()
.sorted { lhs, rhs in
lhs.element.quality == rhs.element.quality
? lhs.offset < rhs.offset
: lhs.element.quality > rhs.element.quality
}
.map(\.element)
}
/// Parses a single `Accept-Language` header entry into its ``LanguageRange``.
///
/// The entry's language tag precedes the first `;`; a `q` parameter after it sets the weight.
/// A missing or malformed weight counts as 1, the highest preference, matching a tag sent without one.
/// - Parameter entry: a single comma-separated header entry.
/// - Returns: the entry's language range, or `nil` when it has no language tag.
func range(
from entry: Substring
) -> LanguageRange? {
let parts = entry.split(separator: .Separator.semicolon)
let tag = parts.first
.map(String.init)?
.trimmingCharacters(in: .whitespaces)
?? .empty
guard !tag.isEmpty else {
return nil
}
let quality = parts
.dropFirst()
.compactMap { parameter -> Double? in
let parameter = parameter
.trimmingCharacters(in: .whitespaces)
.lowercased()
guard parameter.hasPrefix(.Prefix.quality) else {
return nil
}
return Double(parameter.dropFirst(String.Prefix.quality.count))
}
.first
?? 1
return .init(
tag: tag,
quality: quality
)
}
/// Finds the supported language that best matches a single `Accept-Language` tag.
///
/// An exact, case-insensitive match wins; otherwise the tag's primary subtag is matched against the supported languages' primary subtags, so a
/// regional tag such as `de-AT` resolves to `de`.
/// - Parameters:
/// - tag: a single language tag from the header.
/// - supported: the supported language identifiers.
/// - Returns: the matching supported language, or `nil` when the tag matches none.
func match(
_ tag: String,
in supported: [String]
) -> String? {
let tag = tag.lowercased()
if let exact = supported.first(
where: { $0.lowercased() == tag }
) {
return exact
}
let primary = tag.primarySubtag
return supported.first {
$0.lowercased().primarySubtag == primary
}
}
}
// MARK: - Character+Extensions
private extension Character {
// MARK: Constants
enum Separator {
static let comma: Character = ","
static let dash: Character = "-"
static let semicolon: Character = ";"
}
}
// MARK: - String+Extensions
private extension String {
// MARK: Constants
static let empty: String = ""
static let wildcard: String = "*"
enum Prefix {
static let quality = "q="
}
/// The primary language subtag, i.e. everything before the first `-` (`de-AT` becomes `de`).
var primarySubtag: String {
split(separator: .Separator.dash)
.first
.map(String.init)
?? self
}
}
@@ -0,0 +1,61 @@
import Foundation
/// The list of languages an app can serve, derived from a bundle's String Catalog.
///
/// The languages are read from the injected `bundle`'s String Catalog, so the catalog that ships in that bundle is the single source of truth: adding
/// a language is a translation-only change once a locale exists in the catalog, it appears in ``all`` with no code change required.
public struct LanguageList: Sendable {
// MARK: Properties
/// The backend that reports the available languages.
private let resolver: any CatalogResolving
// MARK: Initializers
/// Creates a language list backed by the given bundle.
/// - Parameter bundle: the bundle whose String Catalog defines the available languages.
public init(
bundle: Bundle
) {
self.init(resolver: StringCatalog.cached(bundle: bundle))
}
/// Creates a language list backed by the given resolver.
///
/// The seam for tests and alternative backends; the public API derives languages from a bundled catalog.
/// - Parameter resolver: the backend that reports the available languages.
init(
resolver: any CatalogResolving
) {
self.resolver = resolver
}
// MARK: Computed
/// The outcome of reading the bundle's String Catalog.
///
/// The list degrades to the default language rather than failing, so check this once at startup and warn when it is not ``CatalogState/loaded``.
public var catalogState: CatalogState {
resolver.state
}
/// The language served when none of the supported languages match a request.
///
/// Always the catalog's source (development) language, so the default cannot drift from the bundle the list is bound to.
public var `default`: String {
resolver.sourceLanguage
}
/// Every language the bundle's String Catalog provides a localization for.
///
/// The `Base` internationalization is excluded, as it is a development placeholder rather than a real language.
/// The result is sorted for a stable order.
public var all: [String] {
resolver
.languages
.filter { $0 != "Base" }
.sorted()
}
}
@@ -0,0 +1,134 @@
import Foundation
import Testing
@testable import Localization
@Suite(
"Localize method",
.tags(.method)
)
struct LocalizeTests {
// MARK: Constants
private let localize = Localize(bundle: .module)
// MARK: Functional tests
@Test
func `resolves a key in the default locale`() {
let text = localize(
"test.greeting",
locale: Locale(identifier: "en")
)
#expect(text == "Hello")
}
@Test
func `resolves a key in another locale`() {
let text = localize(
"test.greeting",
locale: Locale(identifier: "de"),
)
#expect(text == "Hallo")
}
@Test
func `resolves a key in a regional locale`() {
let text = localize(
"test.greeting",
locale: Locale(identifier: "pt-BR"),
)
#expect(text == "Olá")
}
@Test
func `falls back to the primary language for an unmatched regional locale`() {
let text = localize(
"test.greeting",
locale: Locale(identifier: "de-AT"),
)
#expect(text == "Hallo")
}
@Test
func `falls back to the source language for an unsupported locale`() {
let text = localize(
"test.greeting",
locale: Locale(identifier: "fr"),
)
#expect(text == "Hello")
}
@Test
func `falls back to the key for an unknown entry`() {
let text = localize(
"unknown.key",
locale: Locale(identifier: "en"),
)
#expect(text == "unknown.key")
}
@Test
func `falls back to the key for a missing catalog`() {
let localize = Localize(bundle: .main)
let text = localize(
"test.greeting",
locale: Locale(identifier: "en")
)
#expect(text == "test.greeting")
}
// MARK: Properties tests
@Test
func `reports a loaded catalog`() {
#expect(localize.catalogState == .loaded)
}
@Test
func `reports a missing catalog`() {
let localize = Localize(bundle: .main)
#expect(localize.catalogState == .missing)
}
// A malformed catalog cannot ship as a test resource Xcode generates string symbols for every
// bundled `.xcstrings` and fails the build on invalid JSON so one is staged in a temporary
// directory bundle instead.
@Test
func `reports an undecodable catalog`() throws {
let directory = URL(fileURLWithPath: NSTemporaryDirectory())
.appendingPathComponent(
"UndecodableCatalog-\(UUID().uuidString)",
isDirectory: true
)
try FileManager.default.createDirectory(
at: directory,
withIntermediateDirectories: true
)
defer {
try? FileManager.default.removeItem(at: directory)
}
try Data("not a catalog".utf8).write(
to: directory.appendingPathComponent("Localizable.xcstrings")
)
let bundle = try #require(Bundle(url: directory))
let localize = Localize(bundle: bundle)
#expect(localize.catalogState == .undecodable)
}
}
@@ -0,0 +1,130 @@
import Foundation
import Testing
@testable import Localization
@Suite(
"Negotiate method",
.tags(.method)
)
struct NegotiateTests {
// MARK: Constants
private let negotiate = Negotiate(bundle: .module)
// MARK: Functional tests
@Test
func `matches an exact language tag`() {
let language = negotiate(acceptLanguage: "de")
#expect(language == "de")
}
@Test
func `matches a regional language tag`() {
let language = negotiate(acceptLanguage: "de-AT")
#expect(language == "de")
}
@Test
func `matches a regional catalog language exactly`() {
let language = negotiate(acceptLanguage: "pt-BR")
#expect(language == "pt-BR")
}
@Test
func `matches a regional catalog language by its primary subtag`() {
let language = negotiate(acceptLanguage: "pt")
#expect(language == "pt-BR")
}
@Test
func `respects the header order of preference`() {
let language = negotiate(acceptLanguage: "de, en")
#expect(language == "de")
}
@Test
func `orders the language tags by descending quality weight`() {
let language = negotiate(acceptLanguage: "en;q=0.5, de;q=0.9")
#expect(language == "de")
}
@Test
func `treats a tag without a weight as the highest preference`() {
let language = negotiate(acceptLanguage: "en;q=0.9, de")
#expect(language == "de")
}
@Test
func `treats a tag with a malformed weight as the highest preference`() {
let language = negotiate(acceptLanguage: "en;q=0.9, de;q=broken")
#expect(language == "de")
}
@Test
func `drops language tags weighted as not acceptable`() {
let language = negotiate(acceptLanguage: "de;q=0, en;q=0.8")
#expect(language == "en")
}
@Test
func `falls back to the default when every tag is weighted as not acceptable`() {
let language = negotiate(acceptLanguage: "de;q=0, fr;q=0")
#expect(language == "en")
}
@Test
func `serves the default language for a wildcard`() {
let language = negotiate(acceptLanguage: "fr;q=0.9, *;q=0.5")
#expect(language == "en")
}
@Test
func `trims whitespace around the language tags`() {
let language = negotiate(acceptLanguage: " de , en ")
#expect(language == "de")
}
@Test
func `falls back to the default for an unsupported language`() {
let language = negotiate(acceptLanguage: "fr")
#expect(language == "en")
}
@Test
func `falls back to the default for a missing header`() {
let language = negotiate(acceptLanguage: nil)
#expect(language == "en")
}
@Test
func `falls back to the default for an empty header`() {
let language = negotiate(acceptLanguage: "")
#expect(language == "en")
}
@Test
func `falls back to the default for a header without language tags`() {
let language = negotiate(acceptLanguage: " , ;q=0.5,")
#expect(language == "en")
}
}
@@ -0,0 +1,105 @@
import Foundation
import Testing
@testable import Localization
@Suite(
"LanguageList type",
.tags(.type)
)
struct LanguageListTests {
// MARK: Properties tests
@Suite("default")
struct Default {
@Test
func `defaults to english`() {
let list = LanguageList(
bundle: .module
)
#expect(list.default == "en")
}
@Test
func `follows the catalog's source language`() {
let list = LanguageList(
resolver: StubCatalog(
sourceLanguage: "de",
languages: ["de", "en"]
)
)
#expect(list.default == "de")
}
}
@Suite("catalogState")
struct CatalogState {
@Test
func `reports a loaded catalog`() {
let list = LanguageList(
bundle: .module
)
#expect(list.catalogState == .loaded)
}
@Test
func `reports a missing catalog`() {
let list = LanguageList(
bundle: .main
)
#expect(list.catalogState == .missing)
}
}
@Suite("all")
struct All {
@Test
func `lists the catalog languages`() {
let list = LanguageList(
bundle: .module
)
#expect(list.all.contains("en"))
#expect(list.all.contains("de"))
}
@Test
func `excludes the base localization`() {
let list = LanguageList(
resolver: StubCatalog(
sourceLanguage: "en",
languages: ["Base", "de", "en"]
)
)
#expect(list.all == ["de", "en"])
}
@Test
func `sorts the languages`() {
let list = LanguageList(
resolver: StubCatalog(
sourceLanguage: "en",
languages: ["fr", "en", "de"]
)
)
#expect(list.all == ["de", "en", "fr"])
}
@Test
func `degrades to the default language for a missing catalog`() {
let list = LanguageList(
bundle: .main
)
#expect(list.all == ["en"])
}
}
}
@@ -0,0 +1,29 @@
{
"sourceLanguage" : "en",
"strings" : {
"test.greeting" : {
"comment" : "Fixture string used by the Localization test suite.",
"localizations" : {
"de" : {
"stringUnit" : {
"state" : "translated",
"value" : "Hallo"
}
},
"en" : {
"stringUnit" : {
"state" : "translated",
"value" : "Hello"
}
},
"pt-BR" : {
"stringUnit" : {
"state" : "translated",
"value" : "Olá"
}
}
}
}
},
"version" : "1.0"
}
@@ -0,0 +1,8 @@
import Testing
extension Tag {
/// Tests exercising a method of the Localization package.
@Tag static var method: Tag
/// Tests exercising a type of the Localization package.
@Tag static var type: Tag
}
@@ -0,0 +1,23 @@
import Foundation
@testable import Localization
/// A ``CatalogResolving`` backend with fixed languages, for exercising types apart from a bundled catalog.
struct StubCatalog: CatalogResolving {
// MARK: Properties
let sourceLanguage: String
let languages: Set<String>
var state: CatalogState = .loaded
// MARK: Methods
func string(
for key: String,
in locale: Locale
) -> String {
key
}
}