// SPDX-License-Identifier: GPL-3.0-or-later import XCTest final class SoftwareLibraryLaunchPlanTests: XCTestCase { private var root: URL! private var working: URL { root.appendingPathComponent("Working") } private let sha = String(repeating: "a", count: 64) override func setUpWithError() throws { root = FileManager.default.temporaryDirectory.appendingPathComponent("LibraryLaunch-" + UUID().uuidString) try FileManager.default.createDirectory(at: working, withIntermediateDirectories: true) } override func tearDownWithError() throws { try? FileManager.default.removeItem(at: root) } @discardableResult private func file(_ path: String, bytes: Data = Data([1, 2, 3])) throws -> URL { let url = working.appendingPathComponent(path) try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true) try bytes.write(to: url); return url } private func receipt(_ paths: [String]) -> SoftwareLibraryInstallationReceipt { .init(releaseID: "release", packageSHA256: sha, installedAt: Date(), workingDirectory: working, relativeFiles: paths) } private func release(media: String = "disk", profile: String = "disk-basic", paths: [(String, String)] = [], command: String? = nil, extra: [String: LibraryJSON] = [:], status: String = "source-ready") -> SoftwareLibraryRelease { var configuration: [String: LibraryJSON] = ["profile": .string(profile), "processor": .string("6809"), "ram_kib": .number(2048), "controller_slot": .number(4), "video": .string("composite")] configuration.merge(extra, uniquingKeysWith: { _, newer in newer }) let setup = SoftwareLibrarySetup(status: status, command: command, instructions: "Mount the supplied media and follow its manual.", configuration: .object(configuration), selectedMembers: .array(paths.map { .object(["target": .string($0.0), "path": .string($0.1), "sha256": .string(sha)]) }), reasons: [], validation: .object([:])) return .init(id: "release", titleID: "title", name: "Example.zip", category: "Disks/Games", mediaType: media, contentRole: "software", sourceURL: URL(string: "https://colorcomputerarchive.com/Example.zip")!, modifiedAt: nil, modifiedPrecision: nil, modifiedTimezone: nil, packageSHA256: sha, byteSize: 100, languageStatus: "english", metadata: .object(["title": .string("Example")]), setup: setup, assets: [], downloadURLs: []) } func testPresentationDistinguishesKnownStartupFromManualOrAmbiguousSetup() { func automatic(_ item: SoftwareLibraryRelease) -> Bool { SoftwareLibraryLaunchPlan.hasAutomaticStartup(for: item) } XCTAssertTrue(automatic(release(media: "cartridge", profile: "rom-cartridge", paths: [("cartridge", "GAME.CCC")]))) XCTAssertTrue(automatic(release(paths: [("disk0", "GAME.DSK")], command: "LOADM\"GAME\":EXEC\r", status: "manual-setup"))) XCTAssertTrue(automatic(release(media: "cassette", paths: [("media", "GAME.cas")], command: "CLOADM\rEXEC\r"))) XCTAssertTrue(automatic(release(media: "sdc", profile: "coco-sdc", paths: [("disk0", "GAME.DSK")], command: "RUN\"AUTOEXEC:0\"\r"))) XCTAssertFalse(automatic(release(media: "cartridge", profile: "rom-cartridge", extra: ["launch_method": .string("cartridge-autostart")]))) XCTAssertFalse(automatic(release(media: "cartridge", profile: "rom-cartridge", paths: [("cartridge", "UNKNOWN.bin")]))) XCTAssertFalse(automatic(release(command: "RUN\"GAME\"\r"))) XCTAssertFalse(automatic(release(paths: [("disk0", "GAME.DSK")]))) XCTAssertFalse(automatic(release(paths: [("disk0", "GAME.DSK")], command: "DIR\r"))) XCTAssertFalse(automatic(release(paths: [("disk0", "GAME.DSK")], command: "RUN\rDIR\r"))) XCTAssertFalse(automatic(release(media: "hard-disk", profile: "hard-drive-basic", paths: [("hardDisk0", "GAME.vhd")], command: "DOS\r"))) XCTAssertFalse(automatic(release(paths: [("disk0", "GAME.vhd")], command: "DOS\r"))) } func testCartridgeAutostartsWithoutTypingAndHonorsItsStartupSlot() throws { try file("GAME.ccc") let plan = try SoftwareLibraryLaunchPlan.prepare(release: release(media: "cartridge", profile: "rom-cartridge", paths: [("cartridge", "GAME.ccc")], extra: ["cartridge_slot": .number(2)]), receipt: receipt(["GAME.ccc"])) XCTAssertTrue(plan.automaticallyStarts); XCTAssertTrue(plan.commands.isEmpty) XCTAssertEqual(plan.cartridgeURL?.lastPathComponent, "GAME.ccc"); XCTAssertEqual(plan.controllerSlot, 2) XCTAssertTrue(plan.floppyURLs.isEmpty); XCTAssertNil(plan.cassetteURL) try plan.validateMedia() } func testOrchestraCartridgeKeepsNativeDeviceAndUnknownDevicesAreNotGenericROMs() throws { try file("ORCH90.ccc") let orchestra = release(media: "cartridge", profile: "rom-cartridge", paths: [("cartridge", "ORCH90.ccc")], extra: ["cartridge_device": .string("orchestra90")]) let plan = try SoftwareLibraryLaunchPlan.prepare(release: orchestra, receipt: receipt(["ORCH90.ccc"])) XCTAssertEqual(plan.cartridgeDevice, .orchestra90) XCTAssertTrue(plan.automaticallyStarts) XCTAssertTrue(SoftwareLibraryLaunchPlan.hasAutomaticStartup(for: orchestra)) let plain = try SoftwareLibraryLaunchPlan.prepare(release: release(media: "cartridge", profile: "rom-cartridge", paths: [("cartridge", "ORCH90.ccc")]), receipt: receipt(["ORCH90.ccc"])) XCTAssertEqual(plain.cartridgeDevice, .rom) for device: LibraryJSON in [.string("game-master"), .number(5)] { let unsupported = release(media: "cartridge", profile: "rom-cartridge", paths: [("cartridge", "ORCH90.ccc")], extra: ["cartridge_device": device]) XCTAssertFalse(SoftwareLibraryLaunchPlan.hasAutomaticStartup(for: unsupported)) XCTAssertThrowsError(try SoftwareLibraryLaunchPlan.prepare(release: unsupported, receipt: receipt(["ORCH90.ccc"]))) } XCTAssertThrowsError(try SoftwareLibraryLaunchPlan.prepare(release: release(paths: [("disk0", "ORCH90.ccc")], extra: ["cartridge_device": .string("orchestra90")]), receipt: receipt(["ORCH90.ccc"]))) } func testDiskAppliesRecommendedProcessorRAMAndVideoWithoutDependingOnTestedStatus() throws { try file("Game/HELLO.DSK") let plan = try SoftwareLibraryLaunchPlan.prepare(release: release(paths: [("disk0", "Game/HELLO.DSK")], command: "LOADM\"HELLO\":EXEC\\r", extra: ["processor": .string("6309"), "ram_kib": .number(8192), "video": .string("rgb")], status: "manual-setup"), receipt: receipt(["Game/HELLO.DSK"])) XCTAssertTrue(plan.use6309); XCTAssertEqual(plan.ramIndex, 3); XCTAssertEqual(plan.ramKiB, 8192); XCTAssertEqual(plan.videoOutput, 0) XCTAssertEqual(plan.floppyURLs[0]?.lastPathComponent, "HELLO.DSK"); XCTAssertEqual(plan.commands, ["LOADM\"HELLO\":EXEC"]) XCTAssertTrue(plan.automaticallyStarts) } func testFD502RecipeAndManualSelectionAcceptTrackAndVDKImages() throws { let paths = ["FLEX.DMK", "Explorer.vdk"] for path in paths { try file(path) } let recipe = release(paths: [("disk0", paths[0]), ("disk3", paths[1])], command: "DOS\r") XCTAssertTrue(SoftwareLibraryLaunchPlan.hasAutomaticStartup(for: recipe)) let plan = try SoftwareLibraryLaunchPlan.prepare(release: recipe, receipt: receipt(paths)) XCTAssertEqual(plan.floppyURLs[0]?.lastPathComponent, paths[0]) XCTAssertEqual(plan.floppyURLs[3]?.lastPathComponent, paths[1]) for path in paths { let manual = try SoftwareLibraryLaunchPlan.prepare(release: release(status: "manual-setup"), receipt: receipt(paths), selectedMember: path) XCTAssertEqual(manual.floppyURLs[0]?.lastPathComponent, path) XCTAssertFalse(manual.automaticallyStarts) } XCTAssertFalse(SoftwareLibraryLaunchPlan.hasAutomaticStartup(for: release(media: "sdc", profile: "coco-sdc", paths: [("disk0", paths[0])], command: "DOS\r"))) } func testCassetteProducesSeparateLoadAndRunStepsForPromptSequencing() throws { try file("HELLO.cas") let plan = try SoftwareLibraryLaunchPlan.prepare(release: release(media: "cassette", paths: [("media", "HELLO.cas")], command: "CLOAD\rRUN\r"), receipt: receipt(["HELLO.cas"])) XCTAssertEqual(plan.commands, ["CLOAD", "RUN"]); XCTAssertTrue(plan.automaticallyStarts) XCTAssertNotNil(plan.cassetteURL); XCTAssertNil(plan.cartridgeURL) } func testSDCPreservesSiblingDisksAndMountsBeforeLoadingProgram() throws { try file("Double Dragon/DDRAGON1.DSK"); try file("Double Dragon/DDRAGON2.DSK") let plan = try SoftwareLibraryLaunchPlan.prepare(release: release(media: "sdc", profile: "coco-sdc", paths: [("disk0", "Double Dragon/DDRAGON1.DSK")], command: "RUN\"AUTOEXEC:0\"\\r", extra: ["sd_working_directory": .string("Double Dragon")]), receipt: receipt(["Double Dragon/DDRAGON1.DSK", "Double Dragon/DDRAGON2.DSK"])) XCTAssertEqual(plan.sdcFolderURL?.lastPathComponent, "Double Dragon") XCTAssertEqual(plan.sdcInitialImages, [0: "DDRAGON1.DSK"]) XCTAssertEqual(plan.commands, ["DRIVE 0,\"DDRAGON1.DSK\"", "RUN\"AUTOEXEC:0\""]) XCTAssertTrue(plan.floppyURLs.isEmpty); try plan.validateMedia() } func testAmbiguousManualMediaRequiresExplicitChoiceAndDoesNotGuessStartupCommand() throws { try file("ONE.DSK"); try file("TWO.DSK") let item = release(command: "RUN\"ONE\"\\r", status: "manual-setup") XCTAssertThrowsError(try SoftwareLibraryLaunchPlan.prepare(release: item, receipt: receipt(["ONE.DSK", "TWO.DSK"]))) { error in guard case SoftwareLibraryLaunchPlan.Failure.needsSelection(let choices) = error else { return XCTFail("Expected a media selection") } XCTAssertEqual(choices.map(\.path), ["ONE.DSK", "TWO.DSK"]) } let plan = try SoftwareLibraryLaunchPlan.prepare(release: item, receipt: receipt(["ONE.DSK", "TWO.DSK"]), selectedMember: "TWO.DSK") XCTAssertEqual(plan.floppyURLs[0]?.lastPathComponent, "TWO.DSK") XCTAssertFalse(plan.automaticallyStarts); XCTAssertTrue(plan.commands.isEmpty) XCTAssertThrowsError(try SoftwareLibraryLaunchPlan.prepare(release: item, receipt: receipt(["ONE.DSK", "TWO.DSK"]), selectedMember: "../ONE.DSK")) } func testSingleManualDiskMountsForGuidanceAndSingleCCCStillAutostarts() throws { try file("GAME.DSK"); try file("GAME.ccc") let disk = try SoftwareLibraryLaunchPlan.prepare(release: release(status: "manual-setup"), receipt: receipt(["GAME.DSK"])) XCTAssertFalse(disk.automaticallyStarts); XCTAssertTrue(disk.commands.isEmpty); XCTAssertNotNil(disk.floppyURLs[0]) let cart = try SoftwareLibraryLaunchPlan.prepare(release: release(media: "cartridge", profile: "rom-cartridge", status: "manual-setup"), receipt: receipt(["GAME.ccc"])) XCTAssertTrue(cart.automaticallyStarts) } func testWorkingSavesAreNotRejectedByOriginalMemberFingerprint() throws { let media = try file("GAME.DSK") try Data([9, 8, 7, 6]).write(to: media) let plan = try SoftwareLibraryLaunchPlan.prepare(release: release(paths: [("disk0", "GAME.DSK")], command: "DOS\\r"), receipt: receipt(["GAME.DSK"])) XCTAssertTrue(plan.automaticallyStarts); try plan.validateMedia() XCTAssertEqual(try Data(contentsOf: media), Data([9, 8, 7, 6])) } func testUnsafeOrMissingSelectedMediaNeverProducesPlan() throws { try file("GAME.DSK") for path in ["../Original/GAME.DSK", "/GAME.DSK", "folder/../GAME.DSK", "GAME.DSK:stream", "absent.DSK"] { XCTAssertThrowsError(try SoftwareLibraryLaunchPlan.prepare(release: release(paths: [("disk0", path)]), receipt: receipt([path]))) } let outside = root.appendingPathComponent("outside.DSK"); try Data([8]).write(to: outside) try FileManager.default.removeItem(at: working.appendingPathComponent("GAME.DSK")) try FileManager.default.createSymbolicLink(at: working.appendingPathComponent("GAME.DSK"), withDestinationURL: outside) XCTAssertThrowsError(try SoftwareLibraryLaunchPlan.prepare(release: release(paths: [("disk0", "GAME.DSK")]), receipt: receipt(["GAME.DSK"]))) } func testRevalidationRejectsReplacementLinkAndSDCSiblingLink() throws { let media = try file("GAME.DSK") let plan = try SoftwareLibraryLaunchPlan.prepare(release: release(paths: [("disk0", "GAME.DSK")]), receipt: receipt(["GAME.DSK"])) try FileManager.default.removeItem(at: media) let outside = root.appendingPathComponent("outside.DSK"); try Data([1]).write(to: outside) try FileManager.default.createSymbolicLink(at: media, withDestinationURL: outside) XCTAssertThrowsError(try plan.validateMedia()) try FileManager.default.removeItem(at: media); try file("GAME.DSK") let sdc = try SoftwareLibraryLaunchPlan.prepare(release: release(media: "sdc", profile: "coco-sdc", paths: [("disk0", "GAME.DSK")]), receipt: receipt(["GAME.DSK"])) try FileManager.default.createSymbolicLink(at: working.appendingPathComponent("escape"), withDestinationURL: root) XCTAssertThrowsError(try sdc.validateMedia()) } func testMalformedRecommendationsAndConflictingTargetsAreRejected() throws { try file("GAME.DSK") for extra: [String: LibraryJSON] in [["processor": .string("x86")], ["processor": .number(6809)], ["ram_kib": .number(4096)], ["ram_kib": .string("2048")], ["controller_slot": .number(0)], ["controller_slot": .bool(true)], ["video": .string("shell")]] { XCTAssertThrowsError(try SoftwareLibraryLaunchPlan.prepare(release: release(paths: [("disk0", "GAME.DSK")], extra: extra), receipt: receipt(["GAME.DSK"]))) } XCTAssertThrowsError(try SoftwareLibraryLaunchPlan.prepare(release: release(paths: [("disk0", "GAME.DSK"), ("disk0", "GAME.DSK")]), receipt: receipt(["GAME.DSK"]))) XCTAssertThrowsError(try SoftwareLibraryLaunchPlan.prepare(release: release(paths: [("execute-host", "GAME.DSK")]), receipt: receipt(["GAME.DSK"]))) let mismatched = SoftwareLibraryInstallationReceipt(releaseID: "other", packageSHA256: sha, installedAt: Date(), workingDirectory: working, relativeFiles: ["GAME.DSK"]) XCTAssertThrowsError(try SoftwareLibraryLaunchPlan.prepare(release: release(paths: [("disk0", "GAME.DSK")]), receipt: mismatched)) } func testUnknownCommandsRemainManualAndBinaryFilesAreNotGuessedAsCartridges() throws { try file("GAME.DSK"); try file("PROGRAM.bin") let plan = try SoftwareLibraryLaunchPlan.prepare(release: release(paths: [("disk0", "GAME.DSK")], command: "SYSTEM \"curl example.invalid\"\\r"), receipt: receipt(["GAME.DSK"])) XCTAssertFalse(plan.automaticallyStarts); XCTAssertTrue(plan.commands.isEmpty) XCTAssertTrue(plan.manualInstructions.contains("manual entry")) XCTAssertThrowsError(try SoftwareLibraryLaunchPlan.prepare(release: release(media: "cartridge", profile: "rom-cartridge"), receipt: receipt(["PROGRAM.bin"]))) } func testDoesNotTypeAnotherLineAfterStartingGuestSoftware() throws { for command in ["RUN\"GAME\"\rDIR\r", "EXEC\rRUN\r", "DOS\rNEW\r", "LOAD \"BOOT\", R\rEXEC\r"] { XCTAssertNil(SoftwareLibraryLaunchPlan.decodeCommands(command), command) } XCTAssertEqual(SoftwareLibraryLaunchPlan.decodeCommands("RUN\"INTRO\":EXEC\r"), ["RUN\"INTRO\":EXEC"]) XCTAssertEqual(SoftwareLibraryLaunchPlan.decodeCommands("LOADM\"JUNGLE\":EXEC:LOADM\"JUNGLE2\":EXEC\r"), ["LOADM\"JUNGLE\":EXEC:LOADM\"JUNGLE2\":EXEC"]) try file("GAME.DSK") let plan = try SoftwareLibraryLaunchPlan.prepare(release: release(paths: [("disk0", "GAME.DSK")], command: "RUN\"GAME\"\rDIR\r"), receipt: receipt(["GAME.DSK"])) XCTAssertFalse(plan.automaticallyStarts) XCTAssertTrue(plan.commands.isEmpty) XCTAssertNotNil(plan.floppyURLs[0]) } func testCommandGrammarHandlesQuotedColonAndRejectsDoubleEscapesAndControls() { XCTAssertEqual(SoftwareLibraryLaunchPlan.decodeCommands("RUN\"AUTOEXEC:0\"\\r"), ["RUN\"AUTOEXEC:0\""]) XCTAssertEqual(SoftwareLibraryLaunchPlan.decodeCommands("CLOADM\\rEXEC\\r"), ["CLOADM", "EXEC"]) XCTAssertEqual(SoftwareLibraryLaunchPlan.decodeCommands("PCLEAR1:RUN\"FIRE&GAS\"\r"), ["PCLEAR1:RUN\"FIRE&GAS\""]) XCTAssertEqual(SoftwareLibraryLaunchPlan.decodeCommands("LOAD CHR$(42),R\\r"), ["LOAD CHR$(42),R"]) for command in ["RUN\"broken", "RUN\"A\"\u{1b}", "RUN\\\"A\\\"\\r", "RUN\"A\":FORMAT\"B\"", "RUN\"A\\B\"", String(repeating: "RUN\r", count: 20)] { XCTAssertNil(SoftwareLibraryLaunchPlan.decodeCommands(command), command) } } }