Skip to content

TestFoundation: Add infrastructure to assert that a test should crash #2270

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 15, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions TestFoundation/Utilities.swift
Original file line number Diff line number Diff line change
Expand Up @@ -521,3 +521,38 @@ func testExpectedToFail<T>(_ test: @escaping (T) -> () throws -> Void, _ reason
return { _ in return { } }
}
}

extension XCTest {
func assertCrashes(within block: () throws -> Void) rethrows {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@airspeedswift This might interest you.

let childProcessEnvVariable = "NS_FOUNDATION_TEST_PERFORM_ASSERT_CRASHES_BLOCKS"
let childProcessEnvVariableOnValue = "YES"

let isChildProcess = ProcessInfo.processInfo.environment[childProcessEnvVariable] == childProcessEnvVariableOnValue

if isChildProcess {
try block()
} else {
var arguments = ProcessInfo.processInfo.arguments
let process = Process()
process.executableURL = URL(fileURLWithPath: arguments[0])

arguments.remove(at: 0)
arguments.removeAll(where: { $0.hasPrefix("TestFoundation.") })
arguments.append("TestFoundation." + self.name.replacingOccurrences(of: ".", with: "/"))
process.arguments = arguments

var environment = ProcessInfo.processInfo.environment
environment[childProcessEnvVariable] = childProcessEnvVariableOnValue
process.environment = environment

do {
try process.run()
process.waitUntilExit()
XCTAssertEqual(process.terminationReason, .uncaughtSignal, "Child process should have crashed: \(process)")
} catch {
XCTFail("Couldn't start child process for testing crash: \(process) - \(error)")
}

}
}
}