Skip to content

Play your own Switch games on iPhone/iPad — one-click macOS app, no terminal. | 把 Switch 游戏装进 iPhone:图形界面一键构建,不用命令行。Bring your own game.

Run the Mac launcher tests on their own defaults

v0lumehi093886b6515e
diff --git a/frontend/ARCHITECTURE.md b/frontend/ARCHITECTURE.md
index 3b37180a..99a1ed48 100644
--- a/frontend/ARCHITECTURE.md
+++ b/frontend/ARCHITECTURE.md
@@ -61,7 +61,7 @@ A view observes only the stores it shows. A change in one store invalidates only
- **Logic stays out.** What needs no state (parsing, comparing, deciding what may be installed) is a static function in `NXCore` (`AppUpdate`) with its own tests. The store only calls it and keeps the result.
- **Actions check their own conditions.** `install` refuses while a build runs and for a copy that is not a released one. The view does not decide that.
- **Async work.** The method that starts it sets its state synchronously (`busy = true`), runs a `Task` on the main actor, hops off it for blocking work (`Task.detached`) and returns the `Task`, so a test awaits `store.checkForUpdate().value`.
-- **Tests.** `NXModelTests`, a `@MainActor` test class, no SwiftUI. Fakes for the services, a `UserDefaults` suite of its own, files in a temporary folder.
+- **Tests.** `NXModelTests`, a `@MainActor` test class, no SwiftUI. Fakes for the services, a `UserDefaults` suite of its own, files in a temporary folder. The tests of `NX2AppleTests` derive from `IsolatedDefaultsTestCase`: `LauncherStores(defaults: testDefaults)` keeps the settings of a test in a suite of its own, and a test that leaves a key in the shared test domain fails.
- **Wiring.** `LauncherStores` creates the store and connects it to the others. Views take it as an `@ObservedObject` parameter (or as an environment object, as `Localizer`), so a change redraws the views that show it and nothing else.
### `appVersion`
diff --git a/frontend/Sources/NX2Apple/LauncherStores.swift b/frontend/Sources/NX2Apple/LauncherStores.swift
index 36e85ba5..a6d1d7fe 100644
--- a/frontend/Sources/NX2Apple/LauncherStores.swift
+++ b/frontend/Sources/NX2Apple/LauncherStores.swift
@@ -26,8 +26,10 @@ import NXModel
/// - Parameters:
/// - xcrun: runs xcodebuild and devicectl: a test points it at a stand-in.
/// - volumesRoot: where external drives are mounted.
+ /// - defaults: where the stores keep their settings: a test passes its own suite, so it neither reads nor writes the shared ones.
init(localizer: Localizer = Localizer(), runner: ProcessRunner = SystemProcessRunner(), gitCheckout: GitCheckout? = nil,
- releases: ReleaseSource = GitHubReleases(), xcrun: String = "/usr/bin/xcrun", volumesRoot: String = "/Volumes") {
+ releases: ReleaseSource = GitHubReleases(), xcrun: String = "/usr/bin/xcrun", volumesRoot: String = "/Volumes",
+ defaults: UserDefaults = .standard) {
_ = Self.endGroupsWhenQuitting
let git = gitCheckout ?? SystemGitCheckout(runner: runner)
self.localizer = localizer; self.runner = runner; self.gitCheckout = git; self.releases = releases
@@ -35,38 +37,38 @@ import NXModel
let laterBuild = Later<BuildStore>(), laterEngine = Later<EngineSyncStore>()
let repo = RepoStore(
- localizer: localizer, git: git,
+ localizer: localizer, git: git, defaults: defaults,
buildRunning: { laterBuild.value?.running ?? false },
isReleaseApp: { laterEngine.value?.usesEngineStore ?? false },
log: { log.append($0) },
didMove: { _ = laterEngine.value?.syncEngine() }) // the pull may have moved the pin or the patches
let dependencies = DependencyStore(
- localizer: localizer, runner: runner, repo: repo,
- needsIOS: { Self.needsIOSPlatform() },
+ localizer: localizer, runner: runner, repo: repo, defaults: defaults,
+ needsIOS: { Self.needsIOSPlatform(defaults: defaults) },
openAppStore: { NSWorkspace.shared.open(URL(fileURLWithPath: "/Applications/App Store.app")) },
log: { log.append($0) },
installFailed: { laterBuild.value?.note($0) })
let engineSync = EngineSyncStore(
- localizer: localizer, runner: runner, repo: repo, python: dependencies,
+ localizer: localizer, runner: runner, repo: repo, python: dependencies, defaults: defaults,
setRepoPath: { repo.path = $0 },
buildRunning: { laterBuild.value?.running ?? false },
autoUpdate: { repo.autoUpdate },
log: { log.append($0) })
laterEngine.value = engineSync
- let devices = DeviceStore(runner: runner, xcrun: xcrun)
+ let devices = DeviceStore(runner: runner, xcrun: xcrun, defaults: defaults)
let updates = AppUpdateStore(
- localizer: localizer, runner: runner, releases: releases,
+ localizer: localizer, runner: runner, releases: releases, defaults: defaults,
buildRunning: { (laterBuild.value?.running ?? false) || ProcessGroups.buildProcessesAlive },
terminate: {
NSApp.terminate(nil)
DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) { exit(0) }
})
let build = BuildStore(
- localizer: localizer, runner: runner, log: log, repo: repo, deps: dependencies, engine: engineSync, devices: devices,
+ localizer: localizer, runner: runner, log: log, repo: repo, deps: dependencies, engine: engineSync, devices: devices, defaults: defaults,
volumesRoot: volumesRoot,
targetChanged: {
// A Mac-only setup needs no iOS SDK for a Mac build, but does for an iPhone one (needsIOSPlatform)
- if UserDefaults.standard.string(forKey: OnboardingDefaults.platform) == "mac" { _ = dependencies.check() }
+ if defaults.string(forKey: OnboardingDefaults.platform) == "mac" { _ = dependencies.check() }
})
laterBuild.value = build
self.repo = repo; self.engineSync = engineSync; self.dependencies = dependencies; self.deviceStore = devices
diff --git a/frontend/Tests/NX2AppleTests/AddOnContentCopyTests.swift b/frontend/Tests/NX2AppleTests/AddOnContentCopyTests.swift
index 2bf51b7c..99a2fdec 100644
--- a/frontend/Tests/NX2AppleTests/AddOnContentCopyTests.swift
+++ b/frontend/Tests/NX2AppleTests/AddOnContentCopyTests.swift
@@ -6,7 +6,7 @@ import NXModel
/// The slim default leaves DLC images in the work folder, and the archive step copies them into the game folder
/// whichever way it ends (issue #202). The copy is one helper, so this drives it with a stale destination.
-final class AddOnContentCopyTests: XCTestCase {
+final class AddOnContentCopyTests: IsolatedDefaultsTestCase {
func testCopiesTheImagesAndReplacesAStaleFolder() throws {
let fm = FileManager.default
let root = fm.temporaryDirectory.appendingPathComponent("nxnative-aoc-" + UUID().uuidString)
diff --git a/frontend/Tests/NX2AppleTests/BuildFailureRowsTests.swift b/frontend/Tests/NX2AppleTests/BuildFailureRowsTests.swift
index a0ddb461..b1e20dc2 100644
--- a/frontend/Tests/NX2AppleTests/BuildFailureRowsTests.swift
+++ b/frontend/Tests/NX2AppleTests/BuildFailureRowsTests.swift
@@ -6,7 +6,7 @@ import NXModel
/// The failure rows for keys, game files and the build's own steps (issue #141): what sets each one, that its text names the
/// action, and that its button does it. The log lines are the script's real messages (Tests/Fixtures/build_failures.json).
-@MainActor final class BuildFailureRowsTests: XCTestCase {
+@MainActor final class BuildFailureRowsTests: IsolatedDefaultsTestCase {
func fixture(_ id: String) throws -> BuildFailureTests.Fixture {
try XCTUnwrap(BuildFailureTests().fixtures().first { $0.id == id }, id)
}
@@ -47,7 +47,7 @@ import NXModel
XCTAssertEqual(BuildFailureClassifier.classify("[RED] the zbic package decoded it").kind, .unknown)
XCTAssertTrue(L10n.table["fail.zbic.next"]?.en.contains("pip install zbic") ?? false)
XCTAssertEqual(L10n.table["fail.zbic.button"]?.en, "Install zbic")
- let mStores = LauncherStores(); let m = mStores.build
+ let mStores = LauncherStores(defaults: testDefaults); let m = mStores.build
m.logTail = log
m.noteFailure()
XCTAssertEqual(m.failure?.kind, .zbic)
@@ -68,7 +68,7 @@ import NXModel
let low = BuildFailureClassifier.classify(try fixture("disk.low").text)
XCTAssertEqual(low, BuildFailure(kind: .diskFull, gameName: nil, detail: try fixture("disk.low").gb))
XCTAssertEqual(BuildFailureClassifier.classify(try fixture("disk.full").text), BuildFailure(kind: .diskFull, gameName: nil, detail: nil))
- let mStores = LauncherStores(); let m = mStores.build
+ let mStores = LauncherStores(defaults: testDefaults); let m = mStores.build
m.lang = .en // the English text, whatever the Mac's language
XCTAssertTrue(m.failureWhat(low).contains("40 GB"), m.failureWhat(low))
XCTAssertFalse(m.failureWhat(BuildFailure(kind: .diskFull, gameName: nil)).contains("GB"))
@@ -83,7 +83,7 @@ import NXModel
try FileManager.default.createDirectory(at: volumes.appendingPathComponent("Games"), withIntermediateDirectories: true)
XCTAssertEqual(BuildFailureClassifier.classify(log, inputs: .init(keysPath: "", paths: [gone], volumes: volumes.path)).kind, .noTitleID, "the drive is there")
XCTAssertEqual(BuildFailureClassifier.classify(log, inputs: .init(keysPath: "/Users/x/prod.keys", paths: ["/Users/x/g.nsp"], volumes: volumes.path)).kind, .noTitleID, "a path off /Volumes is no drive")
- let mStores = LauncherStores(); let m = mStores.build
+ let mStores = LauncherStores(defaults: testDefaults); let m = mStores.build
m.lang = .en // the quotes are English ones whatever the device language is
XCTAssertTrue(m.failureWhat(f).contains("“Games”"))
}
@@ -143,7 +143,7 @@ import NXModel
func testAFailedBuildShowsTheRowForItsLogLine() throws {
for (id, kind) in [("keys.missing", BuildFailureKind.keys), ("games.several", .severalGames), ("games.noTitleID", .noTitleID), ("disk.low", .diskFull), ("disk.full", .diskFull)] {
- let mStores = LauncherStores(); let m = mStores.build
+ let mStores = LauncherStores(defaults: testDefaults); let m = mStores.build
m.logTail = try fixture(id).text + "\n"
m.noteFailure()
XCTAssertEqual(m.failure?.kind, kind, id)
@@ -152,7 +152,7 @@ import NXModel
}
func testTheKeysButtonOpensTheKeysPicker() {
- let mStores = LauncherStores(); let m = mStores.build
+ let mStores = LauncherStores(defaults: testDefaults); let m = mStores.build
var opened = 0
m.chooseKeys = { opened += 1 }
m.failure = BuildFailure(kind: .keys, gameName: nil)
@@ -162,7 +162,7 @@ import NXModel
func testShowFolderRevealsTheGameFolderAndForAFullDiskTheBuildFolder() throws {
let dir = try tempFolder()
- let mStores = LauncherStores(); let m = mStores.build
+ let mStores = LauncherStores(defaults: testDefaults); let m = mStores.build
var shown: [String] = []
m.revealFolder = { shown.append($0.path) }
m.gameDir = dir.path
@@ -187,7 +187,7 @@ import NXModel
}
@MainActor func testAnInstallStepThatFailedShowsItsRow() {
- let mStores = LauncherStores(); let m = mStores.build
+ let mStores = LauncherStores(defaults: testDefaults); let m = mStores.build
mStores.deviceStore.signingTeam = "TEAM123456"
mStores.deviceStore.readTeams = { [SigningTeam(id: "TEAM123456", identity: "")] }
m.noteInstallFailure(.sign, error: "error: Failed to register bundle identifier: cannot be registered to your development team")
@@ -205,7 +205,7 @@ import NXModel
}
func testTryAgainStartsANewBuildAndClearsTheCard() {
- let mStores = LauncherStores(); let m = mStores.build
+ let mStores = LauncherStores(defaults: testDefaults); let m = mStores.build
m.target = BuildTarget.mac // the iPhone / iPad target stops first, at the device check
m.failure = BuildFailure(kind: .deviceTransfer, gameName: nil)
m.fixBuildFailure(.deviceTransfer) // no repository here: the build stops at once, but it has started and dropped the old card
@@ -213,7 +213,7 @@ import NXModel
}
func testTheXcodeButtonOpensXcodeWhenItIsInstalled() {
- let mStores = LauncherStores(); let m = mStores.build
+ let mStores = LauncherStores(defaults: testDefaults); let m = mStores.build
var opened: [URL] = []
m.openApp = { opened.append($0) }
m.failure = BuildFailure(kind: .teamTaken, gameName: nil)
diff --git a/frontend/Tests/NX2AppleTests/BuildFailureTests.swift b/frontend/Tests/NX2AppleTests/BuildFailureTests.swift
index 346917e8..6b36ff6d 100644
--- a/frontend/Tests/NX2AppleTests/BuildFailureTests.swift
+++ b/frontend/Tests/NX2AppleTests/BuildFailureTests.swift
@@ -7,7 +7,7 @@ import NXModel
/// The script's early stops, turned into hints. The fixture holds the real message of every pattern, copied from the script
/// (Tests/Fixtures/build_failures.json, shared with the Qt front end's test).
-@MainActor final class BuildFailureTests: XCTestCase {
+@MainActor final class BuildFailureTests: IsolatedDefaultsTestCase {
struct Fixture: Decodable {
let id: String, kind: String, source: String, fragment: String, text: String
let game: String?, folder: String?, gb: String?
@@ -135,7 +135,7 @@ import NXModel
}
func testNothingIsArmedUntilTheConfirmation() {
- let mStores = LauncherStores(); let m = mStores.build
+ let mStores = LauncherStores(defaults: testDefaults); let m = mStores.build
m.failure = BuildFailure(kind: .otherMetal, gameName: nil)
m.requestBuildAnyway()
XCTAssertEqual(m.confirmingOverride, .otherMetal)
@@ -147,7 +147,7 @@ import NXModel
}
func testAConfirmedOverrideServesOneBuildOnly() {
- let mStores = LauncherStores(); let m = mStores.build
+ let mStores = LauncherStores(defaults: testDefaults); let m = mStores.build
m.target = BuildTarget.mac // the iPhone / iPad target stops first, at the device check
m.failure = BuildFailure(kind: .damagedNSP, gameName: nil)
m.requestBuildAnyway()
@@ -159,7 +159,7 @@ import NXModel
}
func testAStopWithoutAnOverrideCannotBeBuiltAnyway() {
- let mStores = LauncherStores(); let m = mStores.build
+ let mStores = LauncherStores(defaults: testDefaults); let m = mStores.build
for k in BuildFailureKind.allCases where k.overrideFlag == nil {
m.failure = BuildFailure(kind: k, gameName: nil)
m.requestBuildAnyway()
@@ -168,7 +168,7 @@ import NXModel
}
func testAFailedBuildShowsTheHintInsteadOfTheLastLine() {
- let mStores = LauncherStores(); let m = mStores.build
+ let mStores = LauncherStores(defaults: testDefaults); let m = mStores.build
m.logTail = "[RED] the iOS SDK is not installed: install the iOS platform in Xcode\n"
m.noteFailure()
XCTAssertEqual(m.failure?.kind, .iosSDK)
@@ -254,7 +254,7 @@ import NXModel
}
@MainActor func testTheMetalRowsDetailReadsInTheLauncher() {
- let mStores = LauncherStores(); let m = mStores.build
+ let mStores = LauncherStores(defaults: testDefaults); let m = mStores.build
let dep = DependencyCheck.metalDep(runs: true, lock: Self.lock, now: ["macosx": Self.other], needsIOS: false)
XCTAssertTrue(mStores.dependencies.detail(of: dep).contains(Self.other), mStores.dependencies.detail(of: dep))
XCTAssertTrue(mStores.dependencies.detail(of: dep).contains(Self.pinned), mStores.dependencies.detail(of: dep))
@@ -284,7 +284,7 @@ import NXModel
("hint-other-metal-zh", .otherMetal, .zh)]
+ [BuildFailureKind.keys, .severalGames, .noTitleID, .driveMissing, .diskFull, .teamTaken, .noSigningAccount, .deviceTransfer].flatMap { k in
[("row-\(k.rawValue)", k, Lang.en), ("row-\(k.rawValue)-zh", k, Lang.zh)] } {
- let mStores = LauncherStores(); let m = mStores.build
+ let mStores = LauncherStores(defaults: testDefaults); let m = mStores.build
m.lang = CaptureLanguage.current(lang)
m.failure = BuildFailure(kind: kind, gameName: nil, detail: kind == .diskFull ? "40" : kind == .driveMissing ? "Games" : nil)
m.doneNote = m.failureWhat(m.failure!)
@@ -293,7 +293,7 @@ import NXModel
BuildFailureCard(m: m).environmentObject(mStores.localizer).padding(24)
})
}
- let mStores = LauncherStores(); let m = mStores.build
+ let mStores = LauncherStores(defaults: testDefaults); let m = mStores.build
m.lang = .en
MainActor.assumeIsolated { mStores.dependencies.checked = true }
MainActor.assumeIsolated { mStores.dependencies.deps = [Dep(id: "xcode", name: "dep.xcode", hint: "dep.xcode.hint", present: true, installCmd: []),
diff --git a/frontend/Tests/NX2AppleTests/BuildFolderPanelTests.swift b/frontend/Tests/NX2AppleTests/BuildFolderPanelTests.swift
index 0d4e5a45..0432dcdb 100644
--- a/frontend/Tests/NX2AppleTests/BuildFolderPanelTests.swift
+++ b/frontend/Tests/NX2AppleTests/BuildFolderPanelTests.swift
@@ -3,7 +3,7 @@ import XCTest
@testable import NX2Apple
/// The Build tab's Save to dialog must offer "New Folder": the folder for the IPA often does not exist yet (#477).
-@MainActor final class BuildFolderPanelTests: XCTestCase {
+@MainActor final class BuildFolderPanelTests: IsolatedDefaultsTestCase {
func testTheSaveToPanelCanCreateFolders() {
let panel = LauncherStores.buildFolderPanel()
XCTAssertTrue(panel.canCreateDirectories)
diff --git a/frontend/Tests/NX2AppleTests/BuildLogTests.swift b/frontend/Tests/NX2AppleTests/BuildLogTests.swift
index 3b533aab..343de0d5 100644
--- a/frontend/Tests/NX2AppleTests/BuildLogTests.swift
+++ b/frontend/Tests/NX2AppleTests/BuildLogTests.swift
@@ -3,7 +3,7 @@ import XCTest
@testable import NXModel
/// LNPANDY/NX2Apple#387, step 3: the build log is a store of its own and needs no SwiftUI.
-@MainActor final class BuildLogTests: XCTestCase {
+@MainActor final class BuildLogTests: IsolatedDefaultsTestCase {
func testAppendAddsText() {
let log = BuildLog()
log.append("one\n")
diff --git a/frontend/Tests/NX2AppleTests/BuildNotificationsTests.swift b/frontend/Tests/NX2AppleTests/BuildNotificationsTests.swift
index 5c6afc5e..7464f0e6 100644
--- a/frontend/Tests/NX2AppleTests/BuildNotificationsTests.swift
+++ b/frontend/Tests/NX2AppleTests/BuildNotificationsTests.swift
@@ -6,7 +6,7 @@ import NXModel
@testable import NXLauncher
/// When a build notification is posted and what it says (issue #64). Nothing here touches the notification center.
-@MainActor final class BuildNotificationsTests: XCTestCase {
+@MainActor final class BuildNotificationsTests: IsolatedDefaultsTestCase {
private func en(_ key: String) -> String { L10n.string(key, .en) }
func testOnlyAFinishedOrFailedBuildIsNotified() {
@@ -58,7 +58,7 @@ import NXModel
let temporary = FileManager.default.temporaryDirectory.appendingPathComponent("nxnative-notify-" + UUID().uuidString)
try FileManager.default.createDirectory(at: temporary, withIntermediateDirectories: true)
defer { try? FileManager.default.removeItem(at: temporary) }
- let modelStores = LauncherStores(); let model = modelStores.build
+ let modelStores = LauncherStores(defaults: testDefaults); let model = modelStores.build
model.lang = CaptureLanguage.current(.en)
MainActor.assumeIsolated { modelStores.dependencies.checked = true }
MainActor.assumeIsolated { modelStores.dependencies.deps = [Dep(id: "test", name: "Xcode", hint: "", present: true, installCmd: [])] }
diff --git a/frontend/Tests/NX2AppleTests/BuildTargetTests.swift b/frontend/Tests/NX2AppleTests/BuildTargetTests.swift
index 6746a2d5..51613efe 100644
--- a/frontend/Tests/NX2AppleTests/BuildTargetTests.swift
+++ b/frontend/Tests/NX2AppleTests/BuildTargetTests.swift
@@ -5,7 +5,7 @@ import XCTest
/// The launcher builds for this Mac or for the one shared app on an iPhone or iPad. Settings and library files written
/// when one IPA per game was a target still load, and older single-IPA builds stay in the library.
-final class BuildTargetTests: XCTestCase {
+final class BuildTargetTests: IsolatedDefaultsTestCase {
private var temporary: URL!
override func setUpWithError() throws {
diff --git a/frontend/Tests/NX2AppleTests/BundledToolsTests.swift b/frontend/Tests/NX2AppleTests/BundledToolsTests.swift
index cf9ffe21..069947e8 100644
--- a/frontend/Tests/NX2AppleTests/BundledToolsTests.swift
+++ b/frontend/Tests/NX2AppleTests/BundledToolsTests.swift
@@ -6,7 +6,7 @@ import NXModel
/// The release app carries its build tools and a Python (BundledTools.swift): the dependency check prefers them to Homebrew's and to
/// a system Python, and the build's PATH starts with them. A fake bundle stands in for Contents/Resources.
-final class BundledToolsTests: XCTestCase {
+final class BundledToolsTests: IsolatedDefaultsTestCase {
private var root: URL!
override func setUpWithError() throws {
diff --git a/frontend/Tests/NX2AppleTests/CheatFilesTests.swift b/frontend/Tests/NX2AppleTests/CheatFilesTests.swift
index 8f853ed7..08d3c3b9 100644
--- a/frontend/Tests/NX2AppleTests/CheatFilesTests.swift
+++ b/frontend/Tests/NX2AppleTests/CheatFilesTests.swift
@@ -8,7 +8,7 @@ import NXModel
/// Issue #97: the cheat files the launcher manages, as the host reads them (dm/host/hle_cheats.c, docs/frontends.md "Cheats"). The
/// expectations are written by hand from the contract and from the host's parser, not generated by the code under test. Everything
/// runs in a temporary folder, devicectl is a stand-in, and no test reaches a device or the real Application Support.
-@MainActor final class CheatFilesTests: XCTestCase {
+@MainActor final class CheatFilesTests: IsolatedDefaultsTestCase {
private var temporary: URL!
private let titleID = "010015100B514000"
private let build = "CD57B23FA4BBAD65"
@@ -262,7 +262,7 @@ import NXModel
}
func testTheImportMessageSaysWhatCameInAndWhatDidNot() {
- let mStores = LauncherStores(); let m = mStores.build; m.lang = .en
+ let mStores = LauncherStores(defaults: testDefaults); let m = mStores.build; m.lang = .en
XCTAssertEqual(CheatsView.importMessage(.init(imported: ["A", "B"]), loc: mStores.localizer).0, "Files imported: 2.")
XCTAssertTrue(CheatsView.importMessage(.init(imported: ["A"], skipped: ["x.txt"]), loc: mStores.localizer).0.contains("x.txt"))
XCTAssertFalse(CheatsView.importMessage(.init(), loc: mStores.localizer).1)
@@ -374,7 +374,7 @@ import NXModel
try fm.createDirectory(at: ios, withIntermediateDirectories: true)
try PropertyListSerialization.data(fromPropertyList: ["CFBundleIdentifier": "com.example.zelda"], format: .xml, options: 0).write(to: ios.appendingPathComponent("Info.plist"))
- let modelStores = LauncherStores(); let model = modelStores.build
+ let modelStores = LauncherStores(defaults: testDefaults); let model = modelStores.build
model.lang = .en
MainActor.assumeIsolated { modelStores.dependencies.checked = true }
MainActor.assumeIsolated { modelStores.dependencies.deps = [Dep(id: "test", name: "Xcode", hint: "", present: true, installCmd: [])] }
@@ -432,7 +432,7 @@ import NXModel
}
/// Issue #252: an iPhone or iPad game runs data cheats only, so the Cheats sheet carries a note for a game with an iOS build.
-@MainActor final class CheatsIOSNoteTests: XCTestCase {
+@MainActor final class CheatsIOSNoteTests: IsolatedDefaultsTestCase {
func testNoteShowsOnlyWithAnIOSBuild() throws {
let dir = FileManager.default.temporaryDirectory.appendingPathComponent("nxnative-iosnote-" + UUID().uuidString)
try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
diff --git a/frontend/Tests/NX2AppleTests/CloudFolderTests.swift b/frontend/Tests/NX2AppleTests/CloudFolderTests.swift
index d4f202b5..4a55c974 100644
--- a/frontend/Tests/NX2AppleTests/CloudFolderTests.swift
+++ b/frontend/Tests/NX2AppleTests/CloudFolderTests.swift
@@ -6,18 +6,15 @@ import NXModel
/// #263: a build folder in iCloud Drive fails at the signing step ("resource fork, Finder information, or similar detritus not
/// allowed"). The launcher says so before the build starts, and reads the same words from a log.
-@MainActor final class CloudFolderTests: XCTestCase {
+@MainActor final class CloudFolderTests: IsolatedDefaultsTestCase {
private var home: URL!
- private var saved: [(String, Any?)] = []
override func setUpWithError() throws {
- saved = ["repoPath", "buildOutputDirectory"].map { ($0, UserDefaults.standard.object(forKey: $0)) }
home = FileManager.default.temporaryDirectory.appendingPathComponent("nspb-cloud-" + UUID().uuidString)
try FileManager.default.createDirectory(at: home, withIntermediateDirectories: true)
}
override func tearDownWithError() throws {
- for (key, value) in saved { UserDefaults.standard.set(value, forKey: key) }
try? FileManager.default.removeItem(at: home)
}
@@ -114,7 +111,7 @@ import NXModel
try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
try "x".write(to: url, atomically: true, encoding: .utf8)
}
- let mStores = LauncherStores(); let m = mStores.build
+ let mStores = LauncherStores(defaults: testDefaults); let m = mStores.build
m.target = BuildTarget.mac // the iPhone / iPad target stops first, at the device check
mStores.repo.path = repo.path
m.outDir = ""
diff --git a/frontend/Tests/NX2AppleTests/CloudSavesMigrationTests.swift b/frontend/Tests/NX2AppleTests/CloudSavesMigrationTests.swift
index f1e7f5d3..c5009bdd 100644
--- a/frontend/Tests/NX2AppleTests/CloudSavesMigrationTests.swift
+++ b/frontend/Tests/NX2AppleTests/CloudSavesMigrationTests.swift
@@ -6,7 +6,7 @@ import XCTest
/// The `DM_SAVE_SYNC=icloud` keyword changed meaning in the engine (NX2Apple Saves became nxnative Saves). A player whose Mac app
/// uses the keyword and whose iPhone app a bookmark to NX2Apple Saves must keep both on that folder. A folder chosen in either
/// app's window is already a path and is never touched.
-final class CloudSavesMigrationTests: XCTestCase {
+final class CloudSavesMigrationTests: IsolatedDefaultsTestCase {
private var temporary: URL!
private var drive: URL { temporary.appendingPathComponent("CloudDocs") }
private var support: URL { temporary.appendingPathComponent("nxnative") }
diff --git a/frontend/Tests/NX2AppleTests/ConsoleLiveTests.swift b/frontend/Tests/NX2AppleTests/ConsoleLiveTests.swift
index 177bf878..5c7ba377 100644
--- a/frontend/Tests/NX2AppleTests/ConsoleLiveTests.swift
+++ b/frontend/Tests/NX2AppleTests/ConsoleLiveTests.swift
@@ -5,7 +5,7 @@ import SwiftUI
@testable import NXLauncher
/// The live console driver over a real GameLibrary in a temporary folder, with fake controllers and a fake launch call.
-@MainActor final class ConsoleLiveTests: XCTestCase {
+@MainActor final class ConsoleLiveTests: IsolatedDefaultsTestCase {
private var temporary: URL!
private let titleID = "01001A9012345000"
private let bundleID = "org.nxnative.consolelivetests"
diff --git a/frontend/Tests/NX2AppleTests/ConsolePadTests.swift b/frontend/Tests/NX2AppleTests/ConsolePadTests.swift
index 61c2716a..f007ad06 100644
--- a/frontend/Tests/NX2AppleTests/ConsolePadTests.swift
+++ b/frontend/Tests/NX2AppleTests/ConsolePadTests.swift
@@ -8,7 +8,7 @@ import NXModel
/// The player-mode setting's plumbing and the controller path into console mode (the same LauncherGamepad.perform
/// closure the desktop launcher and the onboarding use). A real controller still needs a manual check.
-@MainActor final class ConsolePadTests: XCTestCase {
+@MainActor final class ConsolePadTests: IsolatedDefaultsTestCase {
private func freshDefaults() -> UserDefaults {
let name = "ConsolePadTests.\(UUID().uuidString)"
let defaults = UserDefaults(suiteName: name)!
@@ -200,9 +200,9 @@ import NXModel
let library = GameLibrary(file: output.appendingPathComponent("unused-library.json"))
// the bottom right shows the Home hint and the Console mode button while a controller is connected (this Mac's, when one is)
for width: CGFloat in [1280, 900] {
- try shot(AnyView(LauncherView(stores: LauncherStores(), library: library, performStartupChecks: false, enterConsole: {})), "desktop-bar-\(Int(width))", width, 720)
+ try shot(AnyView(LauncherView(stores: LauncherStores(defaults: testDefaults), library: library, performStartupChecks: false, enterConsole: {})), "desktop-bar-\(Int(width))", width, 720)
}
- try shot(AnyView(LauncherView(stores: LauncherStores(), library: library, performStartupChecks: false, enterConsole: {}, qaPrompt: true)), "prompt-windowed", 1000, 720)
+ try shot(AnyView(LauncherView(stores: LauncherStores(defaults: testDefaults), library: library, performStartupChecks: false, enterConsole: {}, qaPrompt: true)), "prompt-windowed", 1000, 720)
for lang in [Lang.en, .zh] {
try shot(AnyView(ConsoleConnectionPrompt(lang: lang, enterConsole: {}, dismissPrompt: {}).environmentObject(PadFocus()).preferredColorScheme(.dark)), "prompt-\(lang.code)", 900, 500)
}
diff --git a/frontend/Tests/NX2AppleTests/ConsolePointerTests.swift b/frontend/Tests/NX2AppleTests/ConsolePointerTests.swift
index 934bdc04..ba4b78c8 100644
--- a/frontend/Tests/NX2AppleTests/ConsolePointerTests.swift
+++ b/frontend/Tests/NX2AppleTests/ConsolePointerTests.swift
@@ -4,7 +4,7 @@ import XCTest
@testable import NXLauncher
/// When the pointer hides in console mode. Nothing here touches NSCursor.
-final class ConsolePointerTests: XCTestCase {
+final class ConsolePointerTests: IsolatedDefaultsTestCase {
private let here = CGPoint(x: 10, y: 10)
func testHidesAfterAboutOneAndAHalfIdleSecondsAndShowsOnMovement() {
diff --git a/frontend/Tests/NX2AppleTests/ConsoleTests.swift b/frontend/Tests/NX2AppleTests/ConsoleTests.swift
index 248b7625..0b1a92e4 100644
--- a/frontend/Tests/NX2AppleTests/ConsoleTests.swift
+++ b/frontend/Tests/NX2AppleTests/ConsoleTests.swift
@@ -6,7 +6,7 @@ import Combine
import NXModel
@testable import NXLauncher
-@MainActor final class ConsoleTests: XCTestCase {
+@MainActor final class ConsoleTests: IsolatedDefaultsTestCase {
/// The games ready on this Mac come first. The rest follow in their own order, each with its status.
func testReadyGamesComeFirst() {
func game(_ id: String, _ status: ConsoleGame.Status) -> ConsoleGame {
@@ -207,7 +207,7 @@ import NXModel
try FileManager.default.createDirectory(at: output, withIntermediateDirectories: true)
for lang in CaptureLanguage.all([.en, .zh]) {
for width: CGFloat in [900, 1280] {
- let modelStores = LauncherStores(); let model = modelStores.build
+ let modelStores = LauncherStores(defaults: testDefaults); let model = modelStores.build
model.lang = lang
let library = GameLibrary(file: output.appendingPathComponent("unused-library.json"))
let driver = MockConsoleDriver(scenario: .controllersMixed, lang: lang, animated: false)
diff --git a/frontend/Tests/NX2AppleTests/ControlPresetsTests.swift b/frontend/Tests/NX2AppleTests/ControlPresetsTests.swift
index 1738a898..54d14903 100644
--- a/frontend/Tests/NX2AppleTests/ControlPresetsTests.swift
+++ b/frontend/Tests/NX2AppleTests/ControlPresetsTests.swift
@@ -5,7 +5,7 @@ import XCTest
/// Issue #70: the controller layouts and the DM_PAD_MAP each passes. Controllers are stand-in product categories; nothing
/// reads a real controller.
-final class ControlPresetsTests: XCTestCase {
+final class ControlPresetsTests: IsolatedDefaultsTestCase {
private var defaults: UserDefaults!
private let suite = "nxnative-control-presets-tests"
diff --git a/frontend/Tests/NX2AppleTests/ControlsTests.swift b/frontend/Tests/NX2AppleTests/ControlsTests.swift
index d7eef343..428d9657 100644
--- a/frontend/Tests/NX2AppleTests/ControlsTests.swift
+++ b/frontend/Tests/NX2AppleTests/ControlsTests.swift
@@ -4,7 +4,7 @@ import XCTest
@testable import NXLauncher
/// The Controls page's layout and the DM_KEYMAP / DM_PAD_MAP it passes (read by dm/host/input_map.h).
-final class ControlsTests: XCTestCase {
+final class ControlsTests: IsolatedDefaultsTestCase {
private var defaults: UserDefaults!
private let suite = "nxnative-controls-tests"
@@ -70,7 +70,7 @@ final class ControlsTests: XCTestCase {
}
}
-final class StageNameTests: XCTestCase {
+final class StageNameTests: IsolatedDefaultsTestCase {
func testTheScriptsStageNamesAreShownInTheLaunchersLanguage() {
let zh = { (k: String) in L10n.string(k, .zh) }, sv = { (k: String) in L10n.string(k, .sv) }
XCTAssertEqual(Stage.localizedName("Mac shaders", zh), "Mac 着色器")
diff --git a/frontend/Tests/NX2AppleTests/DiagnosticsTests.swift b/frontend/Tests/NX2AppleTests/DiagnosticsTests.swift
index 96f79b48..30ec9d36 100644
--- a/frontend/Tests/NX2AppleTests/DiagnosticsTests.swift
+++ b/frontend/Tests/NX2AppleTests/DiagnosticsTests.swift
@@ -4,7 +4,7 @@ import XCTest
@testable import NXLauncher
/// Issue #69: Copy diagnostics. Every input is a stand-in; nothing reads this Mac's checkout, tools or keys.
-final class DiagnosticsTests: XCTestCase {
+final class DiagnosticsTests: IsolatedDefaultsTestCase {
private let home = "/Users/jo"
private func inputs() -> Diagnostics.Inputs {
diff --git a/frontend/Tests/NX2AppleTests/DockProgressTests.swift b/frontend/Tests/NX2AppleTests/DockProgressTests.swift
index 16f458f3..a34be1fe 100644
--- a/frontend/Tests/NX2AppleTests/DockProgressTests.swift
+++ b/frontend/Tests/NX2AppleTests/DockProgressTests.swift
@@ -4,7 +4,7 @@ import XCTest
@testable import NXLauncher
/// The Dock tile's text for a running build (DockProgress): the text is pure, the tile view is built without a Dock.
-final class DockProgressTests: XCTestCase {
+final class DockProgressTests: IsolatedDefaultsTestCase {
func testThePercentTextForAProgressFraction() {
XCTAssertEqual(DockProgress.percentText(0), "0%")
XCTAssertEqual(DockProgress.percentText(0.404), "40%", "rounded, never 40.4%")
diff --git a/frontend/Tests/NX2AppleTests/DropFilesTests.swift b/frontend/Tests/NX2AppleTests/DropFilesTests.swift
index 36e8d46d..db4e9e3b 100644
--- a/frontend/Tests/NX2AppleTests/DropFilesTests.swift
+++ b/frontend/Tests/NX2AppleTests/DropFilesTests.swift
@@ -6,7 +6,7 @@ import NXModel
@testable import NXLauncher
/// Files dropped on the Builds page (issue #68), sorted by the same classification as Choose game folder.
-@MainActor final class DropFilesTests: XCTestCase {
+@MainActor final class DropFilesTests: IsolatedDefaultsTestCase {
private var temporary: URL!
override func setUpWithError() throws {
@@ -26,7 +26,7 @@ import NXModel
}
func testPickedFilesThatDoNotFitTheRowAreNotTaken() throws {
- let mStores = LauncherStores(); let m = mStores.build
+ let mStores = LauncherStores(defaults: testDefaults); let m = mStores.build
let base = try file("01007EF00011E000_v0_420d1c5034ab.nsp")
let update = try file("01007EF00011E800_v1114112_038ff9df0888.nsp")
let dlc1 = try file("01007EF00011F001_v196608_8a46aae731b8.nsp")
@@ -63,7 +63,7 @@ import NXModel
let new = try file("01007EF00011E800_v1114112_038ff9df0888.nsp", in: "reporter")
_ = try file("01007EF00011F001_v196608_8a46aae731b8.nsp", in: "reporter")
_ = try file("01007EF00011F002_v196608_193e5731baf2.nsp", in: "reporter")
- let mStores = LauncherStores(); let m = mStores.build
+ let mStores = LauncherStores(defaults: testDefaults); let m = mStores.build
m.lang = .en
m.scan(folder: folder.path)
XCTAssertEqual(m.updatePath, new)
@@ -72,11 +72,11 @@ import NXModel
XCTAssertTrue(m.slot("update").summary(m.t).contains("the newest of 2"))
XCTAssertFalse(m.slot("update").note.contains(";"))
XCTAssertTrue(m.slot("dlc").summary(m.t).hasPrefix("2 files"))
- XCTAssertTrue(LauncherStores().build.slot("dlc").summary(m.t).contains("several files"))
+ XCTAssertTrue(LauncherStores(defaults: testDefaults).build.slot("dlc").summary(m.t).contains("several files"))
}
func testDroppedFilesJoinWhatIsAlreadyChosen() throws {
- let mStores = LauncherStores(); let m = mStores.build
+ let mStores = LauncherStores(defaults: testDefaults); let m = mStores.build
let base = try file("Game [0100000000010000].nsp", in: "base")
let dlc1 = try file("Game DLC [0100000000011001].nsp", in: "dlc")
m.take(dropped: [base, dlc1])
@@ -96,7 +96,7 @@ import NXModel
m.take(dropped: [try file("cover.jpg")])
XCTAssertEqual(m.basePath, base)
XCTAssertEqual(m.slot("base").problem, "")
- let emptyStores = LauncherStores(); let empty = emptyStores.build
+ let emptyStores = LauncherStores(defaults: testDefaults); let empty = emptyStores.build
empty.take(dropped: [try file("notes.txt")])
XCTAssertEqual(empty.slot("base").problem, "data.noNsp")
}
@@ -107,7 +107,7 @@ import NXModel
let keys = try file("prod.keys", in: "Game")
try file("Game [0100000000010800][v999999].nsp", in: "Game/0100000000010000_build") // the pipeline's own folder is pruned
let folder = temporary.appendingPathComponent("Game").path
- let mStores = LauncherStores(); let m = mStores.build
+ let mStores = LauncherStores(defaults: testDefaults); let m = mStores.build
m.take(dropped: [folder])
XCTAssertEqual(m.gameDir, folder)
XCTAssertEqual(m.basePath, base)
@@ -115,7 +115,7 @@ import NXModel
XCTAssertEqual(m.keysPath, keys)
// a folder with a file beside it: the folder's files and the file, added to what is chosen
- let otherStores = LauncherStores(); let other = otherStores.build
+ let otherStores = LauncherStores(defaults: testDefaults); let other = otherStores.build
let dlc = try file("Game DLC [0100000000011001].nsp", in: "elsewhere")
other.take(dropped: [folder, dlc])
XCTAssertEqual(other.basePath, base)
@@ -130,9 +130,7 @@ import NXModel
let output = URL(fileURLWithPath: directory)
try FileManager.default.createDirectory(at: output, withIntermediateDirectories: true)
NSApplication.shared.setActivationPolicy(.accessory)
- let oldOutput = UserDefaults.standard.object(forKey: "buildOutputDirectory")
- defer { UserDefaults.standard.set(oldOutput, forKey: "buildOutputDirectory") }
- let modelStores = LauncherStores(); let model = modelStores.build
+ let modelStores = LauncherStores(defaults: testDefaults); let model = modelStores.build
model.lang = CaptureLanguage.current(.en)
model.outDir = temporary.path
MainActor.assumeIsolated { modelStores.dependencies.checked = true }
diff --git a/frontend/Tests/NX2AppleTests/EngineLayoutTests.swift b/frontend/Tests/NX2AppleTests/EngineLayoutTests.swift
index c32f1a1f..0117587c 100644
--- a/frontend/Tests/NX2AppleTests/EngineLayoutTests.swift
+++ b/frontend/Tests/NX2AppleTests/EngineLayoutTests.swift
@@ -7,7 +7,7 @@ import NXModel
/// #214: which engine the launcher builds from. A checkout of this repository builds from its engine/ (synced first when it is stale or
/// missing, there is no committed tree), a folder that is an engine tree itself (an installed release's engine) from that folder.
/// The stamp key matches tools/engine.py's.
-@MainActor final class EngineLayoutTests: XCTestCase {
+@MainActor final class EngineLayoutTests: IsolatedDefaultsTestCase {
private var root: URL!
private var repo: String { root.path }
private let pin = String(repeating: "a", count: 40)
@@ -111,7 +111,7 @@ import NXModel
private func model(engineScript script: String) throws -> LauncherStores {
try newLayout()
try touch("tools/engine.py", script)
- let mStores = LauncherStores()
+ let mStores = LauncherStores(defaults: testDefaults)
mStores.repo.path = repo
mStores.dependencies.pythonPath = "/usr/bin/python3"
return mStores
diff --git a/frontend/Tests/NX2AppleTests/EngineManifestTests.swift b/frontend/Tests/NX2AppleTests/EngineManifestTests.swift
index 7d56cd16..c3ceaf84 100644
--- a/frontend/Tests/NX2AppleTests/EngineManifestTests.swift
+++ b/frontend/Tests/NX2AppleTests/EngineManifestTests.swift
@@ -6,7 +6,7 @@ import XCTest
/// The release manifest and the engine store (EngineManifest.swift). Everything is driven from bytes and
/// temporary folders here: no network, no release.
-final class EngineManifestTests: XCTestCase {
+final class EngineManifestTests: IsolatedDefaultsTestCase {
private lazy var digest = String(repeating: "a", count: 64)
private let pin = String(repeating: "e", count: 40)
private var engineID: String { pin + "-0123456789ab" }
diff --git a/frontend/Tests/NX2AppleTests/EngineUpdateModelTests.swift b/frontend/Tests/NX2AppleTests/EngineUpdateModelTests.swift
index 7a9fea47..43de5d92 100644
--- a/frontend/Tests/NX2AppleTests/EngineUpdateModelTests.swift
+++ b/frontend/Tests/NX2AppleTests/EngineUpdateModelTests.swift
@@ -6,12 +6,12 @@ import NXModel
/// The engine in the model: that the release app never runs git, and the engine strings. What the app does with an update check's
/// outcome is `EngineSyncStore`, tested in NXModelTests. Nothing here touches the network or the store.
-@MainActor final class EngineUpdateModelTests: XCTestCase {
+@MainActor final class EngineUpdateModelTests: IsolatedDefaultsTestCase {
private let root = URL(fileURLWithPath: "/nonexistent-engine-bundle")
/// A launcher built from the repository keeps git, the release app never touches it.
@MainActor func testTheReleaseAppNeverRunsGit() {
- let mStores = LauncherStores(); let m = mStores.build
+ let mStores = LauncherStores(defaults: testDefaults); let m = mStores.build
mStores.engineSync.bundle = root
mStores.repo.clone()
mStores.repo.pull()
diff --git a/frontend/Tests/NX2AppleTests/EngineUpdaterTests.swift b/frontend/Tests/NX2AppleTests/EngineUpdaterTests.swift
index ba43a136..a2a58c35 100644
--- a/frontend/Tests/NX2AppleTests/EngineUpdaterTests.swift
+++ b/frontend/Tests/NX2AppleTests/EngineUpdaterTests.swift
@@ -6,7 +6,7 @@ import XCTest
/// Channels, asset URLs, the installer and the update check (EngineUpdater.swift in NXCore, EngineSyncStore in NXModel). The
/// archive is built here with `ditto`, so the unpack path is real. Nothing touches the network.
-final class EngineUpdaterTests: XCTestCase {
+final class EngineUpdaterTests: IsolatedDefaultsTestCase {
private var root: URL!
override func setUpWithError() throws {
diff --git a/frontend/Tests/NX2AppleTests/FrameTimesTests.swift b/frontend/Tests/NX2AppleTests/FrameTimesTests.swift
index fc4ebf29..a73254ac 100644
--- a/frontend/Tests/NX2AppleTests/FrameTimesTests.swift
+++ b/frontend/Tests/NX2AppleTests/FrameTimesTests.swift
@@ -6,7 +6,7 @@ import NXModel
@testable import NXLauncher
/// Frame-time recordings (DM_NVN_TSV): reading the host's timing rows and summing them up as scripts/bench.py does.
-@MainActor final class FrameTimesTests: XCTestCase {
+@MainActor final class FrameTimesTests: IsolatedDefaultsTestCase {
/// Rows as the host writes them (dm/gfx/nvn/hle_nvn.c): frame, @metric, value; call-count rows and junk in between.
private let tsv = """
1\t@t_s\t0.000
@@ -177,7 +177,7 @@ import NXModel
let saved = UserDefaults.standard.object(forKey: key)
defer { UserDefaults.standard.set(saved, forKey: key) }
FrameTimes.setEnabled(true, titleID: titleID)
- let modelStores = LauncherStores(); let model = modelStores.build
+ let modelStores = LauncherStores(defaults: testDefaults); let model = modelStores.build
model.lang = .en
let host = NSHostingView(rootView: LaunchOptionsView(m: model, library: library, gameID: library.games[0].id).environmentObject(PadFocus()).environmentObject(modelStores.localizer))
let window = OffscreenWindow(size: NSSize(width: 900, height: 1300), styleMask: [.titled, .closable, .resizable])
diff --git a/frontend/Tests/NX2AppleTests/FreeSpaceTests.swift b/frontend/Tests/NX2AppleTests/FreeSpaceTests.swift
index 0fd0840b..4a1d36ec 100644
--- a/frontend/Tests/NX2AppleTests/FreeSpaceTests.swift
+++ b/frontend/Tests/NX2AppleTests/FreeSpaceTests.swift
@@ -5,7 +5,7 @@ import XCTest
/// Free space (#67): a synthetic <title ID>_build folder in a temporary directory, laid out as build_ipa_from_nsp.py
/// leaves it, with the finished app, the IPA and the game data archive beside it.
-final class FreeSpaceTests: XCTestCase {
+final class FreeSpaceTests: IsolatedDefaultsTestCase {
private var temporary: URL!
private let titleID = "0100535012974000"
diff --git a/frontend/Tests/NX2AppleTests/FrenchLocalizationTests.swift b/frontend/Tests/NX2AppleTests/FrenchLocalizationTests.swift
index 5b1d1ee6..2c9898d2 100644
--- a/frontend/Tests/NX2AppleTests/FrenchLocalizationTests.swift
+++ b/frontend/Tests/NX2AppleTests/FrenchLocalizationTests.swift
@@ -5,7 +5,7 @@ import XCTest
/// 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 {
+final class FrenchLocalizationTests: IsolatedDefaultsTestCase {
/// Keys whose French text is the English one on purpose: names, units, button letters, codes.
static let sameAsEnglish: Set<String> = [
"onboarding.platform.mac", "onboarding.platform.iphone", "onboarding.background.python",
diff --git a/frontend/Tests/NX2AppleTests/GameCloudSavesTests.swift b/frontend/Tests/NX2AppleTests/GameCloudSavesTests.swift
index 6d270e05..69fdb867 100644
--- a/frontend/Tests/NX2AppleTests/GameCloudSavesTests.swift
+++ b/frontend/Tests/NX2AppleTests/GameCloudSavesTests.swift
@@ -7,7 +7,7 @@ import XCTest
/// #499: the Mac launcher shows and sets a game's cloud saves folder where dm/mac/launcher.c reads it, and reads the last
/// session's sync from the game's log.
-final class GameCloudSavesTests: XCTestCase {
+final class GameCloudSavesTests: IsolatedDefaultsTestCase {
private var root: URL!
private let titleID = "0100535012974000"
private var preference: String?
@@ -104,7 +104,7 @@ final class GameCloudSavesTests: XCTestCase {
let output = URL(fileURLWithPath: directory)
try FileManager.default.createDirectory(at: output, withIntermediateDirectories: true)
NSApplication.shared.setActivationPolicy(.accessory)
- let localizer = LauncherStores().localizer
+ let localizer = LauncherStores(defaults: testDefaults).localizer
localizer.lang = CaptureLanguage.current(.en)
let game = LibraryGame(titleID: titleID, name: "Hades")
let drive = "/Users/jo/Library/Mobile Documents/com~apple~CloudDocs"
diff --git a/frontend/Tests/NX2AppleTests/GameDeletionTests.swift b/frontend/Tests/NX2AppleTests/GameDeletionTests.swift
index a42b7b5a..f2bd34ba 100644
--- a/frontend/Tests/NX2AppleTests/GameDeletionTests.swift
+++ b/frontend/Tests/NX2AppleTests/GameDeletionTests.swift
@@ -9,7 +9,7 @@ import XCTest
/// #559: Delete game on the Mac. What goes (the Mac app, the IPA, the game data for the shared app, the game's place in the
/// shared app, the build folder, the log) and what stays (the files it was built from, other games, and the saves unless the
/// player chose them too).
-final class GameDeletionTests: XCTestCase {
+final class GameDeletionTests: IsolatedDefaultsTestCase {
private var root: URL!
private let titleID = "0100535012974000", other = "0100000000010000"
private var path: String { root.path }
@@ -125,7 +125,7 @@ final class GameDeletionTests: XCTestCase {
let output = URL(fileURLWithPath: directory)
try FileManager.default.createDirectory(at: output, withIntermediateDirectories: true)
NSApplication.shared.setActivationPolicy(.accessory)
- let localizer = LauncherStores().localizer
+ let localizer = LauncherStores(defaults: testDefaults).localizer
localizer.lang = CaptureLanguage.current(.en)
let game = LibraryGame(titleID: titleID, name: "Hades")
let out = "/Volumes/Games/Hades"
diff --git a/frontend/Tests/NX2AppleTests/GameLogTests.swift b/frontend/Tests/NX2AppleTests/GameLogTests.swift
index 81eebc09..53603fac 100644
--- a/frontend/Tests/NX2AppleTests/GameLogTests.swift
+++ b/frontend/Tests/NX2AppleTests/GameLogTests.swift
@@ -5,7 +5,7 @@ import XCTest
/// Show game log and the log in Copy diagnostics: where dm/mac/launcher.c puts a game's log, which file is the latest, and
/// that only the end of a large log is read.
-final class GameLogTests: XCTestCase {
+final class GameLogTests: IsolatedDefaultsTestCase {
private var temporary: URL!
private let id = "0100535012974000"
diff --git a/frontend/Tests/NX2AppleTests/GameStartScreenTests.swift b/frontend/Tests/NX2AppleTests/GameStartScreenTests.swift
index 193c1610..5c08c6f1 100644
--- a/frontend/Tests/NX2AppleTests/GameStartScreenTests.swift
+++ b/frontend/Tests/NX2AppleTests/GameStartScreenTests.swift
@@ -5,7 +5,7 @@ import XCTest
@testable import NXLauncher
/// DM_SCREEN in the launch environment (front_mac.m opens the game's window on that NSScreenNumber).
-@MainActor final class GameStartScreenTests: XCTestCase {
+@MainActor final class GameStartScreenTests: IsolatedDefaultsTestCase {
private func number(_ screen: NSScreen) -> NSNumber? { screen.deviceDescription[NSDeviceDescriptionKey("NSScreenNumber")] as? NSNumber }
func testDisplayIDIsTheScreenNumber() throws {
diff --git a/frontend/Tests/NX2AppleTests/GermanLocalizationTests.swift b/frontend/Tests/NX2AppleTests/GermanLocalizationTests.swift
index 0e5460dd..34610e5b 100644
--- a/frontend/Tests/NX2AppleTests/GermanLocalizationTests.swift
+++ b/frontend/Tests/NX2AppleTests/GermanLocalizationTests.swift
@@ -5,7 +5,7 @@ import XCTest
/// 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 {
+final class GermanLocalizationTests: IsolatedDefaultsTestCase {
/// Keys whose German text is the English text on purpose: names, units and button letters.
private let sameAsEnglish: Set<String> = [
"onboarding.platform.mac", "onboarding.platform.iphone", "onboarding.setup.metal",
diff --git a/frontend/Tests/NX2AppleTests/InputStagingTests.swift b/frontend/Tests/NX2AppleTests/InputStagingTests.swift
index 932d762b..fb5fc8c2 100644
--- a/frontend/Tests/NX2AppleTests/InputStagingTests.swift
+++ b/frontend/Tests/NX2AppleTests/InputStagingTests.swift
@@ -5,7 +5,7 @@ import XCTest
/// The staging folder for files picked from several folders (#132): the same selection stages to the same
/// paths with the same dates, and the folder holds exactly the current selection.
-final class InputStagingTests: XCTestCase {
+final class InputStagingTests: IsolatedDefaultsTestCase {
private var temporary: URL!
private var a: URL { temporary.appendingPathComponent("one") }
private var b: URL { temporary.appendingPathComponent("two") }
diff --git a/frontend/Tests/NX2AppleTests/IsolatedDefaultsTestCase.swift b/frontend/Tests/NX2AppleTests/IsolatedDefaultsTestCase.swift
new file mode 100644
index 00000000..2d882dfd
--- /dev/null
+++ b/frontend/Tests/NX2AppleTests/IsolatedDefaultsTestCase.swift
@@ -0,0 +1,72 @@
+import XCTest
+
+/// The base of every test in this target. A test process shares one UserDefaults domain (`com.apple.dt.xctest.tool`), and the domain
+/// outlives the run: a key one test wrote, or a killed run left behind, was read by the next test and the next run (a stale
+/// `exportIPA` or a `repoPath` in a deleted folder failed the shell install tests).
+///
+/// - `testDefaults` is a suite of its own for the test, removed after it. A test hands it to `LauncherStores(defaults:)` and to every
+/// store or helper that takes a `defaults`, so nothing reads or writes the shared domain.
+/// - The shared domain is emptied once per process, so a leftover of an earlier run is gone before the first test.
+/// - After each test the shared domain must be as it was before: a test that leaves a key there fails, and the key is put back.
+class IsolatedDefaultsTestCase: XCTestCase {
+ /// The suite of this test, created on first use.
+ var testDefaults: UserDefaults {
+ if let suite = isolatedSuite { return suite.defaults }
+ let name = "nx2apple-test-" + UUID().uuidString
+ let defaults = UserDefaults(suiteName: name)!
+ isolatedSuite = (name, defaults)
+ return defaults
+ }
+ private var isolatedSuite: (name: String, defaults: UserDefaults)?
+
+ /// The domain the process reads and writes through `UserDefaults.standard`.
+ static var sharedDomain: String { Bundle.main.bundleIdentifier ?? ProcessInfo.processInfo.processName }
+
+ private static let sharedDomainCleared: Void = {
+ UserDefaults.standard.removePersistentDomain(forName: sharedDomain)
+ }()
+
+ static func sharedKeys() -> [String: Any] { UserDefaults.standard.persistentDomain(forName: sharedDomain) ?? [:] }
+
+ override func invokeTest() {
+ _ = Self.sharedDomainCleared
+ let before = Self.sharedKeys()
+ isolatedSuite = nil
+ super.invokeTest()
+ if let suite = isolatedSuite {
+ UserDefaults().removePersistentDomain(forName: suite.name)
+ try? FileManager.default.removeItem(atPath: NSHomeDirectory() + "/Library/Preferences/\(suite.name).plist") // no file per test
+ }
+ isolatedSuite = nil
+ let after = Self.sharedKeys()
+ let changed = Set(before.keys).union(after.keys).filter { !Self.same(before[$0], after[$0]) }.sorted()
+ if !changed.isEmpty {
+ XCTFail("\(name) left \(changed.joined(separator: ", ")) in the shared test defaults (\(Self.sharedDomain)). "
+ + "Give the store or helper `testDefaults`, or restore the key.")
+ for key in changed { UserDefaults.standard.set(before[key], forKey: key) } // the next test starts clean
+ }
+ }
+
+ private static func same(_ a: Any?, _ b: Any?) -> Bool {
+ switch (a, b) {
+ case (nil, nil): return true
+ case let (a?, b?): return (a as AnyObject).isEqual(b)
+ default: return false
+ }
+ }
+}
+
+/// The guard's own tests: the suite is separate from the shared domain, and the shared domain starts empty.
+final class SharedDefaultsGuardTests: IsolatedDefaultsTestCase {
+ func testTheTestSuiteIsNotTheSharedDomain() {
+ let before = Self.sharedKeys()
+ testDefaults.set("somewhere", forKey: "repoPath")
+ testDefaults.set(true, forKey: "exportIPA")
+ XCTAssertEqual(testDefaults.string(forKey: "repoPath"), "somewhere")
+ XCTAssertEqual(NSDictionary(dictionary: Self.sharedKeys()), NSDictionary(dictionary: before))
+ }
+
+ func testTheSharedDomainIsEmptyBeforeTheTest() {
+ XCTAssertTrue(Self.sharedKeys().isEmpty, "left over: \(Self.sharedKeys().keys.sorted())")
+ }
+}
diff --git a/frontend/Tests/NX2AppleTests/KeyCheckTests.swift b/frontend/Tests/NX2AppleTests/KeyCheckTests.swift
index 2eacc231..7bc73fd9 100644
--- a/frontend/Tests/NX2AppleTests/KeyCheckTests.swift
+++ b/frontend/Tests/NX2AppleTests/KeyCheckTests.swift
@@ -6,7 +6,7 @@ import NXModel
@testable import NXLauncher
/// prod.keys against the game files before a build (issue #63). Every key here is made up for the test.
-@MainActor final class KeyCheckTests: XCTestCase {
+@MainActor final class KeyCheckTests: IsolatedDefaultsTestCase {
private var temporary: URL!
private let headerKey = (0..<32).map { UInt8(0xA0 ^ $0) }
@@ -169,9 +169,7 @@ import NXModel
let output = URL(fileURLWithPath: directory)
try FileManager.default.createDirectory(at: output, withIntermediateDirectories: true)
NSApplication.shared.setActivationPolicy(.accessory)
- let oldOutput = UserDefaults.standard.object(forKey: "buildOutputDirectory")
- defer { UserDefaults.standard.set(oldOutput, forKey: "buildOutputDirectory") }
- let modelStores = LauncherStores(); let model = modelStores.build
+ let modelStores = LauncherStores(defaults: testDefaults); let model = modelStores.build
model.lang = CaptureLanguage.current(.en)
model.outDir = temporary.path
MainActor.assumeIsolated { modelStores.dependencies.checked = true }
diff --git a/frontend/Tests/NX2AppleTests/LanguageListTests.swift b/frontend/Tests/NX2AppleTests/LanguageListTests.swift
index 9e569dcd..72f16bd1 100644
--- a/frontend/Tests/NX2AppleTests/LanguageListTests.swift
+++ b/frontend/Tests/NX2AppleTests/LanguageListTests.swift
@@ -10,7 +10,7 @@ extension Lang {
}
/// The language list comes from the files (LNPANDY/NX2Apple#388, step 2): the picker, the device detection and the names.
-final class LanguageListTests: XCTestCase {
+final class LanguageListTests: IsolatedDefaultsTestCase {
private var temporary: URL!
override func setUpWithError() throws {
diff --git a/frontend/Tests/NX2AppleTests/LaunchOptionsTests.swift b/frontend/Tests/NX2AppleTests/LaunchOptionsTests.swift
index 904528c3..fa49e107 100644
--- a/frontend/Tests/NX2AppleTests/LaunchOptionsTests.swift
+++ b/frontend/Tests/NX2AppleTests/LaunchOptionsTests.swift
@@ -4,7 +4,7 @@ import XCTest
@testable import NXLauncher
/// Launch options beyond the app's own list: Display mode, the basic / advanced split, the render scale in pixels, and mods.
-final class LaunchOptionsTests: XCTestCase {
+final class LaunchOptionsTests: IsolatedDefaultsTestCase {
private var temporary: URL!
override func setUpWithError() throws {
diff --git a/frontend/Tests/NX2AppleTests/LauncherControlWidthTests.swift b/frontend/Tests/NX2AppleTests/LauncherControlWidthTests.swift
index 62ebeb3f..65fe5099 100644
--- a/frontend/Tests/NX2AppleTests/LauncherControlWidthTests.swift
+++ b/frontend/Tests/NX2AppleTests/LauncherControlWidthTests.swift
@@ -10,7 +10,7 @@ import NXModel
/// line. Nothing here lists labels: the real Settings and Builds pages are drawn in every language the launcher has, and each
/// control reports what it measured (LauncherControlSample), so a new button, a new string or a new language is checked as soon as
/// a page shows it.
-@MainActor final class LauncherControlWidthTests: XCTestCase {
+@MainActor final class LauncherControlWidthTests: IsolatedDefaultsTestCase {
private func width(_ text: String, size: CGFloat = 13) throws -> CGFloat {
let font = try XCTUnwrap(Typography.manropeFont(size: size, weight: .semibold))
let line = CTLineCreateWithAttributedString(NSAttributedString(string: text, attributes: [.font: font]))
@@ -177,7 +177,7 @@ import NXModel
let directory = FileManager.default.temporaryDirectory.appendingPathComponent("control-width-\(UUID().uuidString)")
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
defer { try? FileManager.default.removeItem(at: directory) }
- let modelStores = LauncherStores(); let model = modelStores.build
+ let modelStores = LauncherStores(defaults: testDefaults); let model = modelStores.build
let library = GameLibrary(file: directory.appendingPathComponent("library.json"))
try scenario.set(modelStores, library, directory)
model.lang = lang
@@ -200,8 +200,6 @@ import NXModel
/// LauncherControl.height high, and its label fits on one line.
@MainActor func testEveryRowControlOnTheRealPagesFitsInEveryLanguage() throws {
let keys = ["repoPath", "depsExpanded", "buildTarget", "installDevice", "signingTeam", "buildOutputDirectory", "autoUpdateRepo", "exportIPA", "sendWhere"]
- let saved = keys.map { ($0, UserDefaults.standard.object(forKey: $0)) }
- defer { for (key, value) in saved { UserDefaults.standard.set(value, forKey: key) } }
for scenario in scenarios {
for lang in Lang.all {
let samples = try measure(scenario, lang)
@@ -290,7 +288,7 @@ import NXModel
let file = directory.appendingPathComponent("library.json")
try JSONEncoder().encode(Snapshot(games: [game], folder: directory.path)).write(to: file)
let library = GameLibrary(file: file)
- let modelStores = LauncherStores(); let model = modelStores.build
+ let modelStores = LauncherStores(defaults: testDefaults); let model = modelStores.build
for lang in Lang.all {
model.lang = lang
let samples = Samples()
diff --git a/frontend/Tests/NX2AppleTests/LauncherDropdownTests.swift b/frontend/Tests/NX2AppleTests/LauncherDropdownTests.swift
index 2290eee7..91f63f79 100644
--- a/frontend/Tests/NX2AppleTests/LauncherDropdownTests.swift
+++ b/frontend/Tests/NX2AppleTests/LauncherDropdownTests.swift
@@ -4,7 +4,7 @@ import XCTest
@testable import NXCore
@testable import NXLauncher
-final class LauncherDropdownTests: XCTestCase {
+final class LauncherDropdownTests: IsolatedDefaultsTestCase {
private let window = CGSize(width: 1000, height: 700)
func testListOpensBelowTheButton() {
diff --git a/frontend/Tests/NX2AppleTests/LauncherHeroActionTests.swift b/frontend/Tests/NX2AppleTests/LauncherHeroActionTests.swift
index 726fa29d..5b8c83a8 100644
--- a/frontend/Tests/NX2AppleTests/LauncherHeroActionTests.swift
+++ b/frontend/Tests/NX2AppleTests/LauncherHeroActionTests.swift
@@ -6,7 +6,7 @@ import XCTest
@testable import NXLauncher
/// The hero's cream button has one size (LauncherHeroAction) whatever the game's state and the language.
-final class LauncherHeroActionTests: XCTestCase {
+final class LauncherHeroActionTests: IsolatedDefaultsTestCase {
private let languages: [Lang] = [.zh, .en, .sv, .de]
private func width(_ text: String) throws -> CGFloat {
diff --git a/frontend/Tests/NX2AppleTests/LauncherPerformanceTests.swift b/frontend/Tests/NX2AppleTests/LauncherPerformanceTests.swift
index 4ef7f835..7a8d27ca 100644
--- a/frontend/Tests/NX2AppleTests/LauncherPerformanceTests.swift
+++ b/frontend/Tests/NX2AppleTests/LauncherPerformanceTests.swift
@@ -14,7 +14,7 @@ import NXModel
/// Info.plist reads and frame time recordings parsed. The counts do not depend on the machine, so they catch work that grows
/// with the library long before a stopwatch would. The second guard is the time the main thread is busy, the median of
/// several rounds, with budgets far above what main needs on CI. See "Launcher performance test" in frontend/README.md.
-@MainActor final class LauncherPerformanceTests: XCTestCase {
+@MainActor final class LauncherPerformanceTests: IsolatedDefaultsTestCase {
private var temporary: URL!
override func setUpWithError() throws {
@@ -132,9 +132,7 @@ import NXModel
#else
let world = try makeWorld(owned: 30, catalogue: 150)
NSApplication.shared.setActivationPolicy(.accessory)
- let saved = ["repoPath", "buildOutputDirectory"].map { ($0, UserDefaults.standard.object(forKey: $0)) }
- defer { for (key, value) in saved { UserDefaults.standard.set(value, forKey: key) } }
- let modelStores = LauncherStores(); let model = modelStores.build
+ let modelStores = LauncherStores(defaults: testDefaults); let model = modelStores.build
modelStores.repo.path = world.repo.path
model.lang = .en
let library = GameLibrary(file: world.libraryFile)
diff --git a/frontend/Tests/NX2AppleTests/LibraryTests.swift b/frontend/Tests/NX2AppleTests/LibraryTests.swift
index f925397e..798478c0 100644
--- a/frontend/Tests/NX2AppleTests/LibraryTests.swift
+++ b/frontend/Tests/NX2AppleTests/LibraryTests.swift
@@ -6,7 +6,7 @@ import Combine
import NXModel
@testable import NXLauncher
-@MainActor final class LibraryTests: XCTestCase {
+@MainActor final class LibraryTests: IsolatedDefaultsTestCase {
private var temporary: URL!
private let titleID = "0100535012974000"
@@ -287,9 +287,7 @@ import NXModel
/// Stop ends the build and leaves no stage behind (a spinner and a percentage of a build that no longer runs).
@MainActor func testStoppedBuildResetsItsProgress() throws {
guard FileManager.default.isExecutableFile(atPath: "/usr/bin/python3") else { throw XCTSkip("System Python is required for the process fixture") }
- let saved = ["repoPath", "buildTarget", "buildOutputDirectory"].map { ($0, UserDefaults.standard.object(forKey: $0)) }
- defer { for (key, value) in saved { UserDefaults.standard.set(value, forKey: key) } }
- let modelStores = LauncherStores(); let model = modelStores.build
+ let modelStores = LauncherStores(defaults: testDefaults); let model = modelStores.build
modelStores.repo.path = temporary.path
model.target = "mac-app"
model.outDir = temporary.path
@@ -387,7 +385,7 @@ import NXModel
/// An action on the installed app names what is missing instead of doing nothing, and a failed reinstall is a note on
/// the installed app, not a failed build (the app is still on the device).
@MainActor func testReinstallAndSaveReportAMissingSignedApp() throws {
- let modelStores = LauncherStores(xcrun: "/usr/bin/true"); let model = modelStores.build
+ let modelStores = LauncherStores(xcrun: "/usr/bin/true", defaults: testDefaults); let model = modelStores.build
model.installedOn = "00008150-AAAA"
model.installedAppPath = temporary.path + "/gone/DmShell.app"
var reported = expectation(description: "Reinstall says what is missing")
@@ -410,7 +408,7 @@ import NXModel
let info: [String: Any] = ["CFBundleDisplayName": "Zelda: Echoes/of Wisdom"]
try PropertyListSerialization.data(fromPropertyList: info, format: .xml, options: 0)
.write(to: app.appendingPathComponent("Info.plist"))
- let modelStores = LauncherStores(); let model = modelStores.build
+ let modelStores = LauncherStores(defaults: testDefaults); let model = modelStores.build
model.installedAppPath = app.path
XCTAssertEqual(model.defaultIPAName(), "Zelda_ Echoes_of Wisdom.ipa")
}
@@ -426,9 +424,7 @@ import NXModel
/// An app from before the shared app has no project to sign again: the note says to build the game again. Without a team
/// the note asks for one first.
@MainActor func testResignOfAnOlderAppAsksForANewBuild() throws {
- let savedTeam = UserDefaults.standard.string(forKey: "signingTeam")
- defer { UserDefaults.standard.set(savedTeam, forKey: "signingTeam") }
- let modelStores = LauncherStores(); let model = modelStores.build
+ let modelStores = LauncherStores(defaults: testDefaults); let model = modelStores.build
let older = temporary.appendingPathComponent("0100_build/xcode-derived-data/Build/Products/Release-iphoneos/DmIOS.app").path
modelStores.deviceStore.signingTeam = "TEAM123456"
var reported = expectation(description: "Older app reported")
@@ -445,9 +441,7 @@ import NXModel
/// The shared app's project is gone (the shell folder was removed): the note names it.
@MainActor func testResignReportsAMissingSharedProject() throws {
- let savedTeam = UserDefaults.standard.string(forKey: "signingTeam")
- defer { UserDefaults.standard.set(savedTeam, forKey: "signingTeam") }
- let modelStores = LauncherStores(); let model = modelStores.build
+ let modelStores = LauncherStores(defaults: testDefaults); let model = modelStores.build
modelStores.deviceStore.signingTeam = "TEAM123456"
let shared = temporary.appendingPathComponent("shell/derived-data/Build/Products/Release-iphoneos/DmShell.app")
let reported = expectation(description: "Missing project reported")
@@ -568,9 +562,7 @@ import NXModel
guard FileManager.default.isExecutableFile(atPath: "/usr/bin/python3") else { throw XCTSkip("System Python is required for the process fixture") }
let app = NSApplication.shared
app.setActivationPolicy(.accessory)
- let saved = ["repoPath", "buildTarget", "buildOutputDirectory"].map { ($0, UserDefaults.standard.object(forKey: $0)) }
- defer { for (key, value) in saved { UserDefaults.standard.set(value, forKey: key) } }
- let modelStores = LauncherStores(); let model = modelStores.build
+ let modelStores = LauncherStores(defaults: testDefaults); let model = modelStores.build
model.lang = .en // the script's stage name as English shows it, whatever the Mac's language
modelStores.repo.path = temporary.path
model.target = "mac-app"
@@ -653,15 +645,13 @@ import NXModel
let output = URL(fileURLWithPath: directory)
try FileManager.default.createDirectory(at: output, withIntermediateDirectories: true)
NSApplication.shared.setActivationPolicy(.accessory)
- let saved = ["repoPath", "buildTarget", "buildOutputDirectory"].map { ($0, UserDefaults.standard.object(forKey: $0)) }
- defer { for (key, value) in saved { UserDefaults.standard.set(value, forKey: key) } }
let real = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0].appendingPathComponent("NS Port Builder/library.json")
let copy = temporary.appendingPathComponent("library.json")
// The games, without the user's folders: names and title IDs only, and BotW as a finished Mac build (a fixture app)
let real_ = GameLibrary(file: real)
let library = GameLibrary(file: copy)
let botw = "01007EF00011E000", totk = "0100F2C0115B6000"
- let modelStores = LauncherStores(); let model = modelStores.build
+ let modelStores = LauncherStores(defaults: testDefaults); let model = modelStores.build
modelStores.repo.path = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent().path
model.lang = .en
MainActor.assumeIsolated { modelStores.dependencies.checked = true }
@@ -760,14 +750,7 @@ import NXModel
let app = NSApplication.shared
app.setActivationPolicy(.accessory)
let repo = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent().path
- let modelStores = LauncherStores(); let model = modelStores.build
- // Restore any preferences changed while preparing isolated preview data.
- let oldRepo = UserDefaults.standard.object(forKey: "repoPath")
- let oldOutput = UserDefaults.standard.object(forKey: "buildOutputDirectory")
- defer {
- UserDefaults.standard.set(oldRepo, forKey: "repoPath")
- UserDefaults.standard.set(oldOutput, forKey: "buildOutputDirectory")
- }
+ let modelStores = LauncherStores(defaults: testDefaults); let model = modelStores.build
modelStores.repo.path = repo
model.lang = CaptureLanguage.current(.en)
model.outDir = temporary.path
diff --git a/frontend/Tests/NX2AppleTests/LiveOnboardingDriverTests.swift b/frontend/Tests/NX2AppleTests/LiveOnboardingDriverTests.swift
index 99cd1cb1..4c698087 100644
--- a/frontend/Tests/NX2AppleTests/LiveOnboardingDriverTests.swift
+++ b/frontend/Tests/NX2AppleTests/LiveOnboardingDriverTests.swift
@@ -5,7 +5,7 @@ import NXModel
@testable import NXLauncher
/// The real driver's logic over fakes: no xcodebuild, sudo, App Store, network or installs run here.
-@MainActor final class LiveOnboardingDriverTests: XCTestCase {
+@MainActor final class LiveOnboardingDriverTests: IsolatedDefaultsTestCase {
final class Fake {
var probe = XcodeProbe(appPath: "/Applications/Xcode.app", selectedIsXcode: true, licenseAccepted: true, firstLaunchDone: true)
var admin: AdminResult = .ok
@@ -30,8 +30,6 @@ import NXModel
override func setUp() {
OnboardingDefaults.sessionPlatform = nil
- let target = UserDefaults.standard.object(forKey: "buildTarget") // choosePlatform sets the Builds page's target
- addTeardownBlock { UserDefaults.standard.set(target, forKey: "buildTarget") }
let suite = "onboarding.tests." + UUID().uuidString
defaults = UserDefaults(suiteName: suite)
addTeardownBlock { UserDefaults().removePersistentDomain(forName: suite) }
@@ -43,7 +41,7 @@ import NXModel
func make(_ fake: Fake, deps: [Dep], step: OnboardingStep? = nil, platform: OnboardingPlatform? = nil) -> (LiveOnboardingDriver, BuildStore) {
if let platform { defaults.set(platform.rawValue, forKey: OnboardingDefaults.platform) }
if let step { defaults.set(step.rawValue, forKey: OnboardingDefaults.step); defaults.set(true, forKey: OnboardingDefaults.inProgress) }
- let modelStores = LauncherStores(); let model = modelStores.build
+ let modelStores = LauncherStores(defaults: testDefaults); let model = modelStores.build
modelStores.dependencies.deps = deps; modelStores.dependencies.checked = true
var env = OnboardingEnvironment()
env.defaults = defaults
diff --git a/frontend/Tests/NX2AppleTests/LocalizerTests.swift b/frontend/Tests/NX2AppleTests/LocalizerTests.swift
index 1467893f..c4f12f66 100644
--- a/frontend/Tests/NX2AppleTests/LocalizerTests.swift
+++ b/frontend/Tests/NX2AppleTests/LocalizerTests.swift
@@ -5,7 +5,7 @@ import XCTest
/// LNPANDY/NX2Apple#387, step 2: the language and the strings live in `Localizer`, which needs no SwiftUI. The choice is stored under the
/// UserDefaults key `appLanguage`, as before, so the tests put the player's own value back.
-@MainActor final class LocalizerTests: XCTestCase {
+@MainActor final class LocalizerTests: IsolatedDefaultsTestCase {
private var stored: String?
override func setUp() {
diff --git a/frontend/Tests/NX2AppleTests/MacAppLanguageTests.swift b/frontend/Tests/NX2AppleTests/MacAppLanguageTests.swift
index d19e7cf0..bbac8066 100644
--- a/frontend/Tests/NX2AppleTests/MacAppLanguageTests.swift
+++ b/frontend/Tests/NX2AppleTests/MacAppLanguageTests.swift
@@ -9,7 +9,7 @@ import XCTest
/// runs it for --platform mac-app (GFXAPI=nvn SETTINGS_PLATFORM=mac DM_LANG=zh-Hans) for profile 01008CF01BAAC000 (Zelda: Echoes of
/// Wisdom) over a control.nacp built for the test (no game files): only the SupportedLanguageFlag at 0x302C, set to en-US, ja, fr, de,
/// es, it, pt, ru, ko, zh-Hant and zh-Hans. Regenerate it the same way when settings.py or settings.tsv changes the rows.
-final class MacAppLanguageTests: XCTestCase {
+final class MacAppLanguageTests: IsolatedDefaultsTestCase {
private var temporary: URL!
private let titleID = "01008CF01BAAC000"
private var bundleID: String { "org.nxnative.frontendtests.lang." + temporary.lastPathComponent }
diff --git a/frontend/Tests/NX2AppleTests/ManageMenuTests.swift b/frontend/Tests/NX2AppleTests/ManageMenuTests.swift
index 7c5cc4dc..185d2dff 100644
--- a/frontend/Tests/NX2AppleTests/ManageMenuTests.swift
+++ b/frontend/Tests/NX2AppleTests/ManageMenuTests.swift
@@ -5,7 +5,7 @@ import XCTest
/// The Manage menu: its rows and when they can be used, what a controller's buttons do around it, and that its rows run
/// the actions the system menu ran.
-final class ManageMenuTests: XCTestCase {
+final class ManageMenuTests: IsolatedDefaultsTestCase {
private var temporary: URL!
override func setUpWithError() throws {
diff --git a/frontend/Tests/NX2AppleTests/MissingFrameworkCaptureTests.swift b/frontend/Tests/NX2AppleTests/MissingFrameworkCaptureTests.swift
index f6e101cd..a2c93da7 100644
--- a/frontend/Tests/NX2AppleTests/MissingFrameworkCaptureTests.swift
+++ b/frontend/Tests/NX2AppleTests/MissingFrameworkCaptureTests.swift
@@ -8,13 +8,13 @@ import NXModel
/// Visual QA of the missing-framework message (LNPANDY/NX2Apple#491, matched by --filter testRenderMissingFrameworkForVisualQA).
/// The Builds page's action card with the note a handoff leaves when the game's framework is not in the build folder.
-final class MissingFrameworkCaptureTests: XCTestCase {
+final class MissingFrameworkCaptureTests: IsolatedDefaultsTestCase {
@MainActor func testRenderMissingFrameworkForVisualQA() throws {
guard let directory = ProcessInfo.processInfo.environment["NX_LAUNCHER_CAPTURE_DIR"] else { throw XCTSkip("Set NX_LAUNCHER_CAPTURE_DIR to capture native views") }
let output = URL(fileURLWithPath: directory)
try FileManager.default.createDirectory(at: output, withIntermediateDirectories: true)
let lang = ProcessInfo.processInfo.environment["NX_CAPTURE_LANG"].flatMap { Lang.find($0) } ?? .en
- let stores = LauncherStores(); let model = stores.build
+ let stores = LauncherStores(defaults: testDefaults); let model = stores.build
stores.localizer.lang = lang
var installer = ShellInstaller(xcrun: "/usr/bin/xcrun", repo: "/nonexistent", python: "/usr/bin/python3", root: "/nonexistent",
device: "", team: "")
diff --git a/frontend/Tests/NX2AppleTests/OffscreenWindow.swift b/frontend/Tests/NX2AppleTests/OffscreenWindow.swift
index 6d01acb8..0652e5e9 100644
--- a/frontend/Tests/NX2AppleTests/OffscreenWindow.swift
+++ b/frontend/Tests/NX2AppleTests/OffscreenWindow.swift
@@ -42,7 +42,7 @@ final class OffscreenWindow: NSWindow {
}
}
-final class OffscreenWindowTests: XCTestCase {
+final class OffscreenWindowTests: IsolatedDefaultsTestCase {
/// Windows of the helper are shown (as the render tests do) and must be on no display, for AppKit and for the window server.
@MainActor func testRenderWindowsAreNeverOnAnyDisplay() {
NSApplication.shared.setActivationPolicy(.accessory)
diff --git a/frontend/Tests/NX2AppleTests/OlderToolsTests.swift b/frontend/Tests/NX2AppleTests/OlderToolsTests.swift
index d2e7950b..1e53e0d7 100644
--- a/frontend/Tests/NX2AppleTests/OlderToolsTests.swift
+++ b/frontend/Tests/NX2AppleTests/OlderToolsTests.swift
@@ -5,7 +5,7 @@ import XCTest
/// Games built with older build tools (ToolsAge, #65): a local git repository stands in for the checkout; a game is marked
/// only when files a build uses changed since the commit its build recorded.
-final class OlderToolsTests: XCTestCase {
+final class OlderToolsTests: IsolatedDefaultsTestCase {
private var temporary: URL!
private let titleID = "0100535012974000"
diff --git a/frontend/Tests/NX2AppleTests/OnboardingTests.swift b/frontend/Tests/NX2AppleTests/OnboardingTests.swift
index 3f8ebe73..ef707dd0 100644
--- a/frontend/Tests/NX2AppleTests/OnboardingTests.swift
+++ b/frontend/Tests/NX2AppleTests/OnboardingTests.swift
@@ -4,7 +4,7 @@ import SwiftUI
@testable import NXCore
@testable import NXLauncher
-final class OnboardingTests: XCTestCase {
+final class OnboardingTests: IsolatedDefaultsTestCase {
func testNextBackAndGates() {
var s = OnboardingState()
XCTAssertTrue(s.primaryEnabled)
diff --git a/frontend/Tests/NX2AppleTests/PadFocusTests.swift b/frontend/Tests/NX2AppleTests/PadFocusTests.swift
index 2b068359..cbba93c8 100644
--- a/frontend/Tests/NX2AppleTests/PadFocusTests.swift
+++ b/frontend/Tests/NX2AppleTests/PadFocusTests.swift
@@ -5,7 +5,7 @@ import XCTest
/// The controller focus: moves go to the nearest target in the direction and stay in their row when they can, left / right
/// change a value where the target holds one, and the first press only shows the focus.
-final class PadFocusTests: XCTestCase {
+final class PadFocusTests: IsolatedDefaultsTestCase {
private func grid() -> PadFocus {
let f = PadFocus()
// a row of three cards under a tab bar of two, and one button far right on the tab bar's line
diff --git a/frontend/Tests/NX2AppleTests/PipeReaderTests.swift b/frontend/Tests/NX2AppleTests/PipeReaderTests.swift
index 6f1de0f4..0ac157ab 100644
--- a/frontend/Tests/NX2AppleTests/PipeReaderTests.swift
+++ b/frontend/Tests/NX2AppleTests/PipeReaderTests.swift
@@ -5,7 +5,7 @@ import XCTest
/// The build log pipes (#201): at end of output the read handler must remove itself, or the dispatch source
/// fires on the closed pipe forever and pins a CPU core.
-final class PipeReaderTests: XCTestCase {
+final class PipeReaderTests: IsolatedDefaultsTestCase {
func testHandlerDetachesAtEndOfOutputAndKeepsAllOutput() throws {
let p = Process()
p.executableURL = URL(fileURLWithPath: "/bin/sh")
diff --git a/frontend/Tests/NX2AppleTests/PrimaryActionTests.swift b/frontend/Tests/NX2AppleTests/PrimaryActionTests.swift
index b6ff3e74..a04a9434 100644
--- a/frontend/Tests/NX2AppleTests/PrimaryActionTests.swift
+++ b/frontend/Tests/NX2AppleTests/PrimaryActionTests.swift
@@ -3,7 +3,7 @@ import XCTest
@testable import NXCore
@testable import NXLauncher
-final class PrimaryActionTests: XCTestCase {
+final class PrimaryActionTests: IsolatedDefaultsTestCase {
private var temporary: URL!
private let titleID = "0100535012974000"
diff --git a/frontend/Tests/NX2AppleTests/ReleaseNotesTests.swift b/frontend/Tests/NX2AppleTests/ReleaseNotesTests.swift
index 4d3a0572..5c0bddc2 100644
--- a/frontend/Tests/NX2AppleTests/ReleaseNotesTests.swift
+++ b/frontend/Tests/NX2AppleTests/ReleaseNotesTests.swift
@@ -8,7 +8,7 @@ import NXModel
/// The update sheet's Markdown: blocks and auto-links, on v0.7.0's real body
/// (Tests/Fixtures/release_v0.7.0.md, copied from `gh release view v0.7.0`).
-@MainActor final class ReleaseNotesTests: XCTestCase {
+@MainActor final class ReleaseNotesTests: IsolatedDefaultsTestCase {
static let root = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent()
.deletingLastPathComponent().deletingLastPathComponent()
@@ -203,7 +203,7 @@ import NXModel
for (name, lang, notes, tag) in [("update-sheet-notes-v072-en", Lang.en, body072, "v0.7.2"), ("update-sheet-notes-v072-zh", Lang.zh, body072, "v0.7.2")]
+ [("update-sheet-notes-en", Lang.en, body, "v0.7.0"), ("update-sheet-notes-zh", Lang.zh, body, "v0.7.0"),
("update-sheet-notes-middle-en", Lang.en, middle, "v0.7.0"), ("update-sheet-notes-middle-zh", Lang.zh, middle, "v0.7.0")] {
- let mStores = LauncherStores(); let m = mStores.build
+ let mStores = LauncherStores(defaults: testDefaults); let m = mStores.build
m.lang = lang
mStores.appUpdates.update = AppUpdate.Release(tag: tag, url: "", digest: nil, notes: notes)
let width: CGFloat = 560, height: CGFloat = 640
diff --git a/frontend/Tests/NX2AppleTests/RepoAutoUpdateTests.swift b/frontend/Tests/NX2AppleTests/RepoAutoUpdateTests.swift
index 48f27840..eee32b51 100644
--- a/frontend/Tests/NX2AppleTests/RepoAutoUpdateTests.swift
+++ b/frontend/Tests/NX2AppleTests/RepoAutoUpdateTests.swift
@@ -6,19 +6,16 @@ import NXModel
/// The automatic update when the app opens (RepoStore.autoPull): a clean checkout on main fast-forwards to origin/main,
/// one with local changes is left as it is. A local bare repository stands in for GitHub.
-@MainActor final class RepoAutoUpdateTests: XCTestCase {
+@MainActor final class RepoAutoUpdateTests: IsolatedDefaultsTestCase {
private var temporary: URL!
- private var saved: [(String, Any?)] = []
override func setUpWithError() throws {
guard FileManager.default.isExecutableFile(atPath: "/usr/bin/git") else { throw XCTSkip("git is required for the fixture") }
temporary = FileManager.default.temporaryDirectory.appendingPathComponent("nxnative-repo-" + UUID().uuidString)
try FileManager.default.createDirectory(at: temporary, withIntermediateDirectories: true)
- saved = ["repoPath", "autoUpdateRepo"].map { ($0, UserDefaults.standard.object(forKey: $0)) }
}
override func tearDownWithError() throws {
- for (key, value) in saved { UserDefaults.standard.set(value, forKey: key) }
try? FileManager.default.removeItem(at: temporary)
}
@@ -48,7 +45,7 @@ import NXModel
}
@MainActor private func open(_ checkout: URL) -> LauncherStores {
- let mStores = LauncherStores(); let m = mStores.build
+ let mStores = LauncherStores(defaults: testDefaults); let m = mStores.build
mStores.repo.path = checkout.path
mStores.repo.autoUpdate = true
mStores.repo.checkForUpdates(silent: true) // what the library does when the app opens
diff --git a/frontend/Tests/NX2AppleTests/RepoToolsTests.swift b/frontend/Tests/NX2AppleTests/RepoToolsTests.swift
index e3667eb9..2c4add2e 100644
--- a/frontend/Tests/NX2AppleTests/RepoToolsTests.swift
+++ b/frontend/Tests/NX2AppleTests/RepoToolsTests.swift
@@ -6,18 +6,15 @@ import NXModel
/// #87: a ZIP copy of the repository is connected to git when the app opens, and a build does not start with build tools
/// older than the app. Temporary folders and a local repository stand in for the user's copy and for GitHub.
-@MainActor final class RepoToolsTests: XCTestCase {
+@MainActor final class RepoToolsTests: IsolatedDefaultsTestCase {
private var temporary: URL!
- private var saved: [(String, Any?)] = []
override func setUpWithError() throws {
temporary = FileManager.default.temporaryDirectory.appendingPathComponent("nxnative-tools87-" + UUID().uuidString)
try FileManager.default.createDirectory(at: temporary, withIntermediateDirectories: true)
- saved = ["repoPath", "autoUpdateRepo"].map { ($0, UserDefaults.standard.object(forKey: $0)) }
}
override func tearDownWithError() throws {
- for (key, value) in saved { UserDefaults.standard.set(value, forKey: key) }
try? FileManager.default.removeItem(at: temporary)
}
@@ -57,7 +54,7 @@ import NXModel
@MainActor func testABuildWithOldToolsRefusesToStart() throws {
let repo = temporary.appendingPathComponent("old")
try write(["dm/tools/nx_extract/Program.cs", RepoLayout.buildScript], in: repo)
- let mStores = LauncherStores(); let m = mStores.build
+ let mStores = LauncherStores(defaults: testDefaults); let m = mStores.build
mStores.repo.path = repo.path
m.target = BuildTarget.mac
m.startBuild()
@@ -84,7 +81,7 @@ import NXModel
}
@MainActor private func openZip(_ f: (origin: URL, zip: URL), auto: Bool, remote: String? = nil) -> LauncherStores {
- let mStores = LauncherStores(); let m = mStores.build
+ let mStores = LauncherStores(defaults: testDefaults); let m = mStores.build
mStores.repo.path = f.zip.path
mStores.repo.autoUpdate = auto
mStores.repo.adoptAtLaunch(remote: remote ?? "file://" + f.origin.path)
diff --git a/frontend/Tests/NX2AppleTests/ReturnAfterPlayTests.swift b/frontend/Tests/NX2AppleTests/ReturnAfterPlayTests.swift
index 671ba29a..e45dcb2b 100644
--- a/frontend/Tests/NX2AppleTests/ReturnAfterPlayTests.swift
+++ b/frontend/Tests/NX2AppleTests/ReturnAfterPlayTests.swift
@@ -4,7 +4,7 @@ import XCTest
@testable import NXLauncher
/// When the launcher comes back to the front after a game it started quits. Nothing here touches NSWorkspace.
-@MainActor final class ReturnAfterPlayTests: XCTestCase {
+@MainActor final class ReturnAfterPlayTests: IsolatedDefaultsTestCase {
func testComesBackForAGameItStarted() {
let watcher = GameReturnWatcher(observesSystem: false)
var forward = 0, quit = 0
diff --git a/frontend/Tests/NX2AppleTests/SaveDiscoveryTests.swift b/frontend/Tests/NX2AppleTests/SaveDiscoveryTests.swift
index c1f13110..26a5f8df 100644
--- a/frontend/Tests/NX2AppleTests/SaveDiscoveryTests.swift
+++ b/frontend/Tests/NX2AppleTests/SaveDiscoveryTests.swift
@@ -5,7 +5,7 @@ import XCTest
/// Issue #250: the game's save found on the device itself, a choice between an iPhone and an iPad, and a device that does not
/// answer. devicectl is the stand-in of SaveTransferTests (a folder per device), so no test reaches a device.
-final class SaveDiscoveryTests: XCTestCase {
+final class SaveDiscoveryTests: IsolatedDefaultsTestCase {
private typealias Fake = SaveTransferTests.FakeDevice
private var temporary: URL!
private let titleID = "0100535012974000"
diff --git a/frontend/Tests/NX2AppleTests/SaveTransferTests.swift b/frontend/Tests/NX2AppleTests/SaveTransferTests.swift
index 61c07257..beddf8f4 100644
--- a/frontend/Tests/NX2AppleTests/SaveTransferTests.swift
+++ b/frontend/Tests/NX2AppleTests/SaveTransferTests.swift
@@ -5,7 +5,7 @@ import XCTest
/// Issue #66: the save copied between the Mac and a device. devicectl is a stand-in that serves a folder as the app's data
/// container, so no test reaches a device, and the Mac side is a temporary folder, never the real Application Support.
-final class SaveTransferTests: XCTestCase {
+final class SaveTransferTests: IsolatedDefaultsTestCase {
private var temporary: URL!
private let titleID = "0100535012974000"
private let fm = FileManager.default
diff --git a/frontend/Tests/NX2AppleTests/SavedChoicesTests.swift b/frontend/Tests/NX2AppleTests/SavedChoicesTests.swift
index 8f4f27a8..7fcfc656 100644
--- a/frontend/Tests/NX2AppleTests/SavedChoicesTests.swift
+++ b/frontend/Tests/NX2AppleTests/SavedChoicesTests.swift
@@ -5,7 +5,7 @@ import XCTest
/// The launch options as saved choices in the app's own preferences domain, and launcher.json schema 1. Every app here has a
/// bundle ID of this run, so nothing touches a real game's domain; tearDown removes it.
-final class SavedChoicesTests: XCTestCase {
+final class SavedChoicesTests: IsolatedDefaultsTestCase {
private var temporary: URL!
private let titleID = "01007EF00011E000"
private var bundleID: String { "org.nxnative.frontendtests.saved." + temporary.lastPathComponent }
diff --git a/frontend/Tests/NX2AppleTests/ShellCacheCaptureTests.swift b/frontend/Tests/NX2AppleTests/ShellCacheCaptureTests.swift
index cd46fb04..6b37904c 100644
--- a/frontend/Tests/NX2AppleTests/ShellCacheCaptureTests.swift
+++ b/frontend/Tests/NX2AppleTests/ShellCacheCaptureTests.swift
@@ -9,17 +9,15 @@ import AppKit
/// Visual QA of Move cache folder, LNPANDY/NX2Apple#427 (matched by --filter testRenderShellCacheForVisualQA). The Tools card of the
/// release app in every state of the move. The states are set on the store, so nothing is moved and no folder is touched: the
/// cache row only reads the saved place, which the test restores.
-final class ShellCacheCaptureTests: XCTestCase {
+final class ShellCacheCaptureTests: IsolatedDefaultsTestCase {
@MainActor func testRenderShellCacheForVisualQA() throws {
guard let directory = ProcessInfo.processInfo.environment["NX_LAUNCHER_CAPTURE_DIR"] else { throw XCTSkip("Set NX_LAUNCHER_CAPTURE_DIR to capture native views") }
let output = URL(fileURLWithPath: directory)
try FileManager.default.createDirectory(at: output, withIntermediateDirectories: true)
let lang = CaptureLanguage.current(.en)
- let saved = ["shellRoot", ShellRootMove.pickedKey].map { ($0, UserDefaults.standard.object(forKey: $0)) }
- defer { for (key, value) in saved { UserDefaults.standard.set(value, forKey: key) } }
- UserDefaults.standard.removeObject(forKey: "shellRoot")
+ testDefaults.removeObject(forKey: "shellRoot")
- let stores = LauncherStores(); let model = stores.build
+ let stores = LauncherStores(defaults: testDefaults); let model = stores.build
stores.localizer.lang = lang
stores.engineSync.bundle = URL(fileURLWithPath: "/Applications/NX2Apple.app/Contents/Resources/engine") // the release app's rows
stores.engineSync.status = ""
@@ -73,7 +71,7 @@ final class ShellCacheCaptureTests: XCTestCase {
model.shellMove = .failed("The disk “T7 Shield” was ejected", stays: defaultRoot) // the store drops the system text's full stop
try shot("8-failed")
- UserDefaults.standard.set(drive, forKey: "shellRoot") // read only: the row shows the saved place
+ testDefaults.set(drive, forKey: "shellRoot") // read only: the row shows the saved place
model.shellMove = .moved(drive)
try shot("9-moved")
model.shellMove = .movedOldStays(drive, old: defaultRoot)
diff --git a/frontend/Tests/NX2AppleTests/ShellExportCaptureTests.swift b/frontend/Tests/NX2AppleTests/ShellExportCaptureTests.swift
index 6d4ee7b4..a7693360 100644
--- a/frontend/Tests/NX2AppleTests/ShellExportCaptureTests.swift
+++ b/frontend/Tests/NX2AppleTests/ShellExportCaptureTests.swift
@@ -7,7 +7,7 @@ import NXModel
@testable import NXLauncher
/// Visual QA of LNPANDY/NX2Apple#416 (matched by --filter testRenderExportStatesForVisualQA).
-final class ShellExportCaptureTests: XCTestCase {
+final class ShellExportCaptureTests: IsolatedDefaultsTestCase {
/// The Install card in every state of the export, for the pull request's screenshots: ready, exported, sending, done, app not found,
/// refused, several apps, drive, copying, copied, FAT32 and the drive before an export. Also the card with the install flow, which the segmented switch changed.
@MainActor func testRenderExportStatesForVisualQA() throws {
@@ -16,8 +16,6 @@ final class ShellExportCaptureTests: XCTestCase {
let fm = FileManager.default
try fm.createDirectory(at: output, withIntermediateDirectories: true)
let lang = ProcessInfo.processInfo.environment["NX_CAPTURE_LANG"].flatMap { Lang.find($0) } ?? .en
- let saved = ["buildTarget", "installDevice", "exportIPA", "exportOneGame", "sendWhere", "driveFolder", "shellRoot"].map { ($0, UserDefaults.standard.object(forKey: $0)) }
- defer { for (key, value) in saved { UserDefaults.standard.set(value, forKey: key) } }
let shellFolder = fm.temporaryDirectory.appendingPathComponent("NX2Apple-capture-\(UUID().uuidString)")
try fm.createDirectory(at: shellFolder, withIntermediateDirectories: true)
let ipa = shellFolder.appendingPathComponent("NX2Apple.ipa") // the name an export writes
@@ -27,7 +25,7 @@ final class ShellExportCaptureTests: XCTestCase {
try handle.close()
defer { try? fm.removeItem(at: shellFolder) }
- let stores = LauncherStores(); let model = stores.build
+ let stores = LauncherStores(defaults: testDefaults); let model = stores.build
stores.localizer.lang = lang
model.target = "ios"
model.slots[0].paths = ["/Games/Super Mario Odyssey [0100000000010000].nsp"]
diff --git a/frontend/Tests/NX2AppleTests/ShellExportTests.swift b/frontend/Tests/NX2AppleTests/ShellExportTests.swift
index 23addfd7..c1cc10aa 100644
--- a/frontend/Tests/NX2AppleTests/ShellExportTests.swift
+++ b/frontend/Tests/NX2AppleTests/ShellExportTests.swift
@@ -8,7 +8,7 @@ import NXModel
/// LNPANDY/NX2Apple#416: the shared app as an unsigned IPA. The commands are checked as pure functions. The export runs headless
/// against a stand-in `xcrun` (xcodebuild only: it makes an app folder) and a stand-in build_shell.sh, while ditto, xattr and codesign
/// are the system's. No test builds a real app, reaches a device or needs a signing team.
-@MainActor final class ShellExportTests: XCTestCase {
+@MainActor final class ShellExportTests: IsolatedDefaultsTestCase {
private var temporary: URL!
private let fm = FileManager.default
private let titleID = "0100535012974000"
@@ -494,9 +494,7 @@ import NXModel
/// Copy with Finder selects the folder in Finder and opens the three steps. A new send closes them again. Before a failure it does nothing.
func testCopyWithFinderRevealsTheFolderAndOpensTheSteps() throws {
- let saved = savedKeys.map { ($0, UserDefaults.standard.object(forKey: $0)) }
- defer { for (key, value) in saved { UserDefaults.standard.set(value, forKey: key) } }
- let stores = LauncherStores(); let model = stores.build
+ let stores = LauncherStores(defaults: testDefaults); let model = stores.build
var revealed: [URL] = []
model.revealItem = { revealed.append($0) }
model.archivePath = path("out/games", titleID)
@@ -530,9 +528,7 @@ import NXModel
}
func testTheSendButtonsNeedTheIPAAndTheirPlace() throws {
- let saved = savedKeys.map { ($0, UserDefaults.standard.object(forKey: $0)) }
- defer { for (key, value) in saved { UserDefaults.standard.set(value, forKey: key) } }
- let stores = LauncherStores(); let model = stores.build
+ let stores = LauncherStores(defaults: testDefaults); let model = stores.build
stores.deviceStore.installDevice = "DEV-1"
model.archivePath = path("out/games", titleID)
XCTAssertFalse(model.canSendGameData, "step 3 waits for step 1")
@@ -551,10 +547,8 @@ import NXModel
let archive = try makeArchive()
try listApps([("org.nxnative.shell.ABC123", "NX2Apple")])
try write(state + "/devices-ok", "")
- let saved = savedKeys.map { ($0, UserDefaults.standard.object(forKey: $0)) }
- defer { for (key, value) in saved { UserDefaults.standard.set(value, forKey: key) } }
- UserDefaults.standard.set(f.root, forKey: "shellRoot")
- let stores = LauncherStores(xcrun: f.xcrun); let model = stores.build
+ testDefaults.set(f.root, forKey: "shellRoot")
+ let stores = LauncherStores(xcrun: f.xcrun, defaults: testDefaults); let model = stores.build
stores.repo.path = f.repo
stores.dependencies.pythonPath = "/usr/bin/python3"
stores.deviceStore.installDevice = "DEV-1"
@@ -646,9 +640,7 @@ import NXModel
@MainActor func testTheStoreCopiesToTheChosenFolderAndRefusesAFAT32Drive() throws {
let archive = try makeArchive()
- let saved = savedKeys.map { ($0, UserDefaults.standard.object(forKey: $0)) } + [(DeviceStore.driveFolderKey, UserDefaults.standard.object(forKey: DeviceStore.driveFolderKey))]
- defer { for (key, value) in saved { UserDefaults.standard.set(value, forKey: key) } }
- let stores = LauncherStores(); let model = stores.build
+ let stores = LauncherStores(defaults: testDefaults); let model = stores.build
model.archivePath = archive
model.exportedIPAPath = path("export/NX2Apple.ipa")
let folder = path("drive")
@@ -709,16 +701,12 @@ import NXModel
// ---- the choice in the build ----
- private let savedKeys = ["repoPath", "buildTarget", "buildOutputDirectory", "installDevice", "signingTeam", "shellRoot", "exportIPA", "exportOneGame"]
-
/// An iPhone build with the export chosen and no device and no team runs the script without `--team-id`, then ends with the IPA
/// instead of the "needs a device and a signing team" stop.
@MainActor func testBuildWithTheExportChoiceNeedsNoDeviceAndNoTeam() throws {
let f = try makeFixture()
- let saved = savedKeys.map { ($0, UserDefaults.standard.object(forKey: $0)) }
- defer { for (key, value) in saved { UserDefaults.standard.set(value, forKey: key) } }
- UserDefaults.standard.set(f.root, forKey: "shellRoot")
- let stores = LauncherStores(xcrun: f.xcrun); let model = stores.build
+ testDefaults.set(f.root, forKey: "shellRoot")
+ let stores = LauncherStores(xcrun: f.xcrun, defaults: testDefaults); let model = stores.build
stores.repo.path = f.repo
model.target = "ios"
model.outDir = path("out")
@@ -772,10 +760,8 @@ import NXModel
/// build ends with that IPA. No shared app, no archive, no shell.json, no stale prompt.
@MainActor func testOneGameExportBuildsTheGamesOwnIPAWithItsDataInside() throws {
let f = try makeFixture()
- let saved = savedKeys.map { ($0, UserDefaults.standard.object(forKey: $0)) }
- defer { for (key, value) in saved { UserDefaults.standard.set(value, forKey: key) } }
- UserDefaults.standard.set(f.root, forKey: "shellRoot")
- let stores = LauncherStores(xcrun: f.xcrun); let model = stores.build
+ testDefaults.set(f.root, forKey: "shellRoot")
+ let stores = LauncherStores(xcrun: f.xcrun, defaults: testDefaults); let model = stores.build
stores.repo.path = f.repo
model.target = "ios"
model.outDir = path("out")
@@ -823,14 +809,12 @@ import NXModel
}
func testOneGameChoiceIsOffAtFirstSavedAndOnlyCountsForAnExport() throws {
- let saved = savedKeys.map { ($0, UserDefaults.standard.object(forKey: $0)) }
- defer { for (key, value) in saved { UserDefaults.standard.set(value, forKey: key) } }
- UserDefaults.standard.removeObject(forKey: DeviceStore.oneGameKey)
- let stores = LauncherStores(); let model = stores.build
+ testDefaults.removeObject(forKey: DeviceStore.oneGameKey)
+ let stores = LauncherStores(defaults: testDefaults); let model = stores.build
XCTAssertFalse(stores.deviceStore.exportOneGame, "the shared app stays the default")
model.target = "ios"
stores.deviceStore.exportOneGame = true
- XCTAssertTrue(UserDefaults.standard.bool(forKey: DeviceStore.oneGameKey))
+ XCTAssertTrue(testDefaults.bool(forKey: DeviceStore.oneGameKey))
stores.deviceStore.exportIPA = false
XCTAssertFalse(model.exportsOneGame, "installing on a device is always the shared app")
stores.deviceStore.exportIPA = true
@@ -843,17 +827,15 @@ import NXModel
/// The choice is saved and a build without it still asks for a device and a team.
@MainActor func testTheChoiceIsSavedAndWithoutItTheDeviceIsStillNeeded() throws {
- let saved = savedKeys.map { ($0, UserDefaults.standard.object(forKey: $0)) }
- defer { for (key, value) in saved { UserDefaults.standard.set(value, forKey: key) } }
- let stores = LauncherStores(); let model = stores.build
+ let stores = LauncherStores(defaults: testDefaults); let model = stores.build
stores.repo.path = temporary.path
try write(temporary.path + "/dm/tools/nx_extract/Program.cs", "")
model.target = "ios"
stores.deviceStore.installDevice = ""
stores.deviceStore.exportIPA = true
- XCTAssertTrue(UserDefaults.standard.bool(forKey: DeviceStore.exportKey))
+ XCTAssertTrue(testDefaults.bool(forKey: DeviceStore.exportKey))
stores.deviceStore.exportIPA = false
- XCTAssertFalse(UserDefaults.standard.bool(forKey: DeviceStore.exportKey))
+ XCTAssertFalse(testDefaults.bool(forKey: DeviceStore.exportKey))
XCTAssertFalse(model.exportsShell)
model.startBuild()
XCTAssertEqual(model.doneNote, model.t("shell.needsDevice"))
diff --git a/frontend/Tests/NX2AppleTests/ShellInstallTests.swift b/frontend/Tests/NX2AppleTests/ShellInstallTests.swift
index 13fecf4a..eae88d14 100644
--- a/frontend/Tests/NX2AppleTests/ShellInstallTests.swift
+++ b/frontend/Tests/NX2AppleTests/ShellInstallTests.swift
@@ -9,7 +9,7 @@ import NXModel
/// after the build runs headless against a stand-in `xcrun` that models devicectl on a folder (a fake device container): an install
/// keeps the container, a copy to a file creates the parents, and `--remove-existing-content true` wipes the destination's siblings,
/// as it does on a real device. No test reaches a device or a real game.
-@MainActor final class ShellInstallTests: XCTestCase {
+@MainActor final class ShellInstallTests: IsolatedDefaultsTestCase {
private var temporary: URL!
private let fm = FileManager.default
private let titleID = "0100535012974000"
@@ -803,10 +803,8 @@ import NXModel
@MainActor func testBuildWithTheShellTargetInstallsAndResignsTheSharedApp() throws {
let f = try makeFixture()
- let keysSaved = ["repoPath", "buildTarget", "buildOutputDirectory", "installDevice", "signingTeam", "shellRoot"].map { ($0, UserDefaults.standard.object(forKey: $0)) }
- defer { for (key, value) in keysSaved { UserDefaults.standard.set(value, forKey: key) } }
- UserDefaults.standard.set(f.root, forKey: "shellRoot")
- let modelStores = LauncherStores(xcrun: f.xcrun); let model = modelStores.build
+ testDefaults.set(f.root, forKey: "shellRoot")
+ let modelStores = LauncherStores(xcrun: f.xcrun, defaults: testDefaults); let model = modelStores.build
modelStores.repo.path = f.repo
model.target = "ios"
model.outDir = path("out")
@@ -869,7 +867,7 @@ import NXModel
}
@MainActor private func makeModel(_ f: Fixture) throws -> LauncherStores {
- let modelStores = LauncherStores(xcrun: f.xcrun); let model = modelStores.build
+ let modelStores = LauncherStores(xcrun: f.xcrun, defaults: testDefaults); let model = modelStores.build
modelStores.repo.path = f.repo
model.target = "ios"
model.outDir = path("out")
@@ -892,8 +890,6 @@ import NXModel
@MainActor func testUnknownDeviceStopsTheBuildBeforeTheScriptRuns() throws {
let f = try makeFixture()
try writeDevices(state + "/devices-default.json", [("00008150-OTHER", "wired")])
- let saved = ["repoPath", "buildTarget", "buildOutputDirectory", "installDevice", "signingTeam"].map { ($0, UserDefaults.standard.object(forKey: $0)) }
- defer { for (key, value) in saved { UserDefaults.standard.set(value, forKey: key) } }
let modelStores = try makeModel(f)
let model = modelStores.build
model.startBuild()
@@ -909,9 +905,7 @@ import NXModel
/// The copy card's answer and the failure row: a copy that fails midway says the data is incomplete, and Retry runs only the data step.
@MainActor func testFailedCopyShowsTheIncompleteRowAndRetryFinishesIt() throws {
let f = try makeFixture()
- let saved = ["repoPath", "buildTarget", "buildOutputDirectory", "installDevice", "signingTeam", "shellRoot"].map { ($0, UserDefaults.standard.object(forKey: $0)) }
- defer { for (key, value) in saved { UserDefaults.standard.set(value, forKey: key) } }
- UserDefaults.standard.set(f.root, forKey: "shellRoot")
+ testDefaults.set(f.root, forKey: "shellRoot")
let modelStores = try makeModel(f)
let model = modelStores.build
try write(state + "/fail-on", "romfs.img")
@@ -948,9 +942,7 @@ import NXModel
}
@MainActor func testShellTargetWithoutDeviceStopsBeforeBuilding() throws {
- let saved = ["repoPath", "buildTarget", "installDevice", "signingTeam", DeviceStore.exportKey].map { ($0, UserDefaults.standard.object(forKey: $0)) }
- defer { for (key, value) in saved { UserDefaults.standard.set(value, forKey: key) } }
- let modelStores = LauncherStores(); let model = modelStores.build
+ let modelStores = LauncherStores(defaults: testDefaults); let model = modelStores.build
modelStores.repo.path = temporary.path
try write(temporary.path + "/dm/tools/nx_extract/Program.cs", "")
model.target = "ios"
diff --git a/frontend/Tests/NX2AppleTests/ShellMirrorTests.swift b/frontend/Tests/NX2AppleTests/ShellMirrorTests.swift
index 4a7fa1b3..f2a8306b 100644
--- a/frontend/Tests/NX2AppleTests/ShellMirrorTests.swift
+++ b/frontend/Tests/NX2AppleTests/ShellMirrorTests.swift
@@ -3,7 +3,7 @@ import XCTest
@testable import NXCore
@testable import NXLauncher
-final class ShellMirrorTests: XCTestCase {
+final class ShellMirrorTests: IsolatedDefaultsTestCase {
private let id = "0100A00019DE0000"
private var tmp = ""
diff --git a/frontend/Tests/NX2AppleTests/SignatureTests.swift b/frontend/Tests/NX2AppleTests/SignatureTests.swift
index ac93f31d..c3a1ba8b 100644
--- a/frontend/Tests/NX2AppleTests/SignatureTests.swift
+++ b/frontend/Tests/NX2AppleTests/SignatureTests.swift
@@ -5,7 +5,7 @@ import XCTest
/// The provisioning-profile expiry a free Apple ID's install has to show (7 days), and the re-sign command that renews
/// it: parsing, the day count, the wording, and the xcodebuild parameters (the install's, plus the app's own bundle ID).
-final class SignatureTests: XCTestCase {
+final class SignatureTests: IsolatedDefaultsTestCase {
private func profile(expires: Date?) throws -> Data {
var plist: [String: Any] = ["Name": "iOS Team Provisioning Profile: org.nxnative.test", "TeamIdentifier": ["TEAM123456"]]
if let expires { plist["ExpirationDate"] = expires }
diff --git a/frontend/Tests/NX2AppleTests/SourceSizeTests.swift b/frontend/Tests/NX2AppleTests/SourceSizeTests.swift
index e1159643..42826686 100644
--- a/frontend/Tests/NX2AppleTests/SourceSizeTests.swift
+++ b/frontend/Tests/NX2AppleTests/SourceSizeTests.swift
@@ -2,7 +2,7 @@ import XCTest
/// LNPANDY/NX2Apple#387: no Swift file under frontend/Sources is above 800 lines. The files above it today are listed with their
/// size, so they may only shrink. When one drops to 800 lines or fewer, its entry goes (the test says so), and nothing grows back.
-final class SourceSizeTests: XCTestCase {
+final class SourceSizeTests: IsolatedDefaultsTestCase {
private static let limit = 800
/// Path under frontend/Sources → its line count when the limit came in. Lower the number when the file shrinks.
diff --git a/frontend/Tests/NX2AppleTests/StaleFrameworksTests.swift b/frontend/Tests/NX2AppleTests/StaleFrameworksTests.swift
index 2227ad8b..66c087be 100644
--- a/frontend/Tests/NX2AppleTests/StaleFrameworksTests.swift
+++ b/frontend/Tests/NX2AppleTests/StaleFrameworksTests.swift
@@ -5,7 +5,7 @@ import SwiftUI
import NXModel
/// LNPANDY/NX2Apple#449: a shell folder with one framework of the current chain and one of the old chain.
-@MainActor final class StaleFrameworksTests: XCTestCase {
+@MainActor final class StaleFrameworksTests: IsolatedDefaultsTestCase {
private let current = "b-b7cd656abd7c"
private let old = "b-e65a4ebd3322"
private let oldID = "0100A00019DE0000"
@@ -80,7 +80,7 @@ import NXModel
func testStopLeavesEveryFileAsItWas() throws {
let (stale, fresh) = try shell()
let before = try Data(contentsOf: URL(fileURLWithPath: ShellLibrary.stateFile(root: tmp + "/shell")))
- let modelStores = LauncherStores(); let model = modelStores.build
+ let modelStores = LauncherStores(defaults: testDefaults); let model = modelStores.build
model.staleFrameworks = found()
XCTAssertFalse(model.staleFrameworks.isEmpty)
model.stopForStaleFrameworks()
@@ -129,11 +129,10 @@ import NXModel
func testContinueStartsTheBuildAndTheModelEndsWithoutAPrompt() throws {
_ = try shell()
- let modelStores = LauncherStores(); let model = modelStores.build
+ let modelStores = LauncherStores(defaults: testDefaults); let model = modelStores.build
model.staleFrameworks = found()
var started = false
- UserDefaults.standard.set(tmp + "/shell", forKey: "shellRoot")
- defer { UserDefaults.standard.removeObject(forKey: "shellRoot") }
+ testDefaults.set(tmp + "/shell", forKey: "shellRoot")
model.continueWithStaleFrameworks { started = true }
XCTAssertTrue(started)
XCTAssertTrue(model.staleFrameworks.isEmpty)
diff --git a/frontend/Tests/NX2AppleTests/TypographyTests.swift b/frontend/Tests/NX2AppleTests/TypographyTests.swift
index c5cd0518..593766bc 100644
--- a/frontend/Tests/NX2AppleTests/TypographyTests.swift
+++ b/frontend/Tests/NX2AppleTests/TypographyTests.swift
@@ -6,7 +6,7 @@ import XCTest
/// Each size and weight of Manrope is made once and then reused, so a page with hundreds of labels does not
/// create hundreds of fonts each time it is drawn.
-final class TypographyTests: XCTestCase {
+final class TypographyTests: IsolatedDefaultsTestCase {
func testTheSameSizeAndWeightGiveTheSameFont() throws {
let first = try XCTUnwrap(Typography.manropeFont(size: 13, weight: .semibold))
let second = try XCTUnwrap(Typography.manropeFont(size: 13, weight: .semibold))
diff --git a/frontend/Tests/NX2AppleTests/UpdateSheetTests.swift b/frontend/Tests/NX2AppleTests/UpdateSheetTests.swift
index 0e3bacd8..0793fffc 100644
--- a/frontend/Tests/NX2AppleTests/UpdateSheetTests.swift
+++ b/frontend/Tests/NX2AppleTests/UpdateSheetTests.swift
@@ -6,7 +6,7 @@ import XCTest
/// The update sheet's bilingual split (ReleaseNotes.lines, read here as the displayed text of each block): the release bodies follow
/// docs/RELEASE-NOTES-GUIDE.md — a bilingual heading, `**中文** …` / `**English** …` paragraphs, then
/// bullets that interleave. A Chinese reader must not get the English paragraph and vice versa.
-final class UpdateSheetTests: XCTestCase {
+final class UpdateSheetTests: IsolatedDefaultsTestCase {
/// What a reader sees: each block's text, bullets prefixed with "- ".
static func plain(_ notes: String, for lang: Lang) -> [String] {
ReleaseNotes.blocks(from: ReleaseNotes.markdown(notes, for: lang)).map {
diff --git a/frontend/Tests/NX2AppleTests/XcodeTeamsTests.swift b/frontend/Tests/NX2AppleTests/XcodeTeamsTests.swift
index 791bc377..1a7b60d0 100644
--- a/frontend/Tests/NX2AppleTests/XcodeTeamsTests.swift
+++ b/frontend/Tests/NX2AppleTests/XcodeTeamsTests.swift
@@ -6,7 +6,7 @@ import NXModel
/// #87: the signing teams of the Apple IDs signed in to Xcode, read from Xcode's preferences (sample plists, not this
/// Mac's), merged with the teams of development certificates.
-@MainActor final class XcodeTeamsTests: XCTestCase {
+@MainActor final class XcodeTeamsTests: IsolatedDefaultsTestCase {
private func plist(_ body: String) -> Data {
Data("""
<?xml version="1.0" encoding="UTF-8"?>
@@ -95,12 +95,12 @@ import NXModel
func testTheNoTeamMessageNamesTheRealCause() {
for lang in [Lang.en, .zh] {
- let mStores = LauncherStores(); let m = mStores.build; m.lang = lang
+ let mStores = LauncherStores(defaults: testDefaults); let m = mStores.build; m.lang = lang
XCTAssertFalse(m.t("dev.noTeam").isEmpty)
XCTAssertNotEqual(m.t("dev.teamNoCert"), "dev.teamNoCert")
XCTAssertNotEqual(m.t("dev.personalTeam"), "dev.personalTeam")
}
- let mStores = LauncherStores(); let m = mStores.build; m.lang = .en
+ let mStores = LauncherStores(defaults: testDefaults); let m = mStores.build; m.lang = .en
XCTAssertTrue(m.t("dev.noTeam").contains("Settings → Apple Accounts"))
XCTAssertTrue(m.t("dev.noTeam").contains("no development certificate"))
XCTAssertTrue(m.t("dev.noTeam").contains("Download Manual Profiles"))
diff --git a/frontend/Tests/NXCoreTests/UninstallTests.swift b/frontend/Tests/NXCoreTests/UninstallTests.swift
index d155745f..d5c8459c 100644
--- a/frontend/Tests/NXCoreTests/UninstallTests.swift
+++ b/frontend/Tests/NXCoreTests/UninstallTests.swift
@@ -28,7 +28,6 @@ final class UninstallTests: XCTestCase {
/// Uninstall computes from NSHomeDirectory: the tests point it at the temporary folder.
private func setHome(_ path: String) {
- UserDefaults.standard.set(path, forKey: "NSGlobalDomain_home") // not read by the app; the env below is
setenv("HOME", path, 1)
}