示例工程 13-error-handling
13-error-handling/Tests/Ch13KitTests/LoaderTests.swift
import Testing
@testable import Ch13Kit
@Suite("错误与 Result")
struct LoaderTests {
@Test func successfulLoadReturnsDocument() throws {
let document = try DocumentLoader.load("notes.md")
#expect(document == Document(title: "notes.md", body: "hello"))
}
@Test func missingPathThrowsNotFound() {
#expect(throws: LoadError.notFound("")) {
try DocumentLoader.load("")
}
}
@Test func deniedAndCorruptedAreDistinct() {
#expect(throws: LoadError.denied("/root/secret")) {
try DocumentLoader.load("/root/secret")
}
#expect(throws: LoadError.corrupted(line: 3)) {
try DocumentLoader.load("x.bad")
}
}
@Test func resultKeepsFailureReason() {
let failure = DocumentLoader.loadResult("")
guard case .failure(let error) = failure else {
Issue.record("期望失败")
return
}
#expect(error == .notFound(""))
}
@Test func optionalOnlyKeepsPresence() {
#expect(DocumentLoader.loadOptional("") == nil)
#expect(DocumentLoader.loadOptional("ok.md")?.title == "ok.md")
}
}