Skip to content

Commit be1cf86

Browse files
authored
Merge pull request #2270 from millenomi/test-assert-crashes
TestFoundation: Add infrastructure to assert that a test should crash
2 parents 999cbc8 + b3718c0 commit be1cf86

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

TestFoundation/Utilities.swift

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -526,3 +526,38 @@ func testExpectedToFailWithCheck<T>(check: (String) -> Bool, _ test: @escaping
526526
return { _ in return { } }
527527
}
528528
}
529+
530+
extension XCTest {
531+
func assertCrashes(within block: () throws -> Void) rethrows {
532+
let childProcessEnvVariable = "NS_FOUNDATION_TEST_PERFORM_ASSERT_CRASHES_BLOCKS"
533+
let childProcessEnvVariableOnValue = "YES"
534+
535+
let isChildProcess = ProcessInfo.processInfo.environment[childProcessEnvVariable] == childProcessEnvVariableOnValue
536+
537+
if isChildProcess {
538+
try block()
539+
} else {
540+
var arguments = ProcessInfo.processInfo.arguments
541+
let process = Process()
542+
process.executableURL = URL(fileURLWithPath: arguments[0])
543+
544+
arguments.remove(at: 0)
545+
arguments.removeAll(where: { $0.hasPrefix("TestFoundation.") })
546+
arguments.append("TestFoundation." + self.name.replacingOccurrences(of: ".", with: "/"))
547+
process.arguments = arguments
548+
549+
var environment = ProcessInfo.processInfo.environment
550+
environment[childProcessEnvVariable] = childProcessEnvVariableOnValue
551+
process.environment = environment
552+
553+
do {
554+
try process.run()
555+
process.waitUntilExit()
556+
XCTAssertEqual(process.terminationReason, .uncaughtSignal, "Child process should have crashed: \(process)")
557+
} catch {
558+
XCTFail("Couldn't start child process for testing crash: \(process) - \(error)")
559+
}
560+
561+
}
562+
}
563+
}

0 commit comments

Comments
 (0)