DEV Community

Darkø Tasevski
Darkø Tasevski

Posted on Originally published at darkotasevski.dev

Swift Testing expectations inside Core Data perform blocks

This is a short note about a Swift Testing behavior that caught my reading app (an iOS side project with a Core Data store) three times in about a month, each time in a slightly different shape, so I figured it's time to write it down properly instead of fixing it once more in yet another test.

The short version is that a #expect which runs inside a Core Data perform or performAndWait closure, or inside some callback that the code under test calls on the context's queue, doesn't fail the test that wrote it. Xcode still records the failure, but it files it under a separate node called Issues recorded without an associated test or suite, and the test itself shows up as Passed.

What it looks like

Here's the shape of the test that did it the last time, with the domain stripped out. The code under test has a save helper that takes a closure, and while any save is in flight, a snapshot of some shared state has to read as .unavailable. So the natural way to write the test is to check the snapshot from inside the closure, while the save is happening:

@Test func snapshotIsUnavailableDuringSave() async throws {
    let stack = try await CoreDataStack.makeTempDirSQLite()
    let context = stack.newBackgroundContext()

    try await context.perform {
        context.insertTestEntity()
        try stack.saveHoldingFence(in: context) {
            // Runs on the context's private queue
            #expect(stack.snapshot() == .unavailable)
            try context.save()
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

When the production code is broken and the snapshot doesn't go unavailable, the console output from Swift Testing says exactly what happened, if you read all of it (this is from the real test, which checked the snapshot at three points, hence the three issues):

◇ Test snapshotIsUnavailableDuringSave() started.
✘ Test «unknown» recorded an issue at ...Tests.swift:189:21: Expectation failed: ...
✘ Test «unknown» recorded an issue at ...Tests.swift:194:29: Expectation failed: ...
✘ Test «unknown» recorded an issue at ...Tests.swift:198:21: Expectation failed: ...
✔ Test snapshotIsUnavailableDuringSave() passed after 0.085 seconds.
✘ Test run with 1 test in 1 suite failed after 0.088 seconds with 3 issues.
Enter fullscreen mode Exit fullscreen mode

The issue belongs to «unknown», the test passes, and the run fails. In the result bundle, xcresulttool get test-results summary reports "result" : "Failed" with "passedTests" : 1 and "failedTests" : 1 out of a total of 2 for a run where we selected exactly one test, because the unassociated node counts as a test of its own. And xcodebuild test-without-building ended that run with ** TEST EXECUTE SUCCEEDED ** and exit status 0.

Why the test doesn't own the failure

Swift Testing figures out which test an issue belongs to through Test.current, which is backed by a @TaskLocal. The doc comment on Test.current in the swift-testing source says it plainly: if the current thread was created without Swift concurrency, for example through DispatchQueue.async(execute:), the value may be nil. A private-queue NSManagedObjectContext runs its blocks on its own queue, not inside the test's task, so when the #expect in there fails there is no current test to charge it to, and it ends up in the unassociated bucket. The async version of perform doesn't change that, since it only awaits the block, it doesn't run it in our task (and performAndWait on a second context from inside the first one is the same story, one more queue away).

Who gets fooled

Xcode marks the run as failed, so the trouble is with anything that judges by test identifier or by exit status, and with whoever is looking at the test navigator, where the test you just wrote has a green checkmark next to it:

  • A wrapper script that trusts the xcodebuild exit status. Mine printed Failed: 1 from the summary and then All tests passed! right after it, and exited 0, until I made it fail whenever the summary has a positive failed count, regardless of which test it's attributed to.
  • A mutation run that asks "did the named test fail on this mutant?". The first time this happened, a mutation check on a reading-state merge looked clean (five new tests green, runner exiting 0), while the result bundle held one unassociated failure, so the whole mutation evidence was invalid. The last time, a mutant came back with the named test Passed, which reads as a surviving mutant and a weak test, when the test had caught it.

The runner fix in the first bullet made whole runs fail, but the mutation matrix kept recording its verdicts per named test, so a month later the same thing showed up there with a new test that had been written the old way (in a test for nested saves on two background contexts, which is exactly where you want to look at the state from inside the callbacks).

The fix in the test

The fix is to not assert on the queue at all. We collect whatever we want to check while we're on the queue, and assert after the await, back in the test's own task. With Mutex from the Synchronization module that looks like this:

import Synchronization

@Test func snapshotIsUnavailableDuringSave() async throws {
    let stack = try await CoreDataStack.makeTempDirSQLite()
    let context = stack.newBackgroundContext()
    let observed = Mutex<[Snapshot]>([])

    try await context.perform {
        context.insertTestEntity()
        try stack.saveHoldingFence(in: context) {
            observed.withLock { $0.append(stack.snapshot()) }
            try context.save()
        }
    }

    let snapshots = observed.withLock { $0 }
    try #require(snapshots.count == 1)
    #expect(snapshots[0] == .unavailable)
}
Enter fullscreen mode Exit fullscreen mode

The #require on the count matters, because without it a callback that never ran would leave an empty array and nothing to fail on. When the block can just return what we need, returning a Sendable value (a struct of plain values, never a managed object) from perform and asserting on that is even simpler, and that's what the first fix did. After the rewrite, the mutants that had "survived" failed on the named test, with the messages attached to it, and the restored code passed again.

Summary

TLDR: in Swift Testing, never #expect on a Core Data queue. Copy the values out and assert after the await.

If a test touches Core Data (or any code that calls back on a dispatch queue), the expectations have to run in the test's task, so collect the values on the queue and check them after the await. And whatever reads your test results, a script, a CI step or a mutation runner, should look at the total failed count in the result bundle and not only at the named test or the exit status, since that's the one place this kind of failure always shows up. There's more on checks that can't go red for the right reason in Writing checks that can fail on the bug they guard against, and this belongs on the same list, as a test that catches the bug but reports it somewhere the verdict doesn't look.

Top comments (0)