Files
ccn/Packages/Localization/Tests/Cases/Public/Methods/LocalizeTests.swift
T
2026-08-19 23:19:08 +02:00

135 lines
3.2 KiB
Swift

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)
}
}