Test iOS SQLite corruption handling on a cloud Mac
A fully green iOS regression run does not mean the app can handle a damaged local database. An unreadable file header or a dangling foreign key can send the startup flow down a different path. On a cloud Mac, turn these failures into repeatable test fixtures to verify whether the app offers recovery or silently deletes user data.
This walkthrough works only in a dedicated test directory. You need a working Python 3 installation, the system sqlite3 command, and an app test entry point that lets you inject a database path. No production data is required.
Define the scope of the checks
Start by separating “the database is healthy” into three distinct conclusions: the file structure is readable, foreign key references are valid, and business data meets the application’s rules. SQLite’s integrity_check checks page structure, indexes, and some constraints, but not foreign keys; foreign_key_check specifically reports foreign key violations.
Even if both checks pass, that does not prove that order statuses, balances, or business-data versions are correct. Those require separate test assertions; a single ok cannot replace them.
Do not automatically delete the database just to keep a test running. A failed check should lead to a controlled error path, and recovery operations must remain separate from the normal database-opening path.
Here, full checks establish a baseline for a small set of fixed fixtures. quick_check can provide faster screening, but it is not an equivalent substitute for a full index consistency check.
Create three types of fixtures
Run the following commands from the repository root. A new temporary directory prevents existing files from being overwritten; the final line prints the location of this run’s fixtures.
set -eu
FIXTURES="$(mktemp -d "${TMPDIR:-/tmp}/sqlite-fixtures.XXXXXX")"
sqlite3 "$FIXTURES/good.sqlite" '
PRAGMA foreign_keys=ON;
CREATE TABLE parent(id INTEGER PRIMARY KEY);
CREATE TABLE child(
id INTEGER PRIMARY KEY,
parent_id INTEGER NOT NULL REFERENCES parent(id)
);
INSERT INTO parent VALUES(1);
INSERT INTO child VALUES(1, 1);
'
cp "$FIXTURES/good.sqlite" "$FIXTURES/orphan.sqlite"
sqlite3 "$FIXTURES/orphan.sqlite" '
PRAGMA foreign_keys=OFF;
INSERT INTO child VALUES(2, 999);
'
cp "$FIXTURES/good.sqlite" "$FIXTURES/broken.sqlite"
printf 'BROKEN' | dd of="$FIXTURES/broken.sqlite" \
bs=1 count=6 conv=notrunc 2>/dev/null
printf '%s\n' "$FIXTURES"
good.sqlite should pass every check. orphan.sqlite has a valid page structure but references a parent record that does not exist. broken.sqlite has an overwritten file header and should not be readable as a valid database.
Disabling foreign keys is only a way to create a negative test case, not a recommended app setting. Every time the app opens a connection, it should explicitly enable foreign key enforcement and verify the setting.
These copies are made after the command processes have exited. Do not use this file-copying approach to capture a database that is being written to; active WAL snapshots are outside the scope of this experiment.
Build a read-only checker
Save the following as check_sqlite.py. The script requires the input file to exist, opens a read-only connection, and returns a nonzero exit code if a check fails. It does not attempt repairs.
import pathlib
import sqlite3
import sys
if len(sys.argv) != 2:
sys.stderr.write("Usage: check_sqlite.py DATABASE\n")
raise SystemExit(2)
path = pathlib.Path(sys.argv[1]).resolve()
if not path.is_file():
sys.stderr.write("Input file does not exist\n")
raise SystemExit(2)
connection = None
try:
connection = sqlite3.connect(path.as_uri() + "?mode=ro")
connection.execute("PRAGMA query_only=ON")
structure = connection.execute(
"PRAGMA integrity_check"
).fetchall()
relations = connection.execute(
"PRAGMA foreign_key_check"
).fetchall()
if structure != [("ok",)] or relations:
sys.stderr.write(
f"integrity={structure!r}; foreign_keys={relations!r}\n"
)
raise SystemExit(1)
sys.stdout.write("PASS\n")
except sqlite3.DatabaseError as error:
sys.stderr.write(f"Database check failed: {error}\n")
raise SystemExit(1)
finally:
if connection is not None:
connection.close()
Reading the full result set matters: checking only whether the query executed successfully, or looking only at the first row, is not enough. A foreign key check can execute successfully even when it finds violations.
Pass the fixture’s absolute path as an argument in your tests. Integrity checks can scan many pages, so run them in an offline validation task rather than on the app’s main thread at every startup.
Verify failure exit paths
Using the variable from the same terminal session, run the following three validation checks. If either negative test case unexpectedly passes, the command block must fail.
set -eu
python3 check_sqlite.py "$FIXTURES/good.sqlite"
if python3 check_sqlite.py "$FIXTURES/orphan.sqlite"; then
exit 1
fi
if python3 check_sqlite.py "$FIXTURES/broken.sqlite"; then
exit 1
fi
The pipeline should also verify separately that a nonexistent path returns exit code 2. Otherwise, a mistyped path could be mistaken for successful detection of database corruption. An invalid database returns 1; incorrect input or usage returns 2. Record these two failure categories separately.
The SQLite version used by Python may differ from the version in the app. Record sqlite3.sqlite_version, then open the fixtures again through the database wrapper the app actually uses. The host-side script provides screening, not a replacement for validation in the iOS runtime.
Add the fixtures to app regression tests
Add a database-path injection point to the test build. Copy each fixture into a temporary directory dedicated to that test case, then call the real data access layer. Do not let tests modify the fixed fixtures in the repository.
For the valid file, assert that reading succeeds. For the foreign key orphan, assert that the relationship check fails. For the damaged header, assert that opening the database or running the first query fails. Avoid matching the full text of system error messages; prefer assertions on the database error category and the app’s own stable error codes.
Finally, cover these four checks:
- The original database file still exists after failure; compare file hashes after closing all connections.
- The error path does not delete the database, rebuild it, or write default data.
- The UI does not present a database error as “No records.”
- A new database is created only after the user explicitly chooses to rebuild it, and the new database is verified to be readable.
Damaging the file header covers only one failure mode, not every kind of page corruption. First, make all three fixture types produce their expected results reliably in every regression run. Then add separate fixtures based on real failures. Each fixture should have a clearly defined expected outcome, rather than merely checking that the app does not crash.
Frequently asked questions
Does an ok result from integrity_check prove foreign keys are valid?
No. Run foreign_key_check separately. An empty result means that check found no foreign-key violations.
Can I damage a live database to test the error path?
Do not modify a live database. Create and close a dedicated fixture, then damage a copy. Active databases and their WAL files must not be altered for this test.
Rent a Mac for your testing cycle
Choose a dedicated physical Mac mini and rent by the day, week, month, or quarter. Your rental stops when it expires—no automatic renewal or charges.