257 lines
16 KiB
Swift
257 lines
16 KiB
Swift
// SPDX-License-Identifier: GPL-3.0-or-later
|
|
import XCTest
|
|
import SwiftUI
|
|
import AppKit
|
|
|
|
private actor SaveGate {
|
|
private var release: CheckedContinuation<Void, Never>?
|
|
private(set) var started = false
|
|
func wait() async { started = true; await withCheckedContinuation { release = $0 } }
|
|
func open() { release?.resume(); release = nil }
|
|
}
|
|
|
|
final class DiskAutosaveTests: XCTestCase {
|
|
private struct Fixture {
|
|
let folder: URL, disk: URL, store: DiskAssignmentStore
|
|
let original = Data(repeating: 0, count: 161280)
|
|
init(temporary: Bool = false, protected: Bool = false) throws {
|
|
folder = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
|
|
try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
|
|
disk = folder.appendingPathComponent("Autosave é.DSK")
|
|
try original.write(to: disk)
|
|
let rom = folder.appendingPathComponent("authored.rom")
|
|
try Data(repeating: 0, count: 8192).write(to: rom)
|
|
store = DiskAssignmentStore(url: folder.appendingPathComponent("settings.json"))
|
|
var settings = DiskAssignments(); settings.rom = rom
|
|
settings.drives[0] = .init(url: disk, writeProtected: protected, temporary: temporary)
|
|
try store.save(settings)
|
|
}
|
|
func remove() { try? FileManager.default.removeItem(at: folder) }
|
|
}
|
|
// Authored code shared by both CPU engines: fill sector 1, commit, then loop.
|
|
private func writerROM(_ value: UInt8 = 0x5a, repeating: Bool = false) -> Data {
|
|
var program: [UInt8] = [0x86,0x29,0xb7,0xff,0x40,0x86,1,0xb7,0xff,0x4a,
|
|
0x86,0xa0,0xb7,0xff,0x48,0x8e,1,0,0x86,value,
|
|
0xb7,0xff,0x4b,0x30,0x1f,0x26,0xf9,0xb7,0xff,0x4b,0x20,0xfe]
|
|
if repeating {
|
|
program.removeLast(2)
|
|
// Idle between writes so the controller can capture complete sectors.
|
|
program += [0x8e,0x40,0x00,0x30,0x1f,0x26,0xfc]
|
|
let back = UInt8(bitPattern: Int8(-(program.count + 2)))
|
|
program += [0x20, back]
|
|
}
|
|
var rom = Data(repeating: 0, count: 32768); rom.replaceSubrange(0..<program.count, with: program)
|
|
rom[32766] = 0x80; return rom
|
|
}
|
|
@MainActor private func step(_ action: (@escaping @Sendable (VCCMachineSnapshot) -> Void) -> Void) async -> VCCMachineSnapshot {
|
|
await withCheckedContinuation { continuation in action { continuation.resume(returning: $0) } }
|
|
}
|
|
@MainActor private func until(_ condition: () -> Bool) async throws {
|
|
for _ in 0..<500 {
|
|
if condition() { return }
|
|
try await Task.sleep(nanoseconds: 20_000_000)
|
|
}
|
|
XCTFail("Timed out waiting for disk saving")
|
|
throw NSError(domain: "TestTimeout", code: 1)
|
|
}
|
|
@MainActor private func settled(_ model: MachineModel) async throws {
|
|
try await until { !model.busy && !model.diskSaving }
|
|
}
|
|
@MainActor private func close(_ model: MachineModel) async {
|
|
await withCheckedContinuation { continuation in model.shutdown { continuation.resume() } }
|
|
}
|
|
@MainActor private func runWriter(_ controller: VCCMachineController, use6309: Bool = false, value: UInt8 = 0x5a) async {
|
|
let s = await step { controller.loadROM(writerROM(value), use6309: use6309, completion: $0) }
|
|
XCTAssertNil(s.errorMessage)
|
|
_ = await step(controller.resume)
|
|
}
|
|
func testAutomaticFileWriteRejectsConflictsMissingAndReadOnlyFiles() throws {
|
|
let f = try Fixture(); defer { f.remove() }
|
|
let changed = Data(repeating: 0x5a, count: 161280)
|
|
try DiskFiles.saveAutomatically(changed, to: f.disk, expected: f.original)
|
|
XCTAssertEqual(try Data(contentsOf: f.disk), changed)
|
|
XCTAssertThrowsError(try DiskFiles.saveAutomatically(f.original, to: f.disk, expected: f.original))
|
|
XCTAssertEqual(try Data(contentsOf: f.disk), changed)
|
|
try FileManager.default.setAttributes([.posixPermissions: 0o444], ofItemAtPath: f.disk.path)
|
|
XCTAssertThrowsError(try DiskFiles.saveAutomatically(f.original, to: f.disk, expected: changed))
|
|
XCTAssertEqual(try Data(contentsOf: f.disk), changed)
|
|
try FileManager.default.removeItem(at: f.disk)
|
|
XCTAssertThrowsError(try DiskFiles.saveAutomatically(changed, to: f.disk, expected: changed))
|
|
XCTAssertFalse(FileManager.default.fileExists(atPath: f.disk.path))
|
|
let target = f.folder.appendingPathComponent("image-without-extension")
|
|
try f.original.write(to: target)
|
|
try FileManager.default.createSymbolicLink(at: f.disk, withDestinationURL: target)
|
|
try DiskFiles.saveAutomatically(changed, to: f.disk.resolvingSymlinksInPath(), expected: f.original)
|
|
XCTAssertEqual(try Data(contentsOf: target), changed)
|
|
XCTAssertEqual(try FileManager.default.destinationOfSymbolicLink(atPath: f.disk.path), target.path)
|
|
}
|
|
func testOlderSettingsDefaultToAutomaticSaving() throws {
|
|
let f = try Fixture(temporary: true); defer { f.remove() }
|
|
var json = try XCTUnwrap(JSONSerialization.jsonObject(with: Data(contentsOf: f.store.url)) as? [String: Any])
|
|
var drives = try XCTUnwrap(json["drives"] as? [Any])
|
|
var first = try XCTUnwrap(drives[0] as? [String: Any]); first.removeValue(forKey: "temporary")
|
|
drives[0] = first; json["drives"] = drives
|
|
try JSONSerialization.data(withJSONObject: json).write(to: f.store.url)
|
|
XCTAssertFalse(try XCTUnwrap(f.store.load().drives[0]).temporary)
|
|
}
|
|
@MainActor func testGuestWritesSaveWithoutPausingOnBothCPUs() async throws {
|
|
for (cpu, mpi) in [(false, false), (true, false), (false, true), (true, true)] {
|
|
let f = try Fixture(); defer { f.remove() }
|
|
if mpi {
|
|
var settings = try f.store.load(); var layout = CartridgeAssignments()
|
|
layout.multiPak = true; layout.mpiConfigured = true; layout.slots[4].kind = .floppy
|
|
settings.cartridges = layout; try f.store.save(settings)
|
|
}
|
|
let controller = VCCMachineController(); let model = MachineModel(diskStore: f.store, controller: controller)
|
|
do {
|
|
try await settled(model); await runWriter(controller, use6309: cpu)
|
|
try await until { (try? Data(contentsOf: f.disk).first) == 0x5a && !model.diskSaving && !model.disks[0].dirty }
|
|
XCTAssertEqual(model.state, .running); XCTAssertTrue(model.diskSaveErrors.isEmpty)
|
|
let bytes = try Data(contentsOf: f.disk)
|
|
XCTAssertEqual(bytes.prefix(256), Data(repeating: 0x5a, count: 256))
|
|
XCTAssertEqual(bytes.dropFirst(256), f.original.dropFirst(256))
|
|
} catch { await close(model); throw error }
|
|
await close(model)
|
|
let reopened = MachineModel(diskStore: f.store)
|
|
try await settled(reopened); XCTAssertTrue(reopened.disks[0].mounted); XCTAssertFalse(reopened.disks[0].dirty)
|
|
await close(reopened)
|
|
}
|
|
}
|
|
@MainActor func testTemporaryModeAndProtectionKeepSourceUnchanged() async throws {
|
|
for protected in [false, true] {
|
|
let f = try Fixture(temporary: !protected, protected: protected); defer { f.remove() }
|
|
let controller = VCCMachineController(); let model = MachineModel(diskStore: f.store, controller: controller)
|
|
do {
|
|
try await settled(model); XCTAssertEqual(model.diskTemporary[0], !protected)
|
|
await runWriter(controller)
|
|
try await until { model.frames > 20 }
|
|
await withCheckedContinuation { continuation in model.prepareToQuit { continuation.resume() } }
|
|
XCTAssertEqual(try Data(contentsOf: f.disk), f.original)
|
|
XCTAssertEqual(model.disks[0].dirty, !protected)
|
|
XCTAssertEqual(model.unsavedMedia, !protected)
|
|
XCTAssertEqual(model.needsMediaAttention, !protected, "Temporary changes must still need attention")
|
|
if !protected {
|
|
model.setDiskTemporary(0, false); try await settled(model)
|
|
XCTAssertFalse(try XCTUnwrap(f.store.load().drives[0]).temporary)
|
|
await withCheckedContinuation { continuation in model.prepareToQuit { continuation.resume() } }
|
|
XCTAssertFalse(model.unsavedMedia); XCTAssertEqual(try Data(contentsOf: f.disk).first, 0x5a)
|
|
}
|
|
} catch { await close(model); throw error }
|
|
await close(model)
|
|
}
|
|
}
|
|
@MainActor func testExternalEditPausesAndRetainsChangesUntilRetry() async throws {
|
|
let f = try Fixture(); defer { f.remove() }
|
|
let controller = VCCMachineController(); let model = MachineModel(diskStore: f.store, controller: controller)
|
|
do {
|
|
try await settled(model)
|
|
let external = Data(repeating: 7, count: 161280); try external.write(to: f.disk)
|
|
await runWriter(controller)
|
|
try await until { model.diskSaveErrors[0] != nil && !model.diskSaving }
|
|
XCTAssertEqual(model.state, .paused); XCTAssertTrue(model.disks[0].dirty)
|
|
XCTAssertTrue(model.needsMediaAttention, "Real autosave failures must remain visible")
|
|
XCTAssertEqual(try Data(contentsOf: f.disk), external)
|
|
await withCheckedContinuation { continuation in model.prepareToQuit { continuation.resume() } }
|
|
XCTAssertTrue(model.unsavedMedia); XCTAssertEqual(try Data(contentsOf: f.disk), external)
|
|
try f.original.write(to: f.disk)
|
|
model.retryDiskSave(0)
|
|
try await until { !model.diskSaving && !model.disks[0].dirty }
|
|
XCTAssertTrue(model.diskSaveErrors.isEmpty); XCTAssertEqual(try Data(contentsOf: f.disk).first, 0x5a)
|
|
XCTAssertFalse(model.needsMediaAttention)
|
|
} catch { await close(model); throw error }
|
|
await close(model)
|
|
}
|
|
@MainActor func testRepeatedWritesKeepAttentionAndNativeDisplayStable() async throws {
|
|
let f = try Fixture(); defer { f.remove() }
|
|
var assignments = try f.store.load()
|
|
var layout = CartridgeAssignments(); layout.multiPak = true; layout.mpiConfigured = true
|
|
layout.slots[4].kind = .floppy; assignments.cartridges = layout; try f.store.save(assignments)
|
|
let suite = "VCCRepeatedWrites-" + UUID().uuidString
|
|
let defaults = UserDefaults(suiteName: suite)!
|
|
defer { defaults.removePersistentDomain(forName: suite) }
|
|
let controller = VCCMachineController(), gate = SaveGate()
|
|
let model = MachineModel(diskStore: f.store, controller: controller, displayDefaults: defaults,
|
|
inputStore: .init(url: f.folder.appendingPathComponent("input.json")),
|
|
automaticDiskWriter: { data, url, expected in
|
|
if !(await gate.started) { await gate.wait() }
|
|
try DiskFiles.saveAutomatically(data, to: url, expected: expected)
|
|
})
|
|
let presentation = PresentationSettings(defaults: defaults)
|
|
let host = NSHostingView(rootView: MachineView(machine: model, presentation: presentation, showManualHome: {}))
|
|
let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 1100, height: 820),
|
|
styleMask: [.titled, .resizable], backing: .buffered, defer: false)
|
|
window.isReleasedWhenClosed = false; window.contentView = host
|
|
defer { window.close() }
|
|
func display(_ view: NSView) -> KeyboardDisplay? {
|
|
if let result = view as? KeyboardDisplay { return result }
|
|
return view.subviews.lazy.compactMap { display($0) }.first
|
|
}
|
|
do {
|
|
try await settled(model)
|
|
XCTAssertFalse(model.hardware.custom, "System checks must use the illustrated layout, not its conventional fallback")
|
|
_ = await step { controller.loadROM(writerROM(repeating: true), use6309: false, completion: $0) }
|
|
for mode in [PresentationSettings.Mode.display, .system] {
|
|
presentation.mode = mode
|
|
try await Task.sleep(nanoseconds: 100_000_000); host.layoutSubtreeIfNeeded()
|
|
let screen = try XCTUnwrap(display(host))
|
|
let original = screen.convert(screen.bounds, to: host)
|
|
_ = await step(controller.resume)
|
|
for _ in 0..<500 { if await gate.started { break }; try await Task.sleep(nanoseconds: 10_000_000) }
|
|
let started = await gate.started; XCTAssertTrue(started)
|
|
let before = await step(controller.snapshot)
|
|
for _ in 0..<30 {
|
|
model.poll(); try await Task.sleep(nanoseconds: 20_000_000)
|
|
host.layoutSubtreeIfNeeded()
|
|
XCTAssertTrue(model.unsavedMedia, "Quit protection must include pending host writes")
|
|
XCTAssertFalse(model.needsMediaAttention, "Normal repeated saves must not toggle a warning row")
|
|
XCTAssertEqual(screen.convert(screen.bounds, to: host), original, "Disk activity must not resize the live display")
|
|
}
|
|
let after = await step(controller.snapshot)
|
|
XCTAssertGreaterThan(after.frames, before.frames)
|
|
XCTAssertGreaterThan(after.disks[0].writeEvents, before.disks[0].writeEvents)
|
|
XCTAssertEqual(after.generation, before.generation)
|
|
_ = await step(controller.pause)
|
|
}
|
|
await gate.open()
|
|
await withCheckedContinuation { done in model.prepareToQuit { done.resume() } }
|
|
XCTAssertFalse(model.unsavedMedia); XCTAssertFalse(model.needsMediaAttention)
|
|
XCTAssertEqual(try Data(contentsOf: f.disk).prefix(256), Data(repeating: 0x5a, count: 256))
|
|
} catch { await gate.open(); await close(model); throw error }
|
|
await close(model)
|
|
}
|
|
@MainActor func testQuitWaitsForPendingSaveAndFlushesNewerGuestWrites() async throws {
|
|
let f = try Fixture(); defer { f.remove() }
|
|
let controller = VCCMachineController(); let gate = SaveGate()
|
|
let model = MachineModel(diskStore: f.store, controller: controller, automaticDiskWriter: { data, url, expected in
|
|
if !(await gate.started) { await gate.wait() }
|
|
try DiskFiles.saveAutomatically(data, to: url, expected: expected)
|
|
})
|
|
do {
|
|
try await settled(model); await runWriter(controller)
|
|
for _ in 0..<500 {
|
|
if await gate.started { break }
|
|
try await Task.sleep(nanoseconds: 20_000_000)
|
|
}
|
|
let started = await gate.started; XCTAssertTrue(started); XCTAssertTrue(model.diskSaving)
|
|
XCTAssertEqual(try Data(contentsOf: f.disk), f.original)
|
|
// Write a newer version while the first snapshot's host write waits.
|
|
await runWriter(controller, value: 0x6b)
|
|
let start = await step(controller.snapshot)
|
|
for _ in 0..<100 {
|
|
let s = await step(controller.snapshot)
|
|
if s.frames > start.frames + 2 { break }
|
|
try await Task.sleep(nanoseconds: 20_000_000)
|
|
}
|
|
var quitReady = false
|
|
model.prepareToQuit { quitReady = true }
|
|
try await Task.sleep(nanoseconds: 50_000_000)
|
|
XCTAssertFalse(quitReady, "Quit must wait for outstanding file I/O")
|
|
await gate.open()
|
|
try await until { quitReady }
|
|
XCTAssertFalse(model.unsavedMedia); XCTAssertEqual(model.state, .paused)
|
|
XCTAssertEqual(try Data(contentsOf: f.disk).prefix(256), Data(repeating: 0x6b, count: 256))
|
|
} catch { await gate.open(); await close(model); throw error }
|
|
await close(model)
|
|
}
|
|
}
|