Repository Public
1import Foundation2import Testing3@testable import MCCCore45@Suite("Formatting and localization")6struct FormattingTests {7 static let packageRoot = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()8 static let fr = AppLanguage.fr.locale, en = AppLanguage.en.locale9 /// Narrow and regular no-break spaces → plain spaces, to compare formatted output.10 static func plain(_ s: String) -> String { s.replacingOccurrences(of: "\u{202f}", with: " ").replacingOccurrences(of: "\u{a0}", with: " ") }1112 @Test("bytes, percentages, numbers in both languages")13 func numbers() {14 #expect(Format.bytes(68_719_476_736, binary: true, locale: Self.en) == "64 GB")15 #expect(Self.plain(Format.bytes(68_719_476_736, binary: true, locale: Self.fr)) == "64 Go")16 #expect(Format.bytes(494_384_795_648, locale: Self.en) == "494.38 GB")17 #expect(Format.bytes(0, locale: Self.en) == "0 kB" || Format.bytes(0, locale: Self.en).hasPrefix("0"))18 #expect(Format.percent(42, locale: Self.en) == "42%")19 #expect(Self.plain(Format.percent(42, locale: Self.fr)) == "42 %")20 #expect(Format.percent(ratio: 0.5, fractionDigits: 1, locale: Self.en) == "50.0%")21 #expect(Format.number(3.14159, fractionDigits: 2, locale: Self.fr) == "3,14")22 #expect(Format.number(3, fractionDigits: 2, locale: Self.en) == "3")23 }2425 @Test("durations use at most two units and localized abbreviations")26 func durations() {27 #expect(Format.duration(seconds: 0.85, language: .fr) == "850 ms")28 #expect(Format.duration(seconds: 42, language: .en) == "42 s")29 #expect(Format.duration(seconds: 312, language: .fr) == "5 min 12 s")30 #expect(Format.duration(seconds: 3600, language: .fr) == "1 h")31 #expect(Format.duration(seconds: 3 * 86_400 + 4 * 3600 + 59, language: .fr) == "3 j 4 h")32 #expect(Format.duration(seconds: 3 * 86_400 + 4 * 3600 + 59, language: .en) == "3 d 4 h")33 #expect(Format.duration(seconds: -1, language: .en) == "—")34 }3536 @Test("relative time, wall-clock time and unambiguous UTC")37 func time() {38 let now = Date(timeIntervalSince1970: 1_795_000_000)39 let enRel = Format.relative(now.addingTimeInterval(-300), now: now, locale: Self.en)40 #expect(enRel.hasPrefix("5 min") && enRel.hasSuffix("ago"))41 #expect(Format.relative(now.addingTimeInterval(-300), now: now, locale: Self.fr).contains("5"))42 #expect(Format.relative(now.addingTimeInterval(-300), now: now, locale: Self.fr).hasPrefix("il y a"))43 #expect(Format.utc(Date(timeIntervalSince1970: 0)) == "1970-01-01 00:00:00 UTC")44 let utc = TimeZone(identifier: "UTC")!45 #expect(Format.time(Date(timeIntervalSince1970: 3600 * 14 + 300), locale: Self.fr, timeZone: utc).contains("14"))46 }4748 @Test("metric values carry their unit; nothing is rendered for an unmeasured value")49 func metrics() throws {50 #expect(Format.metric(87.5, unit: "%").contains("88") || Format.metric(87.5, unit: "%").contains("87"))51 #expect(Format.metric(1_500_000, unit: "bytes/s").hasSuffix("/s"))52 #expect(Format.metric(12.5, unit: "ms").hasSuffix("ms"))53 let measured = try JSONDecoder().decode(API.MetricValue.self, from: Data(#"{"value":12.5,"unit":"ms","availability":"available"}"#.utf8))54 #expect(MetricValueView.text(for: measured).measured)55 for state in ["unsupported", "permission_denied", "unavailable", "offline"] {56 let v = try JSONDecoder().decode(API.MetricValue.self, from: Data(#"{"availability":"\#(state)","reason":"powermetrics needs root"}"#.utf8))57 let r = MetricValueView.text(for: v)58 #expect(!r.measured)59 #expect(r.text == enumLabel("availability", state))60 #expect(!r.text.contains("0"))61 }62 #expect(MetricValueView.text(for: nil).measured == false)63 // A stale value is shown as a value (flagged), never dropped silently.64 let stale = try JSONDecoder().decode(API.MetricValue.self, from: Data(#"{"value":3,"unit":"count","availability":"stale"}"#.utf8))65 #expect(MetricValueView.text(for: stale).measured)66 }6768 @Test("series: [ts_ms, avg, min, max] rows, gaps stay gaps, summary")69 func series() {70 let t0 = 1_800_000_000_000.071 var rows: [[Double]] = (0..<10).map { [t0 + Double($0) * 60_000, Double($0), Double($0) - 1, Double($0) + 1] }72 rows.remove(at: 5); rows.remove(at: 5) // buckets 5 and 6 are missing73 rows.append([t0, 1]) // malformed row: dropped, not patched74 let s = ChartSeries(id: "cpu", name: "CPU", metricPoints: rows)75 #expect(s.points.count == 8)76 #expect(s.typicalStep == 60)77 let segs = s.segments()78 #expect(segs.count == 2)79 #expect(segs[0].count == 5 && segs[1].count == 3)80 #expect(s.gapCount == 1)81 let sum = s.summary!82 #expect(sum.min == -1 && sum.max == 10 && sum.last == 9)83 #expect(ChartSeries(id: "e", name: "e", metricPoints: []).summary == nil)84 #expect(ChartSeries(id: "one", name: "one", metricPoints: [[t0, 1, 1, 1]]).segments().count == 1)85 }8687 private struct Catalog: Decodable {88 struct Entry: Decodable {89 struct Loc: Decodable { struct Unit: Decodable { var state: String; var value: String }; var stringUnit: Unit? }90 var localizations: [String: Loc]?91 }92 var sourceLanguage: String93 var strings: [String: Entry]94 }9596 @Test("String Catalog: every key is translated in French and English, with matching format specifiers")97 func catalogComplete() throws {98 let url = Self.packageRoot.appendingPathComponent("Sources/MCCCore/Resources/Localizable.xcstrings")99 let cat = try JSONDecoder().decode(Catalog.self, from: Data(contentsOf: url))100 #expect(cat.sourceLanguage == "fr")101 #expect(cat.strings.count > 100)102 let spec = /%(?:\d+\$)?(?:lld|ld|d|@|f|s)/103 for (key, entry) in cat.strings {104 var specs: [String: [String]] = [:]105 for lang in ["fr", "en"] {106 let unit = entry.localizations?[lang]?.stringUnit107 #expect(unit?.state == "translated", "\(key) is not translated in \(lang)")108 #expect(unit?.value.isEmpty == false, "\(key) is empty in \(lang)")109 specs[lang] = (unit?.value.matches(of: spec).map { String($0.output) } ?? []).sorted()110 }111 #expect(specs["fr"] == specs["en"], "\(key): format specifiers differ")112 }113 // Keys built at runtime (enum labels) and every literal tr("…") in the sources exist.114 for key in EnumLabelKeys.all { #expect(cat.strings[key] != nil, "missing \(key)") }115 let sources = Self.packageRoot.appendingPathComponent("Sources/MCCCore")116 var used = Set<String>()117 for case let file as URL in FileManager.default.enumerator(at: sources, includingPropertiesForKeys: nil)! where file.pathExtension == "swift" {118 let text = try String(contentsOf: file, encoding: .utf8)119 for m in text.matches(of: /\btr\(\s*"([^"\\]+)"/) { used.insert(String(m.output.1)) }120 }121 #expect(used.count > 20)122 for key in used { #expect(cat.strings[key] != nil, "tr(\"\(key)\") has no catalog entry") }123 }124125 @Test("the compiled catalog is loaded for both languages and switches at runtime")126 func runtimeLookup() {127 let l = Localization(language: .fr, defaults: UserDefaults(suiteName: "mcc-l10n-\(UUID().uuidString)")!)128 #expect(l.string("enum.freshness.offline") == "Hors ligne")129 #expect(l.string("enum.freshness.offline", language: .en) == "Offline")130 l.language = .en131 #expect(l.string("unavailable.not_implemented.title") == "Not available yet")132 #expect(l.locale.identifier.hasPrefix("en"))133 #expect(l.string("no.such.key") == "no.such.key")134 #expect(l.has("action.retry", language: .fr) && l.has("action.retry", language: .en))135 #expect(!l.has("no.such.key", language: .fr))136 for lang in AppLanguage.allCases { #expect(l.table(for: lang).count > 100) }137 #expect(String(format: l.string("chart.gaps", language: .fr), locale: AppLanguage.fr.locale, arguments: [3]).hasPrefix("3 "))138 }139}140