diff --git a/Foundation/Process.swift b/Foundation/Process.swift index c89a244a92..2b20399320 100644 --- a/Foundation/Process.swift +++ b/Foundation/Process.swift @@ -386,6 +386,11 @@ open class Process: NSObject { // Dispatch the manager thread if it isn't already running Process.setup() + // Check that the process isnt run more than once + guard hasStarted == false && hasFinished == false else { + throw NSError(domain: NSCocoaErrorDomain, code: NSExecutableLoadError) + } + // Ensure that the launch path is set guard let launchPath = self.executableURL?.path else { throw NSError(domain: NSCocoaErrorDomain, code: NSFileNoSuchFileError) diff --git a/TestFoundation/TestProcess.swift b/TestFoundation/TestProcess.swift index 935a7c3735..12750d1155 100644 --- a/TestFoundation/TestProcess.swift +++ b/TestFoundation/TestProcess.swift @@ -319,15 +319,26 @@ class TestProcess : XCTestCase { XCTAssertEqual(fm.currentDirectoryPath, cwd) do { + // Check running the process twice throws an error. let process = Process() process.executableURL = xdgTestHelperURL() process.arguments = ["--exit", "0"] - process.currentDirectoryURL = URL(fileURLWithPath: "/.../_no_such_directory", isDirectory: true) - try process.run() - XCTFail("Executed \(xdgTestHelperURL().path) with invalid currentDirectoryURL") - process.terminate() + XCTAssertNoThrow(try process.run()) process.waitUntilExit() - } catch { + XCTAssertThrowsError(try process.run()) { + let nserror = ($0 as! NSError) + XCTAssertEqual(nserror.domain, NSCocoaErrorDomain) + let code = CocoaError(_nsError: nserror).code + XCTAssertEqual(code, .executableLoad) + } + } + + do { + let process = Process() + process.executableURL = xdgTestHelperURL() + process.arguments = ["--exit", "0"] + process.currentDirectoryURL = URL(fileURLWithPath: "/.../_no_such_directory", isDirectory: true) + XCTAssertThrowsError(try process.run()) } XCTAssertEqual(fm.currentDirectoryPath, cwd) @@ -336,11 +347,7 @@ class TestProcess : XCTestCase { process.executableURL = URL(fileURLWithPath: "/..", isDirectory: false) process.arguments = [] process.currentDirectoryURL = URL(fileURLWithPath: NSTemporaryDirectory()) - try process.run() - XCTFail("Somehow executed a directory!") - process.terminate() - process.waitUntilExit() - } catch { + XCTAssertThrowsError(try process.run()) } XCTAssertEqual(fm.currentDirectoryPath, cwd) fm.changeCurrentDirectoryPath(cwd)