Skip to content

Test iOS property list persistence on a cloud Mac

Test iOS property list persistence on a cloud Mac

Test iOS property list persistence on a cloud Mac

A configuration that reads correctly on a developer’s machine may come back from a cloud Mac pipeline with a boolean treated as a number, or lose date precision after a switch to binary format. Checking that “the file exists” will not catch these problems. For property lists used by iOS, CI should verify three parts of the contract—writing, reading back, and failure handling—not just run a syntax check once.

Define which values may be persisted

This assumes the node already has working command-line tools and that xcrun swift --version returns a version. The examples use Foundation without installing additional dependencies. Host-side checks validate the data format; the app’s own read path still needs coverage in iOS tests.

Property lists support strings, numbers, booleans, dates, Data, arrays, and dictionaries with string keys. They do not support arbitrary Swift objects. When an optional value is absent, explicitly agree to omit the field rather than substituting NSNull.

Add schemaVersion to the root dictionary, and define the rules for each field: whether it may be missing, the permitted integer range, and whether unknown fields can be ignored. If dates are stored at whole-second precision, normalize them before writing. If subsecond precision is required, use a separate integer timestamp field rather than assuming XML and binary date representations are fully equivalent.

Successful parsing proves only that a file follows a particular syntax, not that it satisfies the app’s data contract. An empty dictionary can parse successfully without being a valid configuration.

Test both formats with the same sample

Save the following code as PlistContract.swift. The sample uses a whole-second date, generates both XML and binary files, and then reads them back from disk. Every check uses an explicit failure function rather than assertions that optimization may disable.

import Foundation
import CoreFoundation

func require(_ condition: Bool, _ message: String) {
    if !condition {
        fatalError(message)
    }
}

require(CommandLine.arguments.count == 2, "Output directory required")
let directory = URL(fileURLWithPath: CommandLine.arguments[1],
                    isDirectory: true)
let instant = Date(timeIntervalSince1970: 1_700_000_000)
let payload = Data([0x00, 0x7f, 0x80, 0xff])
let source: [String: Any] = [
    "schemaVersion": 1,
    "enabled": true,
    "attempts": 7,
    "updatedAt": instant,
    "payload": payload,
    "names": ["alpha", "中文"]
]

for format in [PropertyListSerialization.PropertyListFormat.xml, .binary] {
    require(
        PropertyListSerialization.propertyList(source, isValidFor: format),
        "Invalid source"
    )
    let bytes = try PropertyListSerialization.data(
        fromPropertyList: source, format: format, options: 0
    )
    let name = format == .xml ? "sample-xml.plist" : "sample-binary.plist"
    let file = directory.appendingPathComponent(name)
    try bytes.write(to: file, options: .atomic)

    var detected = PropertyListSerialization.PropertyListFormat.xml
    let object = try PropertyListSerialization.propertyList(
        from: Data(contentsOf: file), options: [], format: &detected
    )
    guard let result = object as? [String: Any],
          let version = result["schemaVersion"] as? NSNumber,
          let enabled = result["enabled"] as? NSNumber,
          let attempts = result["attempts"] as? NSNumber else {
        fatalError("Unexpected field types")
    }

    require(detected == format, "Unexpected file format")
    require(CFGetTypeID(enabled) == CFBooleanGetTypeID(), "Boolean lost")
    require(CFGetTypeID(attempts) != CFBooleanGetTypeID(), "Number became boolean")
    require(version.intValue == 1, "Schema changed")
    require(enabled.boolValue, "Boolean changed")
    require(attempts.int64Value == 7, "Integer changed")
    require(result["updatedAt"] as? Date == instant, "Date changed")
    require(result["payload"] as? Data == payload, "Data changed")
    require(result["names"] as? [String] == ["alpha", "中文"], "Array changed")
}

let invalid: [String: Any] = ["missing": NSNull()]
require(
    !PropertyListSerialization.propertyList(invalid, isValidFor: .binary),
    "Invalid object accepted"
)

