All writing

Isolating a Mac Catalyst test host from your real app data

This one is about unit tests on Mac Catalyst, and about the difference between “the tests pass” and “the tests didn’t touch anything they shouldn’t”, which turned out to be bigger than I assumed for a reading app I’m building (SwiftUI, Core Data, iOS plus a Mac Catalyst build).

The test host is your app, in your home

When you run an app’s unit tests on iOS, the test bundle is loaded into the app (the test host), and the app runs inside the simulator’s container, so whatever it reads or writes is thrown away with the simulator and nobody cares. On Mac Catalyst the same test host is the unsandboxed Mac app, running as you, in your home folder, which means ~/Library/Application Support/<bundle id>/ is the very same folder the copy of the app you use every day reads its library from.

That is fine as long as nothing in the test run opens the real store, and in our case three things did. The app delegate ran some launch work (preparing the store, registering background tasks) outside its “am I a unit-test host?” guard, and both of those evaluated CoreDataStack.shared. A bunch of tests reached .shared too, some directly and some through a dependency’s parameterless .live value or a holder that picked .shared by itself. And nothing relocated the host’s home, so even a well-behaved test that wrote a cache file under Application Support wrote it into mine.

What made it more than an untidy log was a Debug-only recovery path. When Core Data refuses to open a store because the model hashes don’t match (error 134100), the Debug build backs both stores up and recreates them, which is a sensible thing to do on a developer’s simulator after a schema change, and a terrible thing to do to the library of the app you read your books in. So the first test run after a model change could leave the installed app with an empty library and a backup_<timestamp> folder in ~/Library/Caches/Backups, and nothing in the run would be red.

It was spotted in a review of an unrelated branch, as 134100 and “Attempting recovery” lines in Catalyst test logs that pointed at the real Application Support path. (The same lines were in logs from two other branches, so it wasn’t anything that branch did. The first suspect, the SwiftUI library window opening the store, was ruled out quickly, since it already skipped its setup under tests.) The real store files were born a week before, so no wipe had happened yet, but the branch under review renamed an entity and would have hit the recreate path for real.

If you want to check your own setup: a backup_<timestamp> folder whose timestamp matches a test run, or store files whose birth time matches a test run instead of an app launch, means the host has been in there.

Closing the paths one by one

Each path needed its own fix, because closing one left the other two open. The delegate returns early in a unit-test host, every seam that needs a store takes it as a parameter (the composition root passes the shared one, a test passes its own), and the host gets a home of its own.

Moving the home is what CFFIXED_USER_HOME is for. Foundation reads it on startup and from then on NSHomeDirectory(), URL.applicationSupportDirectory, URL.documentsDirectory and friends all resolve under it. You can set it for every Catalyst test launch in the test plan:

"environmentVariableEntries" : [
  {
    "key" : "CFFIXED_USER_HOME",
    "value" : "$(TEST_HOST_HOME)"
  }
]

(Or from a script, by exporting TEST_RUNNER_CFFIXED_USER_HOME, since xcodebuild passes TEST_RUNNER_-prefixed variables to the test host without the prefix. That’s how we started, and it meant a run from Xcode’s own test action kept the real home.)

The relocated home starts empty. Every real home has a Documents folder, so code that moves a file into Documents without creating it first works fine for years, and then fails under the relocated home with Cocoa error 4. With randomized test order it only failed when no earlier test had happened to create Documents as a side effect, which made it look flaky. We now create Documents, Application Support and Caches when the test bundle loads.

The first fix also came with a Catalyst-only test that fails if the data root is the account’s real home. It has to be Catalyst-only, because the check asks getpwuid_r for the account’s home directory and the simulator has no account entry to answer with.

The obvious way to find tests that reach .shared is to grep for them, and it misses the indirect ones: a test that calls a dependency’s .live value, which internally grabs .shared, looks perfectly innocent in source. A review found six more of those after I thought the grep had caught them all (it didn’t help that its output was cut at 20 lines).

So the shared store got a Debug-only refusal that the test bundle switches on as it loads. XCTest builds the bundle’s principal class (NSPrincipalClass in the test bundle’s Info.plist) before any test runs, which is the right place for it:

