import Foundation import ParcelIPC import Synchronization import Testing @testable import prcl @Suite("Setup CLI parsing") struct SetupCLIParsingTests { @Test(arguments: [ ["setup"], ["setup", "list"], ["setup", "list", "--json"], ["setup", "--json"], ["setup", "--json", "list"], ]) func listsUseSetupQuery(arguments: [String]) throws { let invocation = try CLIParsing.parse(arguments) #expect( invocation == .request( command: "query", args: ["setups"], query: .setups, json: arguments.contains("--json"))) let request = try #require(invocation.request) #expect(request.command == "query") #expect(request.args == ["setups"]) #expect(request.v == IPCProtocol.version) } @Test(arguments: ["save", "open", "delete"], ["Design work", "東京", " Keep spaces ", "a\"b\\c"]) func mutationsPreserveOneName(action: String, name: String) throws { let expected = CLIInvocation.request(command: "setup-" + action, args: [name], query: nil, json: false) #expect(try CLIParsing.parse(["setup", action, name]) == expected) #expect( try CLIParsing.parse(["setup", action, name, "--json"]) == .request(command: "setup-" + action, args: [name], query: nil, json: true)) #expect( try CLIParsing.parse(["setup", action, "--json", name]) == .request(command: "setup-" + action, args: [name], query: nil, json: true)) #expect( try CLIParsing.parse(["setup", "--json", action, name]) == .request(command: "setup-" + action, args: [name], query: nil, json: true)) } @Test(arguments: [ ["setup", "save", "Design work", "--no-hide", "--json"], ["setup", "save", "--no-hide", "Design work", "--json"], ["setup", "save", "--json", "--no-hide", "Design work"], ]) func noHideIsAnExplicitSaveArgument(arguments: [String]) throws { #expect( try CLIParsing.parse(arguments) == .request(command: "setup-save", args: ["Design work", "no-hide"], query: nil, json: true)) } @Test func flagLikeNamesCanUseArgumentTerminator() throws { #expect( try CLIParsing.parse(["setup", "save", "--", "--no-hide"]) == .request(command: "setup-save", args: ["--no-hide"], query: nil, json: false)) } @Test(arguments: [ ["setup", "unknown"], ["setup", "list", "extra"], ["setup", "list", "--no-hide"], ["setup", "save"], ["setup", "save", "--no-hide"], ["setup", "save", ""], ["setup", "save", " \n\t"], ["setup", "save", "Design", "work"], ["setup", "open"], ["setup", "open", ""], ["setup", "open", " "], ["setup", "open", "Design", "work"], ["setup", "open", "Design work", "--no-hide"], ["setup", "delete"], ["setup", "delete", ""], ["setup", "delete", " "], ["setup", "delete", "Design", "work"], ["setup", "delete", "Design work", "--no-hide"], ["setup", "save", "Design work", "--unknown"], ["setup", "list", "--unknown"], ]) func invalidArgumentsFailWithAVisibleMessage(arguments: [String]) { do { _ = try CLIParsing.parse(arguments) Issue.record("Expected invalid setup arguments to fail: \(arguments)") } catch { #expect(ParcelCLI.exitCode(for: error).rawValue != 0) #expect(!ParcelCLI.fullMessage(for: error).isEmpty) } } @Test func setupHelpDocumentsNamesAndNoHide() { let help = SetupCommand.helpMessage() #expect(help.contains("list")) #expect(help.contains("save")) #expect(help.contains("open")) #expect(help.contains("delete")) let saveHelp = SetupSaveCommand.helpMessage() #expect(saveHelp.contains("--no-hide")) #expect(saveHelp.contains("--json")) #expect(saveHelp.contains("Quote names containing spaces")) } } @Suite("Setup IPC contract") struct SetupIPCContractTests { @Test func listRequestUsesTheVersionedGenericEnvelope() throws { let request = SetupIPC.listRequest(id: .integer(42)) #expect(request.command == "query") #expect(request.args == ["setups"]) #expect( String(data: try IPCCodec.encode(request), encoding: .utf8) == "{\"args\":[\"setups\"],\"command\":\"query\",\"id\":42,\"v\":1}\n") } @Test(arguments: SetupIPC.Mutation.allCases) func mutationRequestKeepsTheNameIntact(mutation: SetupIPC.Mutation) throws { let request = try mutation.request(name: "Design work", id: .integer(7)) #expect(request.command == mutation.rawValue) #expect(request.args == ["Design work"]) #expect(request.id == .integer(7)) #expect(request.v == IPCProtocol.version) #expect(try IPCCodec.decode(IPCRequest.self, from: IPCCodec.encode(request)) == request) } @Test func noHideOnlyChangesSaveArguments() throws { #expect( try SetupIPC.Mutation.save.request(name: "Design work", noHide: true).args == ["Design work", "no-hide"]) } @Test(arguments: [SetupIPC.Mutation.open, .delete]) func otherMutationsRejectNoHide(mutation: SetupIPC.Mutation) { #expect(throws: IPCError.self) { try mutation.request(name: "Design work", noHide: true) } } @Test(arguments: SetupIPC.Mutation.allCases, ["", " \n\t"]) func mutationRequestsRejectEmptyNames(mutation: SetupIPC.Mutation, name: String) { #expect(throws: IPCError.self) { try mutation.request(name: name) } } } @Suite("Setup CLI local socket", .timeLimit(.minutes(1))) struct SetupCLISocketTests { @Test(arguments: [false, true]) func listPrintsNamedRecordsAndKeepsJSONIntact(json: Bool) async throws { let rows: JSONValue = .array([ .object(["name": .string("Design work"), "hideOtherApps": .bool(false)]), .object(["name": .string("東京"), "hideOtherApps": .bool(true)]), ]) let result: JSONValue = .object(["setups": rows]) try await withSetupServer(result: result) { handler, path in let output = Mutex("") let invocation = try CLIParsing.parse(["setup", "list"] + (json ? ["--json"] : [])) try await CLIRunner.execute(invocation, socketPath: path) { text in output.withLock { $0 += text } } let text = output.withLock { $0 } if json { #expect(try IPCCodec.decode(JSONValue.self, from: Data(text.utf8)) == result) #expect(text.split(separator: "\n").count == 1) } else { #expect(text.contains("Name")) #expect(text.contains("Design work")) #expect(text.contains("東京")) #expect(text.contains("hideOtherApps")) #expect(text.contains("Yes")) #expect(text.contains("No")) } #expect(await handler.invocations == [.init(command: "query", args: ["setups"])]) } } @Test func emptyListHasAReadableMessage() async throws { try await withSetupServer(result: .object(["setups": .array([])])) { _, path in let output = Mutex("") try await CLIRunner.execute(CLIParsing.parse(["setup", "list"]), socketPath: path) { text in output.withLock { $0 += text } } #expect(output.withLock { $0 } == "No setups.\n") } } @Test(arguments: ["save", "delete"], [false, true]) func successfulMutationsHaveOutputAndUseDirectCommands(action: String, json: Bool) async throws { try await withSetupServer(result: .null) { handler, path in let output = Mutex("") let arguments = ["setup", action, "Design work"] + (json ? ["--json"] : []) try await CLIRunner.execute(CLIParsing.parse(arguments), socketPath: path) { text in output.withLock { $0 += text } } #expect(output.withLock { $0 } == (json ? "null\n" : "Done.\n")) #expect(await handler.invocations == [.init(command: "setup-" + action, args: ["Design work"])]) } } @Test(arguments: ["save", "open", "delete"]) func canonicallyDecomposedNamesReachTheAppUnchanged(action: String) async throws { let name = " cAFE\u{301} " try await withSetupServer(result: .null) { handler, path in try await CLIRunner.execute(CLIParsing.parse(["setup", action, name]), socketPath: path) { _ in } let invocation = try #require(await handler.invocations.first) #expect(invocation.command == "setup-" + action) let received = try #require(invocation.args.first) #expect(Array(received.utf8) == Array(name.utf8)) } } @Test func noHideReachesTheSaveHandler() async throws { try await withSetupServer(result: .null) { handler, path in let output = Mutex("") try await CLIRunner.execute( CLIParsing.parse(["setup", "save", "Design work", "--no-hide"]), socketPath: path ) { text in output.withLock { $0 += text } } #expect(output.withLock { $0 } == "Done.\n") #expect(await handler.invocations == [.init(command: "setup-save", args: ["Design work", "no-hide"])]) } } @Test(arguments: [false, true]) func openPreservesNativeLaunchReceipts(json: Bool) async throws { let result: JSONValue = .object([ "accepted": .bool(true), "launches": .array([.object(["bundleID": .string("dev.example.Editor"), "pid": .integer(42)])]), ]) try await withSetupServer(result: result) { handler, path in let output = Mutex("") let arguments = ["setup", "open", "Design work"] + (json ? ["--json"] : []) try await CLIRunner.execute(CLIParsing.parse(arguments), socketPath: path) { text in output.withLock { $0 += text } } let text = output.withLock { $0 } if json { #expect(try IPCCodec.decode(JSONValue.self, from: Data(text.utf8)) == result) } else { #expect(text.contains("accepted")) #expect(text.contains("Yes")) #expect(text.contains("launches")) #expect(text.contains("dev.example.Editor")) #expect(text.contains("42")) } #expect(await handler.invocations == [.init(command: "setup-open", args: ["Design work"])]) } } @Test(arguments: ["list", "save", "open", "delete"], [false, true]) func rejectedCommandsFailWithoutSuccessOutput(action: String, json: Bool) async throws { let failure = IPCError(code: "setup_not_found", message: "No setup named Design work.") try await withSetupServer(result: .null, failure: failure) { _, path in let output = Mutex("") let arguments = ["setup", action] + (action == "list" ? [] : ["Design work"]) + (json ? ["--json"] : []) do { try await CLIRunner.execute(CLIParsing.parse(arguments), socketPath: path) { text in output.withLock { $0 += text } } Issue.record("Expected the rejected setup command to fail") } catch { #expect(ParcelCLI.exitCode(for: error).rawValue != 0) let message = ParcelCLI.fullMessage(for: error) #expect(message.contains(failure.code)) #expect(message.contains(failure.message)) #expect(output.withLock { $0 }.isEmpty) } } } @Test func missingServerProducesANonzeroExitAndActionableMessage() async throws { let fixture = try SocketFixture() defer { fixture.remove() } do { try await CLIRunner.execute(CLIParsing.parse(["setup", "list"]), socketPath: fixture.path) { _ in Issue.record("A missing server must not produce success output") } Issue.record("Expected the absent server to fail") } catch { #expect(ParcelCLI.exitCode(for: error).rawValue != 0) #expect(ParcelCLI.fullMessage(for: error).contains("Parcel isn't running")) } } } private actor SetupTestHandler: IPCHandler { struct Invocation: Sendable, Equatable { let command: String let args: [String] } private let result: JSONValue private let failure: IPCError? private(set) var invocations: [Invocation] = [] init(result: JSONValue, failure: IPCError?) { self.result = result self.failure = failure } func query(_ query: IPCQuery) async throws -> JSONValue { invocations.append(.init(command: "query", args: [query.rawValue])) if let failure { throw failure } return result } func run(command: String, args: [String]) async throws -> JSONValue { invocations.append(.init(command: command, args: args)) if let failure { throw failure } return result } func reloadConfig() async throws -> JSONValue { throw IPCError(code: "unexpected_command", message: "Only setup requests are expected.") } } private func withSetupServer( result: JSONValue, failure: IPCError? = nil, body: (SetupTestHandler, String) async throws -> Void ) async throws { let fixture = try SocketFixture() defer { fixture.remove() } let handler = SetupTestHandler(result: result, failure: failure) let server = try IPCServer(handler: handler, socketPath: fixture.path) try await server.start() do { try await body(handler, fixture.path) try await server.stop() } catch { do { try await server.stop() } catch { Issue.record(error) } throw error } }