如何解决如何在 Swift XCTest 单元测试中捕获 stdout 和 stderr?
我正在用 Swift 编写一个命令行工具。在我的单元测试中,我想测试代码输出到 stdout(然后是 stderr)。
我发现的使用 Pipe()
复制或捕获 stdout 输出的示例主要依赖于生成子进程并分配其 stdout——我不知道从哪里开始弄清楚如何处理在 XCTest 中。但我已经设法将一些开始工作的东西整合在一起,而无需产生单独的进程。
到目前为止我想出的是编译和运行,并且使用一个丑陋的 hack 来完成我需要的东西——但只是为了一次使用(如果我尝试在同一次运行中的多个测试中使用它,所有但第一次失败)。技巧是,在写入 stdout 的调用之后,我必须添加一个写入 stderr 的调用,以使数据已经发送到 stdout,然后写入我的 capturedStdout
变量。
似乎应该有更合适的方法来让它发挥作用。
这是我目前得到的:
import XCTest
final class StdoutCaptureTests: XCTestCase {
func testCapturePrint() {
let pipe = Pipe()
var capturedStdout = ""
// Setup to copy data going to stdout into capturedStdout.
setvbuf(stdout,nil,_IONBF,0)
// Assign stdout’s pointer to the pipe:
dup2(pipe.fileHandleForWriting.fileDescriptor,STDOUT_FILENO)
// A closure for receiving the data sent to stdout:
pipe.fileHandleForReading.readabilityHandler = { handle in
if let str = String(data: handle.availableData,encoding: .utf8) {
capturedStdout += str
}
}
// The subject of the test outputs to stdout:
// (In this simplified example,just print "test" to stdout.)
print("test")
// Here’s where it gets weird...
// If none of the following lines are uncommented,// the XCTAssertEqual test below will fail
// (nothing gets written to capturedStdout).
// Uncommenting the following line makes the XCTAssertEqual work:
//XCTAssert(false) // ⚠️
// (but that means the test is considered failed.)
// And this has no effect:
//XCTAssert(true) // ?
// fflush has no effect (when it gets nil as argument here,// the man(ual) page says it “flushes all open streams.”)
//fflush(nil) // ?
// But this works and lets the test pass:
//FileHandle.standardError.write("".data(using: .utf8)!) // ✅
XCTAssertEqual(capturedStdout,"test\n")
// When the above commented lines are still commented:
// ? XCTAssertEqual failed: ("") is not equal to ("test")
}
}
鉴于它在同一次运行中的后续测试方法中使用时失败,我想我可能应该在每次测试结束时进行一些清理,以在运行下一个测试方法之前恢复标准输出。
我找到的一些参考资料:
- using pipe() in Swift App to redirect stdout into a textView (only runs in simulator,not native)
- Redirect Process stdout to Apple System Log Facility in Swift
- https://www.hackingwithswift.com/forums/ios/redirecting-output-to-a-log-file-when-not-attached-to-debugger/5766
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。