Play your own Switch games on iPhone/iPad — one-click macOS app, no terminal. | 把 Switch 游戏装进 iPhone:图形界面一键构建,不用命令行。Bring your own game.
Swift apple-siliconcustom-formathomebrewiosipaipadipadosiphonemetalnative-portnintendo-switchnxnativeromfsswitch-games
Check every language file against the same rules in one test per front end (#388)
v0lumehi74fda7eeb883
diff --git a/frontend-qt/tests/test_localization_de.py b/frontend-qt/tests/test_localization_de.pyindex 4644b1e4..b93cc88d 100644--- a/frontend-qt/tests/test_localization_de.py+++ b/frontend-qt/tests/test_localization_de.py@@ -1,7 +1,8 @@-"""The Qt table carries a complete German column, read from the same file the Swift launcher reads (frontend/l10n/de.json)."""+"""The Qt table carries a German column that is real German, read from the same file the Swift launcher reads (frontend/l10n/de.json).++Completeness and placeholders for every language are in test_localization_rules.py."""from __future__ import annotations-import reimport sysimport unittestfrom pathlib import Path@@ -12,19 +13,12 @@ sys.path.insert(0, str(ROOT / 'frontend-qt'))from nspb_qt.i18n import Lang # noqa: E402from nspb_qt.l10n import TABLE, t # noqa: E402-PLACEHOLDER = re.compile(r'%(?:\d+\$)?(?:\.\d+)?(?:ll|l)?[@dsf%]')-class German(unittest.TestCase):- def test_every_key_has_german_text_that_is_not_the_english_fallback(self):+ def test_no_german_prose_is_left_in_english(self):# dep.python.hint is a list of package names, the same in every languageprose = [k for k, row in TABLE.items() if row['de'] == row['en'] and len(row['en']) > 30 and k != 'dep.python.hint']self.assertEqual(prose, [], 'English text left in the German column')- self.assertTrue(all(row['de'] for row in TABLE.values()))-- def test_placeholders_match_english_in_count_and_order(self):- for key, row in TABLE.items():- self.assertEqual(PLACEHOLDER.findall(row['de']), PLACEHOLDER.findall(row['en']), key)def test_german_has_no_semicolons_and_no_added_product_name(self):for key, row in TABLE.items():diff --git a/frontend-qt/tests/test_localization_fr.py b/frontend-qt/tests/test_localization_fr.pyindex 2e01519b..67a119a9 100644--- a/frontend-qt/tests/test_localization_fr.py+++ b/frontend-qt/tests/test_localization_fr.py@@ -1,7 +1,6 @@-"""The Qt table carries the French column, read from frontend/l10n/fr.json, complete."""+"""The Qt table carries the French column, read from frontend/l10n/fr.json (the rules every file keeps are in test_localization_rules.py)."""from __future__ import annotations-import reimport sysimport unittestfrom pathlib import Path@@ -12,17 +11,8 @@ sys.path.insert(0, str(ROOT / 'frontend-qt'))from nspb_qt.i18n import Lang # noqa: E402from nspb_qt.l10n import TABLE, t # noqa: E402-# %@, %d, %ld, %%, positional %1$@ and float %.1f, as in FrenchLocalizationTests.swift-PLACEHOLDER = re.compile(r'%(?:\d+\$)?(?:\.\d+)?l{0,2}[@dfs%]')-class FrenchTable(unittest.TestCase):- def test_every_row_has_french_and_its_placeholders(self):- for key, row in TABLE.items():- en, fr = row['en'], row['fr']- self.assertTrue(fr, key)- self.assertEqual(PLACEHOLDER.findall(fr), PLACEHOLDER.findall(en), key)-def test_t_reads_the_french_column(self):self.assertEqual(t('onboarding.start', Lang('fr')), 'Commencer')self.assertEqual(t('settings.language.fr', Lang('fr')), 'Français')diff --git a/frontend-qt/tests/test_localization_rules.py b/frontend-qt/tests/test_localization_rules.pynew file mode 100644index 00000000..5427c780--- /dev/null+++ b/frontend-qt/tests/test_localization_rules.py@@ -0,0 +1,107 @@+"""The rules every language file in frontend/l10n has to keep (LNPANDY/NX2Apple#388).++The languages are the files of the folder, so a new `<code>.json` is checked here without a change to this test.+The Mac launcher has the same rules in frontend/Tests/NXCoreTests/LocalizationRulesTests.swift.+"""+from __future__ import annotations++import json+import re+import unittest+from pathlib import Path++L10N = Path(__file__).resolve().parents[2] / 'frontend' / 'l10n'+REQUIRED = ('en', 'zh') # every key is in these two, and English is what a missing text falls back to++# printf placeholders (%@, %d, %ld, %.1f, %s, positional %1$@, and %%) and {0} or {name}+PRINTF = re.compile(r'%(?:(\d+)\$)?(\.\d+)?(ll|l)?([@dsf%])')+BRACES = re.compile(r'\{(\w*)\}')+++def placeholders(text: str) -> tuple[dict[int, str], int, list[str]]:+ """What String(format:) and str.format read: the type of each argument by its position, the count of %%, and the braces.++ A positional `%2$@` is argument 2, so a translation may reorder arguments. Without a position they count 1, 2, 3.+ """+ args: dict[int, str] = {}+ percents = 0+ nxt = 1+ for position, precision, length, kind in PRINTF.findall(text):+ if kind == '%':+ percents += 1+ continue+ index = int(position) if position else nxt+ if not position:+ nxt += 1+ args[index] = f'{precision}{length}{kind}'+ return args, percents, sorted(BRACES.findall(text))+++def raw_keys(path: Path) -> list[str]:+ """The keys in the order the file has them. The files are one entry per line, indented by two spaces."""+ return [m.group(1) for m in re.finditer(r'^ "((?:[^"\\]|\\.)*)": ', path.read_text(encoding='utf-8'), re.M)]+++class LanguageFiles(unittest.TestCase):+ @classmethod+ def setUpClass(cls):+ cls.paths = {p.stem: p for p in sorted(L10N.glob('*.json')) if not p.name.startswith('.')}+ cls.files: dict[str, dict] = {code: json.loads(p.read_text(encoding='utf-8')) for code, p in cls.paths.items()}+ cls.texts = {code: {k: v for k, v in body.items() if k != '_language'} for code, body in cls.files.items()}++ def test_english_and_chinese_exist_and_have_the_same_keys(self):+ for code in REQUIRED:+ self.assertIn(code, self.texts, f'{code}.json is missing')+ self.assertEqual(set(self.texts['en']), set(self.texts['zh']),+ 'English and Chinese need every key: only in en %s, only in zh %s' % (+ sorted(set(self.texts['en']) - set(self.texts['zh'])),+ sorted(set(self.texts['zh']) - set(self.texts['en']))))++ def test_no_language_has_a_key_english_does_not_have(self):+ english = set(self.texts['en'])+ for code, texts in self.texts.items():+ self.assertEqual(sorted(set(texts) - english), [], f'{code}.json has keys that en.json does not have')++ def test_placeholders_match_the_english_text_of_the_same_key(self):+ for code, texts in self.texts.items():+ for key, text in texts.items():+ self.assertEqual(placeholders(text), placeholders(self.texts['en'][key]), f'{code}.json {key}')++ def test_every_value_is_a_non_empty_text(self):+ for code, texts in self.texts.items():+ for key, value in texts.items():+ self.assertIsInstance(value, str, f'{code}.json {key} is not a text')+ self.assertTrue(value.strip(), f'{code}.json {key} is empty')++ def test_every_file_has_a_language_entry_with_name_and_locales(self):+ for code, body in self.files.items():+ entry = body.get('_language')+ self.assertIsInstance(entry, dict, f'{code}.json has no _language')+ self.assertTrue(isinstance(entry.get('name'), str) and entry['name'].strip(), f'{code}.json: _language has no name')+ locales = entry.get('locales')+ self.assertTrue(isinstance(locales, list) and locales and all(isinstance(s, str) and s for s in locales),+ f'{code}.json: _language has no locales')+ self.assertIn(code, locales, f'{code}.json: the code is one of its locales')+ self.assertTrue(all(s == s.lower() for s in locales), f'{code}.json: locales are lowercase')+ if 'order' in entry:+ self.assertTrue(isinstance(entry['order'], int) and not isinstance(entry['order'], bool), f'{code}.json: order is a number')++ def test_the_files_are_flat_and_sorted_with_language_first(self):+ for code, path in self.paths.items():+ keys = raw_keys(path)+ self.assertEqual(keys[:1], ['_language'], f'{code}.json starts with _language')+ self.assertEqual(keys[1:], sorted(keys[1:]), f'{code}.json keys are not sorted')+ self.assertEqual(len(keys), len(set(keys)), f'{code}.json has a duplicate key')+ self.assertEqual(len(keys), len(self.files[code]), f'{code}.json has an entry that is not one line at the top level')+ self.assertTrue(path.read_text(encoding='utf-8').endswith('}\n'), f'{code}.json ends with a newline')++ def test_languages_have_distinct_codes_and_locales(self):+ seen: dict[str, str] = {}+ for code, body in self.files.items():+ for locale in body['_language']['locales']:+ self.assertNotIn(locale, seen, f'{code}.json and {seen.get(locale)}.json both claim {locale}')+ seen[locale] = code+++if __name__ == '__main__':+ unittest.main()diff --git a/frontend/Tests/NX2AppleTests/FrenchLocalizationTests.swift b/frontend/Tests/NX2AppleTests/FrenchLocalizationTests.swiftindex 3e183daa..1da8bd88 100644--- a/frontend/Tests/NX2AppleTests/FrenchLocalizationTests.swift+++ b/frontend/Tests/NX2AppleTests/FrenchLocalizationTests.swift@@ -3,8 +3,8 @@ import XCTest@testable import NXCore@testable import NXLauncher-/// The French overlay covers the whole table. A key added later without its French entry fails here,-/// which is the point: the overlay would otherwise show it in English without anyone noticing.+/// The French overlay reads as French: nothing is left in English but the listed names. Completeness and placeholders for every+/// language are in NXCoreTests/LocalizationRulesTests.swift.final class FrenchLocalizationTests: XCTestCase {/// Keys whose French text is the English one on purpose: names, units, button letters, codes.static let sameAsEnglish: Set<String> = [@@ -21,31 +21,11 @@ final class FrenchLocalizationTests: XCTestCase {"pad.options", "engine.channel.stable", "launch.opt.DM_PRESENT_UPSCALE.off", "launch.opt.DM_PRESENT_UPSCALE.metalfx", "key.tab",]- /// %@, %d, %ld, %%, positional %1$@ and float %.1f: what String(format:) reads.- static func placeholders(_ s: String) -> [String] {- let re = try! NSRegularExpression(pattern: "%(?:\\d+\\$)?(?:\\.\\d+)?l{0,2}[@dfs%]")- return re.matches(in: s, range: NSRange(s.startIndex..., in: s)).map { String(s[Range($0.range, in: s)!]) }- }-- func testEveryKeyHasFrenchText() {- let missing = L10n.table.keys.filter { L10n.fr[$0] == nil }.sorted()- XCTAssertEqual(missing, [], "keys without a French entry")- let extra = L10n.fr.keys.filter { L10n.table[$0] == nil }.sorted()- XCTAssertEqual(extra, [], "French entries for keys the table does not have")- }-func testNothingIsLeftInEnglishButTheListedNames() {let english = L10n.table.compactMap { key, row in L10n.fr[key] == row.en ? key : nil }XCTAssertEqual(Set(english), Self.sameAsEnglish)}- func testPlaceholdersMatchTheEnglishText() {- for (key, row) in L10n.table {- guard let fr = L10n.fr[key] else { continue }- XCTAssertEqual(Self.placeholders(fr), Self.placeholders(row.en), key)- }- }-func testFrenchIsSelectedAndReadsItsCatalog() {XCTAssertEqual(Lang.find("fr"), .fr)XCTAssertEqual(L10n.string("settings.language.fr", .fr), "Français")diff --git a/frontend/Tests/NX2AppleTests/GermanLocalizationTests.swift b/frontend/Tests/NX2AppleTests/GermanLocalizationTests.swiftindex be267d9e..7dc2c119 100644--- a/frontend/Tests/NX2AppleTests/GermanLocalizationTests.swift+++ b/frontend/Tests/NX2AppleTests/GermanLocalizationTests.swift@@ -3,8 +3,8 @@ import XCTest@testable import NXCore@testable import NXLauncher-/// The German catalog (L10n.de) has to be complete and has to keep the rules of the shared table.-/// A string added to the table later needs its German entry, and this fails until it has one.+/// The German catalog (L10n.de) has to read as German and keep the text rules of the shared table.+/// Completeness and placeholders for every language are in NXCoreTests/LocalizationRulesTests.swift.final class GermanLocalizationTests: XCTestCase {/// Keys whose German text is the English text on purpose: names, units and button letters.private let sameAsEnglish: Set<String> = [@@ -23,33 +23,12 @@ final class GermanLocalizationTests: XCTestCase {"launch.opt.DM_FPS_TARGET.30", "launch.opt.DM_FPS_TARGET.60", "launch.opt.DM_PRESENT_UPSCALE.metalfx",]- /// printf-style placeholders in order: %@, %d, %ld, %lld, %.0f and %.1f, positional %1$@, and %%.- private func placeholders(_ s: String) -> [String] {- let re = try! NSRegularExpression(pattern: "%(?:[0-9]+\\$)?(?:\\.[0-9]+)?(?:ll|l)?[@dsf%]")- return re.matches(in: s, range: NSRange(s.startIndex..., in: s)).map { String(s[Range($0.range, in: s)!]) }- }-- func testEveryKeyHasAGermanEntry() {- for key in L10n.table.keys.sorted() {- let de = L10n.de[key]- XCTAssertNotNil(de, "\(key) has no German text")- XCTAssertFalse(de?.isEmpty ?? true, key)- }- for key in L10n.de.keys { XCTAssertNotNil(L10n.table[key], "\(key) is German text for a key that does not exist") }- }-func testGermanIsNotLeftInEnglish() {for (key, row) in L10n.table where !sameAsEnglish.contains(key) {XCTAssertNotEqual(L10n.de[key], row.en, "\(key) has the English text in the German table")}}- func testFormatPlaceholdersMatchEnglishInCountAndOrder() {- for (key, row) in L10n.table {- XCTAssertEqual(placeholders(L10n.string(key, .de)), placeholders(row.en), key)- }- }-func testGermanFollowsTheTextRules() {for (key, row) in L10n.table {let de = L10n.string(key, .de)diff --git a/frontend/Tests/NXCoreTests/LocalizationRulesTests.swift b/frontend/Tests/NXCoreTests/LocalizationRulesTests.swiftnew file mode 100644index 00000000..68804e9a--- /dev/null+++ b/frontend/Tests/NXCoreTests/LocalizationRulesTests.swift@@ -0,0 +1,127 @@+import XCTest+@testable import NXCore++/// The rules every language file in `frontend/l10n` keeps (LNPANDY/NX2Apple#388). The languages are the files of the folder, so a new+/// `<code>.json` is checked here without a change to this test. The Qt front end has the same rules in+/// `frontend-qt/tests/test_localization_rules.py`.+final class LocalizationRulesTests: XCTestCase {+ private static let directory = LocalizationFiles.directory()+ private static let required = ["en", "zh"]++ private func files() throws -> [(code: String, url: URL)] {+ let directory = try XCTUnwrap(Self.directory, "frontend/l10n was not found")+ return LocalizationFiles.codes(in: directory).map { ($0, directory.appendingPathComponent("\($0).json")) }+ }++ private func object(_ url: URL) throws -> [String: Any] {+ try XCTUnwrap(try JSONSerialization.jsonObject(with: Data(contentsOf: url)) as? [String: Any], "\(url.lastPathComponent) is not a JSON object")+ }++ private func texts() throws -> [String: [String: String]] {+ var out: [String: [String: String]] = [:]+ for (code, url) in try files() {+ out[code] = try object(url).filter { $0.key != "_language" }.compactMapValues { $0 as? String }+ }+ return out+ }++ /// What String(format:) reads: the type of each argument by its position, the count of %%, and `{0}` or `{name}` braces.+ /// A positional `%2$@` is argument 2, so a translation may reorder arguments. Without a position they count 1, 2, 3.+ private struct Placeholders: Equatable {+ var arguments: [Int: String] = [:]+ var percents = 0+ var braces: [String] = []++ init(_ text: String) {+ let ns = text as NSString+ let printf = try! NSRegularExpression(pattern: "%(?:([0-9]+)\\$)?(\\.[0-9]+)?(ll|l)?([@dsf%])")+ var next = 1+ for match in printf.matches(in: text, range: NSRange(location: 0, length: ns.length)) {+ func group(_ i: Int) -> String { match.range(at: i).location == NSNotFound ? "" : ns.substring(with: match.range(at: i)) }+ if group(4) == "%" { percents += 1; continue }+ var index = next+ if let position = Int(group(1)) { index = position } else { next += 1 }+ arguments[index] = group(2) + group(3) + group(4)+ }+ let brace = try! NSRegularExpression(pattern: "\\{(\\w*)\\}")+ braces = brace.matches(in: text, range: NSRange(location: 0, length: ns.length)).map { ns.substring(with: $0.range(at: 1)) }.sorted()+ }+ }++ /// The keys in the order the file has them. The files are one entry per line, indented by two spaces.+ private func rawKeys(_ url: URL) throws -> [String] {+ let text = try String(contentsOf: url, encoding: .utf8)+ let re = try NSRegularExpression(pattern: "^ \"((?:[^\"\\\\]|\\\\.)*)\": ", options: .anchorsMatchLines)+ let ns = text as NSString+ return re.matches(in: text, range: NSRange(location: 0, length: ns.length)).map { ns.substring(with: $0.range(at: 1)) }+ }++ func testEnglishAndChineseExistAndHaveTheSameKeys() throws {+ let all = try texts()+ for code in Self.required { XCTAssertNotNil(all[code], "\(code).json is missing") }+ let en = Set(all["en"]?.keys ?? [:].keys), zh = Set(all["zh"]?.keys ?? [:].keys)+ XCTAssertEqual(en.subtracting(zh).sorted(), [], "keys only in en.json")+ XCTAssertEqual(zh.subtracting(en).sorted(), [], "keys only in zh.json")+ }++ func testNoLanguageHasAKeyEnglishDoesNotHave() throws {+ let all = try texts()+ let english = Set(all["en"]?.keys ?? [:].keys)+ for (code, texts) in all { XCTAssertEqual(Set(texts.keys).subtracting(english).sorted(), [], "\(code).json has keys that en.json does not have") }+ }++ func testPlaceholdersMatchTheEnglishTextOfTheSameKey() throws {+ let all = try texts()+ let english = all["en"] ?? [:]+ for (code, texts) in all {+ for (key, text) in texts {+ guard let source = english[key] else { continue }+ XCTAssertEqual(Placeholders(text), Placeholders(source), "\(code).json \(key)")+ }+ }+ }++ func testEveryValueIsANonEmptyText() throws {+ for (code, url) in try files() {+ for (key, value) in try object(url) where key != "_language" {+ guard let text = value as? String else { XCTFail("\(code).json \(key) is not a text"); continue }+ XCTAssertFalse(text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty, "\(code).json \(key) is empty")+ }+ }+ }++ func testEveryFileHasALanguageEntryWithNameAndLocales() throws {+ for (code, url) in try files() {+ let entry = try XCTUnwrap(try object(url)["_language"] as? [String: Any], "\(code).json has no _language")+ XCTAssertFalse((entry["name"] as? String ?? "").trimmingCharacters(in: .whitespaces).isEmpty, "\(code).json: _language has no name")+ let locales = entry["locales"] as? [String] ?? []+ XCTAssertFalse(locales.isEmpty, "\(code).json: _language has no locales")+ XCTAssertTrue(locales.allSatisfy { !$0.isEmpty && $0 == $0.lowercased() }, "\(code).json: locales are lowercase and not empty")+ XCTAssertTrue(locales.contains(code), "\(code).json: the code is one of its locales")+ if let order = entry["order"] { XCTAssertTrue(order is Int, "\(code).json: order is a number") }+ }+ }++ func testTheFilesAreFlatAndSortedWithLanguageFirst() throws {+ for (code, url) in try files() {+ let keys = try rawKeys(url)+ XCTAssertEqual(keys.first, "_language", "\(code).json starts with _language")+ // Sorted by code point, as Python's sorted() writes them, so the Mac and the Windows launcher see the same diff.+ let rest = Array(keys.dropFirst())+ XCTAssertEqual(rest, rest.sorted { Array($0.unicodeScalars.map(\.value)).lexicographicallyPrecedes($1.unicodeScalars.map(\.value)) }, "\(code).json keys are not sorted")+ XCTAssertEqual(keys.count, Set(keys).count, "\(code).json has a duplicate key")+ XCTAssertEqual(keys.count, try object(url).count, "\(code).json has an entry that is not one line at the top level")+ XCTAssertTrue(try String(contentsOf: url, encoding: .utf8).hasSuffix("}\n"), "\(code).json ends with a newline")+ }+ }++ func testLanguagesHaveDistinctLocales() throws {+ var seen: [String: String] = [:]+ for language in LocalizationFiles.languages() {+ for locale in language.locales {+ XCTAssertNil(seen[locale], "\(language.code).json and \(seen[locale] ?? "").json both claim \(locale)")+ seen[locale] = language.code+ }+ }+ }+}