do {
    _ = try PropertyListSerialization.propertyList(
        from: Data("bplist00".utf8), options: [], format: nil
    )
    fatalError("Truncated input accepted")
} catch {
}

The distinction between booleans and ordinary numbers is deliberate: both can appear as NSNumber after bridging to Foundation. Checking only intValue can let some incorrect conversions slip through. This example checks numeric values and boolean type identity; production validation should also reject real numbers in integer fields and enforce lower and upper bounds.

Run in CI and retain the samples

Use a separate directory for this run’s output, and block subsequent delivery steps if the script exits with a nonzero status. Pass the directory path from the job rather than having parallel jobs share fixed files.

set -eu
work="$(mktemp -d "${TMPDIR:-/tmp}/plist-contract.XXXXXX")"
xcrun swift PlistContract.swift "$work"
plutil -lint "$work/sample-xml.plist"
plutil -lint "$work/sample-binary.plist"

plutil provides a supplementary syntax check; it cannot replace field validation. You can delete the directory after a successful job. On failure, retain it as an access-restricted artifact. Samples must use synthetic data and must not contain real user configurations or credentials.

Compare results field by field, not by the hash of the entire file. Dictionary key order does not define application-level ordering, and XML and binary encodings naturally produce different bytes. If the application needs ordered entries, use an array explicitly.

Add rejection and compatibility cases

The truncated header above is only a minimal negative test case, not a substitute for testing other kinds of corruption. Once this is integrated into the project, add at least four more sets of fixtures:

  • Remove the end of a valid binary file. Reading must fail rather than return a partial configuration.
  • Delete a required field or give it the wrong type. Application-level validation must reject it even if the underlying parser succeeds.
  • Supply an older-version file. Verify that migration produces the expected field values, then save it and read it back once more.
  • Supply a file with a future version number. It must be explicitly rejected or handled through a read-only path, never silently overwritten using the older structure.

Do not assume a parser is defective simply because a file “still parses” after a random byte is changed. The changed byte may be part of a valid string value. Negative test cases need explicit structural or application-level expectations.

When reading external files, limit file size before parsing, then limit array element counts, string lengths, and nesting depth after parsing. Even a small file can contain a large number of tiny objects, so limiting disk bytes alone is not enough.

Include failure handling in final acceptance

When the app detects a corrupt file, preserve the original evidence before deciding whether to use in-memory defaults. Never immediately write the default configuration back to the original path in the same branch that handles the read failure. Otherwise, later investigation will find only a “normal” empty configuration.

Atomic writes reduce the chance of reading a partially written file, but they do not coordinate multiple writers or guarantee durability after power loss. If an extension and the main app can write concurrently, design write serialization or file coordination separately, and test contention independently.

The final acceptance criteria should be: both formats read back according to the contract; invalid types and corrupt samples are rejected; older-version migrations work repeatably; future-version files are not mistakenly overwritten; and the original file remains recoverable after a failure. Encoding these conditions in tests makes a format change reviewable rather than a one-off experiment dependent on the state of a local machine.

Frequently asked questions

Should XML and binary property lists have matching file hashes?

No. Formats, dictionary key ordering, and encoding details can differ. Parse each file and compare field types and values unless your protocol explicitly requires identical bytes.

Should a parse failure overwrite the file with defaults?

Preserve the original file and report the failure first. Use in-memory defaults or a controlled recovery path according to product policy rather than destroying recoverable data.

Rent a dedicated Mac mini for your self-hosted runner

The entire machine is dedicated to one customer, with prepaid daily, weekly, monthly, or quarterly plans. After payment, find the delivery details in the console. Your team manages system updates, Xcode versions, and runner processes.

Choose a Mac mini server

Set up runner access on a dedicated node

Choose a model and billing term. After payment, find the delivery details in the console. Your team manages system updates, Xcode versions, and runner processes.