// In the store
public nonisolated(unsafe) static let shared: CoreDataStack = {
    #if DEBUG
    if sharedAccess.withLock({ $0 == .refused }) {
        preconditionFailure("CoreDataStack.shared evaluated in the unit-test host")
    }
    #endif
    return CoreDataStack()
}()

// In the test bundle's principal class
override init() {
    super.init()
    CoreDataStack.refuseShared()
}

Any test that reaches the real store now traps before the store opens, and xcodebuild names the test that did it, which no amount of grepping gives you. One thing to watch with a fence like this is that it can make other tests vacuous: the early return in the delegate meant a test of the delegate’s observers no longer had any observers to check, and it would have passed whatever the code did. If you add a guard that skips work under tests, look for the tests that were checking that work.

Preferences don’t follow the home

With all of that in place, the real app’s preferences plist still changed during isolated runs, and it had picked up keys only a test writes, like AppleLanguages = [en] and AppleLocale = en_US from a test that pins the locale and writes it back in tearDown. The relocated home’s Library/Preferences stayed empty.

Preferences aren’t written by the process. UserDefaults talks to cfprefsd, and for an unsandboxed process cfprefsd keeps the plist in the account’s real ~/Library/Preferences, by domain name, and the domain name is the bundle identifier. The test host is the app, with the app’s bundle identifier, so it shares the app’s domain whatever home it has. A small probe that wrote a uniquely named suite and synchronized it landed in the real ~/Library/Preferences every time:

EnvironmentNSHomeDirectory()Where the plist landed
CFFIXED_USER_HOME=<dir><dir>real ~/Library/Preferences
plus HOME=<dir><dir>real ~/Library/Preferences
plus __CFPREFERENCES_AVOID_DAEMON=1<dir>real ~/Library/Preferences

A suite named by an absolute path does stay at that path, except that a path ending in Library/Preferences/<name> gets folded back into the real directory as <name>, so you can’t trick it that way either.

The isolation test hadn’t noticed because its preferences check compared URL.libraryDirectory against the real home, and URL.libraryDirectory follows CFFIXED_USER_HOME while cfprefsd never looks at it. It was checking a path that has nothing to do with where preferences go.

What fixed it was giving the test host an identity of its own. We added a DebugTest build configuration (a copy of Debug that the scheme’s test action uses) whose Mac Catalyst build has its own bundle identifier, is signed to run locally, and has the app’s entitlements minus the profile-bound ones. Its preferences now land in a <bundle id>.testhost domain that the scheme empties before and after each run. The name has to contain “Debug”, because Xcode builds Swift packages with their debug configuration only for a configuration named so (one called Test built the packages with -O, without DEBUG or testability).

Check a write through whoever stores it. To prove preferences go to the right domain, the test writes a probe key and asks cfprefsd from a second process, defaults read <domain> <key>, for both the test host’s domain and the real app’s:

defaults read com.example.reader.testhost probe-key  # exit 0, the key is set
defaults read com.example.reader probe-key           # exit 1, it isn't

Reading the plist file instead is wrong both ways, because once a domain’s file exists cfprefsd rewrites it 8-10 seconds after a synchronize, so right after a write the file can still be missing a key that is set, or still hold one that was removed. (On Catalyst, Foundation’s Process can’t launch anything, so the test uses posix_spawn with an empty environment, which also keeps the relocated home out of the child.)

The same goes for anything else a daemon keys by bundle identifier, background URLSession identifiers included, which are shared by every process that carries the identifier. Not everything per-app ignores the home, tho: Saved Application State did follow the relocated home when I measured it, so where a per-app file goes has to be measured, not assumed from the home.

The short version is that on Mac Catalyst a unit-test host is your real app, with your real data, until you make it something else, and moving its home only covers the paths the process resolves itself. Give the host its own home and its own bundle identifier, make the shared store refuse to open once the test bundle loads instead of trusting a search to find every reach, and prove that a write landed where you meant by asking whoever stores it, from another process, rather than by comparing paths.

Email address copied [email protected]