Test iOS disk-write failures without filling the test Mac

Test iOS disk-write failures without filling the test Mac

Test iOS disk-write failures without filling the test Mac

Just before release, an offline draft’s save button switches to “Saved,” but reopening the draft brings back the old content. Testing successful writes alone will not catch this kind of bug: a full disk or an unwritable directory can both prevent persistence. When moving these tests to a cloud Mac, inject failures at the write boundary first, then verify real file behavior. Do not reproduce the problem by filling the test node’s disk.

Define the scope

This test suite covers replacement saves for a single file only: on failure, preserve the old content and do not mark the save as successful; once the fault is cleared, allow a retry. Keep database transactions, multi-file commits, and power-loss recovery out of this suite.

Start by defining what the product promises. “Saved” should mean that the persistence interface returned successfully, not merely that the user clicked a button. The draft being edited can remain in memory, but it must be kept separate from the last successfully saved snapshot.

A fault-injection test double demonstrates how the application handles errors. It does not prove that the underlying filesystem provides the same atomicity or durability guarantees.

Pin the source commit and toolchain version on the cloud Mac test node. Give each task its own directory. Do not change system directory permissions or apply recursive permission changes to the entire workspace.

Isolate the write boundary

Add the following code to an existing unit test target. The example model represents only the bytes from the last successful save, not the editor’s entire state. The production adapter uses an atomic write, and the application layer updates the snapshot only after the write returns successfully.

import Foundation
import XCTest

protocol FileWriting {
    func replace(_ data: Data, at url: URL) throws
}

struct DiskWriter: FileWriting {
    func replace(_ data: Data, at url: URL) throws {
        try data.write(to: url, options: .atomic)
    }
}

final class SnapshotStore {
    private let writer: any FileWriting
    private let url: URL
    private(set) var committed: Data

    init(writer: any FileWriting, url: URL, initial: Data) {
        self.writer = writer
        self.url = url
        self.committed = initial
    }

    func save(_ next: Data) throws {
        try writer.replace(next, at: url)
        committed = next
    }
}

Do not assign the new value to committed before attempting to write it to disk. Otherwise, the interface may read a snapshot that was never persisted, even though the write threw an error. After catching the error, the caller should display a failure state and retain the input awaiting save, rather than clearing the edited content.

This example assumes saves run serially. If multiple save requests can arrive concurrently, commit ordering needs a separate constraint. Atomic file replacement does not prevent an older request from finishing last and overwriting newer content.

Inject write failures

The test double throws before replacing the data and tracks the bytes from the last successful write. The two errors cover exhausted storage and permission denial. These tests do not depend on actual free space, and repeated runs do not consume the node’s disk capacity.

final class FaultWriter: FileWriting {
    var failure: POSIXErrorCode?
    private(set) var bytes: Data

    init(initial: Data) {
        bytes = initial
    }

    func replace(_ data: Data, at url: URL) throws {
        if let failure = failure {
            throw POSIXError(failure)
        }
        bytes = data
    }
}

final class PersistenceFailureTests: XCTestCase {
    func testFailurePreservesSnapshotAndAllowsRetry() throws {
        for code in [POSIXErrorCode.ENOSPC, .EACCES] {
            let old = Data("old".utf8)
            let next = Data("next".utf8)
            let writer = FaultWriter(initial: old)
            let store = SnapshotStore(
                writer: writer,
                url: URL(fileURLWithPath: "/unused/snapshot"),
                initial: old
            )
            writer.failure = code

            XCTAssertThrowsError(try store.save(next)) { error in
                XCTAssertEqual((error as? POSIXError)?.code, code)
            }
            XCTAssertEqual(writer.bytes, old)
            XCTAssertEqual(store.committed, old)

            writer.failure = nil
            try store.save(next)
            XCTAssertEqual(writer.bytes, next)
            XCTAssertEqual(store.committed, next)
        }
    }
}

The path is passed only to the test double; no file is created. Do not describe these assertions as a “real disk-full test.” They verify error propagation, commit ordering, and recovery. Actual file operations may also return errors wrapped in NSError, so the UI layer must not rely on a single conditional type cast to recognize failures.

Verify real file operations

Add an integration test to confirm that the production adapter actually replaces the target file. Use a randomly named directory to prevent tests running on multiple nodes or in parallel from overwriting one another’s files. Limit cleanup to the directory created by this test.

extension PersistenceFailureTests {
    func testDiskWriterReplacesExistingFile() throws {
        let root = FileManager.default.temporaryDirectory
            .appendingPathComponent(UUID().uuidString)
        try FileManager.default.createDirectory(
            at: root,
            withIntermediateDirectories: true
        )
        defer { try? FileManager.default.removeItem(at: root) }

        let target = root.appendingPathComponent("snapshot.bin")
        try Data("old".utf8).write(to: target)

        try DiskWriter().replace(Data("next".utf8), at: target)

        XCTAssertEqual(
            try Data(contentsOf: target),
            Data("next".utf8)
        )
    }
}

This test proves only that replacement works under normal conditions. Failures partway through a real write need separate testing in an isolated environment. Deleting the parent directory to trigger an error is not a substitute for testing exhausted storage. Making only the target file read-only is not enough either: an atomic write may still succeed if the directory permits replacement.

Run these cases in an iOS Simulator test target to exercise the file interfaces in that runtime. Tests on the host filesystem do not replace acceptance testing of data protection and storage behavior on a device.

Tighten the release gates

Use the existing project’s shared Scheme and an explicit simulator destination in the pipeline, selecting only this test suite. Supply the actual project parameters before running the command, then check its exit code directly.

set -eu
: "${PROJECT:?Set PROJECT}"
: "${SCHEME:?Set SCHEME}"
: "${SIMULATOR_UDID:?Set SIMULATOR_UDID}"
: "${TEST_TARGET:?Set TEST_TARGET}"

xcodebuild test \
  -project "$PROJECT" \
  -scheme "$SCHEME" \
  -destination "platform=iOS Simulator,id=$SIMULATOR_UDID" \
  "-only-testing:$TEST_TARGET/PersistenceFailureTests"

The final checks cover four points: whether failures propagate to the caller, whether the old snapshot remains unchanged, whether the interface retains unsaved input, and whether saving can be retried once the fault is cleared. The first three code blocks do not replace UI assertions; add those in tests for the caller.

Log the operation stage, error domain, and error code, but never the draft’s content. Automatic retries must have a fixed limit; repeatedly attempting writes when storage is exhausted only makes the failure worse. Use repeatable fault injection as a gate for every merge, and reserve real storage-boundary testing for isolated acceptance tests. That makes “save failed” a verifiable behavior rather than an intermittent report from production.

Frequently asked questions

Do these tests need a genuinely full disk?

No. Inject ENOSPC through a write interface to test application behavior deterministically. Actual storage exhaustion belongs in a separate filesystem integration test, not on a shared test node.

Does atomic Data.write guarantee durability after power loss?

No. Atomic replacement helps prevent readers from seeing a partially written destination. Power-loss durability, multi-file transactions, and recovery require separate guarantees and tests.

Run tests in parallel across multiple nodes

Choose a dedicated physical Mac mini for your workload. Rent by the day, with no renewal when the term ends. Check the model and node before scheduling regression tests.

Prepare for the next test run

Check the model and connection steps, then assign the test tasks.